1package eu.siacs.conversations.services;
2
3import android.annotation.SuppressLint;
4import android.app.AlarmManager;
5import android.app.PendingIntent;
6import android.app.Service;
7import android.content.Context;
8import android.content.Intent;
9import android.content.SharedPreferences;
10import android.database.ContentObserver;
11import android.graphics.Bitmap;
12import android.net.ConnectivityManager;
13import android.net.NetworkInfo;
14import android.net.Uri;
15import android.os.Binder;
16import android.os.Bundle;
17import android.os.FileObserver;
18import android.os.IBinder;
19import android.os.Looper;
20import android.os.PowerManager;
21import android.os.PowerManager.WakeLock;
22import android.os.SystemClock;
23import android.preference.PreferenceManager;
24import android.provider.ContactsContract;
25import android.util.Log;
26import android.util.LruCache;
27
28import net.java.otr4j.OtrException;
29import net.java.otr4j.session.Session;
30import net.java.otr4j.session.SessionID;
31import net.java.otr4j.session.SessionImpl;
32import net.java.otr4j.session.SessionStatus;
33
34import org.openintents.openpgp.util.OpenPgpApi;
35import org.openintents.openpgp.util.OpenPgpServiceConnection;
36
37import java.math.BigInteger;
38import java.security.SecureRandom;
39import java.util.ArrayList;
40import java.util.Arrays;
41import java.util.Collection;
42import java.util.Collections;
43import java.util.Comparator;
44import java.util.Hashtable;
45import java.util.Iterator;
46import java.util.List;
47import java.util.Locale;
48import java.util.Map;
49import java.util.concurrent.CopyOnWriteArrayList;
50
51import de.duenndns.ssl.MemorizingTrustManager;
52import eu.siacs.conversations.Config;
53import eu.siacs.conversations.R;
54import eu.siacs.conversations.crypto.PgpEngine;
55import eu.siacs.conversations.crypto.axolotl.NoSessionsCreatedException;
56import eu.siacs.conversations.entities.Account;
57import eu.siacs.conversations.entities.Blockable;
58import eu.siacs.conversations.entities.Bookmark;
59import eu.siacs.conversations.entities.Contact;
60import eu.siacs.conversations.entities.Conversation;
61import eu.siacs.conversations.entities.Transferable;
62import eu.siacs.conversations.entities.TransferablePlaceholder;
63import eu.siacs.conversations.entities.Message;
64import eu.siacs.conversations.entities.MucOptions;
65import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
66import eu.siacs.conversations.generator.IqGenerator;
67import eu.siacs.conversations.generator.MessageGenerator;
68import eu.siacs.conversations.generator.PresenceGenerator;
69import eu.siacs.conversations.http.HttpConnectionManager;
70import eu.siacs.conversations.parser.IqParser;
71import eu.siacs.conversations.parser.MessageParser;
72import eu.siacs.conversations.parser.PresenceParser;
73import eu.siacs.conversations.persistance.DatabaseBackend;
74import eu.siacs.conversations.persistance.FileBackend;
75import eu.siacs.conversations.ui.UiCallback;
76import eu.siacs.conversations.utils.CryptoHelper;
77import eu.siacs.conversations.utils.ExceptionHelper;
78import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
79import eu.siacs.conversations.utils.PRNGFixes;
80import eu.siacs.conversations.utils.PhoneHelper;
81import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
82import eu.siacs.conversations.utils.Xmlns;
83import eu.siacs.conversations.xml.Element;
84import eu.siacs.conversations.xmpp.OnBindListener;
85import eu.siacs.conversations.xmpp.OnContactStatusChanged;
86import eu.siacs.conversations.xmpp.OnIqPacketReceived;
87import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
88import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
89import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
90import eu.siacs.conversations.xmpp.OnStatusChanged;
91import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
92import eu.siacs.conversations.xmpp.XmppConnection;
93import eu.siacs.conversations.xmpp.chatstate.ChatState;
94import eu.siacs.conversations.xmpp.forms.Data;
95import eu.siacs.conversations.xmpp.forms.Field;
96import eu.siacs.conversations.xmpp.jid.InvalidJidException;
97import eu.siacs.conversations.xmpp.jid.Jid;
98import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
99import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
100import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
101import eu.siacs.conversations.xmpp.pep.Avatar;
102import eu.siacs.conversations.xmpp.stanzas.IqPacket;
103import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
104import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
105import me.leolin.shortcutbadger.ShortcutBadger;
106
107public class XmppConnectionService extends Service implements OnPhoneContactsLoadedListener {
108
109 public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification";
110 public static final String ACTION_DISABLE_FOREGROUND = "disable_foreground";
111 private static final String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
112 public static final String ACTION_TRY_AGAIN = "try_again";
113 public static final String ACTION_DISABLE_ACCOUNT = "disable_account";
114 private ContentObserver contactObserver = new ContentObserver(null) {
115 @Override
116 public void onChange(boolean selfChange) {
117 super.onChange(selfChange);
118 Intent intent = new Intent(getApplicationContext(),
119 XmppConnectionService.class);
120 intent.setAction(ACTION_MERGE_PHONE_CONTACTS);
121 startService(intent);
122 }
123 };
124
125 private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor();
126 private final SerialSingleThreadExecutor mDatabaseExecutor = new SerialSingleThreadExecutor();
127
128 private final IBinder mBinder = new XmppConnectionBinder();
129 private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
130 private final FileObserver fileObserver = new FileObserver(
131 FileBackend.getConversationsImageDirectory()) {
132
133 @Override
134 public void onEvent(int event, String path) {
135 if (event == FileObserver.DELETE) {
136 markFileDeleted(path.split("\\.")[0]);
137 }
138 }
139 };
140 private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
141
142 @Override
143 public void onJinglePacketReceived(Account account, JinglePacket packet) {
144 mJingleConnectionManager.deliverPacket(account, packet);
145 }
146 };
147 private final OnBindListener mOnBindListener = new OnBindListener() {
148
149 @Override
150 public void onBind(final Account account) {
151 account.getRoster().clearPresences();
152 account.pendingConferenceJoins.clear();
153 account.pendingConferenceLeaves.clear();
154 fetchRosterFromServer(account);
155 fetchBookmarks(account);
156 sendPresence(account);
157 connectMultiModeConversations(account);
158 updateConversationUi();
159 }
160 };
161 private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
162
163 @Override
164 public void onMessageAcknowledged(Account account, String uuid) {
165 for (final Conversation conversation : getConversations()) {
166 if (conversation.getAccount() == account) {
167 Message message = conversation.findUnsentMessageWithUuid(uuid);
168 if (message != null) {
169 markMessage(message, Message.STATUS_SEND);
170 if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
171 databaseBackend.updateConversation(conversation);
172 }
173 }
174 }
175 }
176 }
177 };
178 private final IqGenerator mIqGenerator = new IqGenerator(this);
179 public DatabaseBackend databaseBackend;
180 public OnContactStatusChanged onContactStatusChanged = new OnContactStatusChanged() {
181
182 @Override
183 public void onContactStatusChanged(Contact contact, boolean online) {
184 Conversation conversation = find(getConversations(), contact);
185 if (conversation != null) {
186 if (online) {
187 conversation.endOtrIfNeeded();
188 if (contact.getPresences().size() == 1) {
189 sendUnsentMessages(conversation);
190 }
191 } else {
192 if (contact.getPresences().size() >= 1) {
193 if (conversation.hasValidOtrSession()) {
194 String otrResource = conversation.getOtrSession().getSessionID().getUserID();
195 if (!(Arrays.asList(contact.getPresences().asStringArray()).contains(otrResource))) {
196 conversation.endOtrIfNeeded();
197 }
198 }
199 } else {
200 conversation.endOtrIfNeeded();
201 }
202 }
203 }
204 }
205 };
206 private FileBackend fileBackend = new FileBackend(this);
207 private MemorizingTrustManager mMemorizingTrustManager;
208 private NotificationService mNotificationService = new NotificationService(
209 this);
210 private OnMessagePacketReceived mMessageParser = new MessageParser(this);
211 private OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
212 private IqParser mIqParser = new IqParser(this);
213 private OnIqPacketReceived mDefaultIqHandler = new OnIqPacketReceived() {
214 @Override
215 public void onIqPacketReceived(Account account, IqPacket packet) {
216 if (packet.getType() == IqPacket.TYPE.ERROR) {
217 Element error = packet.findChild("error");
218 String text = error != null ? error.findChildContent("text") : null;
219 if (text != null) {
220 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received iq error - "+text);
221 }
222 }
223 }
224 };
225 private MessageGenerator mMessageGenerator = new MessageGenerator(this);
226 private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
227 private List<Account> accounts;
228 private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
229 this);
230 private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(
231 this);
232 private AvatarService mAvatarService = new AvatarService(this);
233 private final List<String> mInProgressAvatarFetches = new ArrayList<>();
234 private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
235 private OnConversationUpdate mOnConversationUpdate = null;
236 private int convChangedListenerCount = 0;
237 private OnShowErrorToast mOnShowErrorToast = null;
238 private int showErrorToastListenerCount = 0;
239 private int unreadCount = -1;
240 private OnAccountUpdate mOnAccountUpdate = null;
241 private OnStatusChanged statusListener = new OnStatusChanged() {
242
243 @Override
244 public void onStatusChanged(Account account) {
245 XmppConnection connection = account.getXmppConnection();
246 if (mOnAccountUpdate != null) {
247 mOnAccountUpdate.onAccountUpdate();
248 }
249 if (account.getStatus() == Account.State.ONLINE) {
250 for (Conversation conversation : account.pendingConferenceLeaves) {
251 leaveMuc(conversation);
252 }
253 for (Conversation conversation : account.pendingConferenceJoins) {
254 joinMuc(conversation);
255 }
256 mMessageArchiveService.executePendingQueries(account);
257 mJingleConnectionManager.cancelInTransmission();
258 List<Conversation> conversations = getConversations();
259 for (Conversation conversation : conversations) {
260 if (conversation.getAccount() == account) {
261 conversation.startOtrIfNeeded();
262 sendUnsentMessages(conversation);
263 }
264 }
265 if (connection != null && connection.getFeatures().csi()) {
266 if (checkListeners()) {
267 Log.d(Config.LOGTAG, account.getJid().toBareJid()
268 + " sending csi//inactive");
269 connection.sendInactive();
270 } else {
271 Log.d(Config.LOGTAG, account.getJid().toBareJid()
272 + " sending csi//active");
273 connection.sendActive();
274 }
275 }
276 syncDirtyContacts(account);
277 account.getAxolotlService().publishOwnDeviceIdIfNeeded();
278 account.getAxolotlService().publishBundlesIfNeeded();
279
280 scheduleWakeUpCall(Config.PING_MAX_INTERVAL, account.getUuid().hashCode());
281 } else if (account.getStatus() == Account.State.OFFLINE) {
282 resetSendingToWaiting(account);
283 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
284 int timeToReconnect = mRandom.nextInt(50) + 10;
285 scheduleWakeUpCall(timeToReconnect,account.getUuid().hashCode());
286 }
287 } else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
288 databaseBackend.updateAccount(account);
289 reconnectAccount(account, true);
290 } else if ((account.getStatus() != Account.State.CONNECTING)
291 && (account.getStatus() != Account.State.NO_INTERNET)) {
292 if (connection != null) {
293 int next = connection.getTimeToNextAttempt();
294 Log.d(Config.LOGTAG, account.getJid().toBareJid()
295 + ": error connecting account. try again in "
296 + next + "s for the "
297 + (connection.getAttempt() + 1) + " time");
298 scheduleWakeUpCall(next,account.getUuid().hashCode());
299 }
300 }
301 getNotificationService().updateErrorNotification();
302 }
303 };
304 private int accountChangedListenerCount = 0;
305 private OnRosterUpdate mOnRosterUpdate = null;
306 private OnUpdateBlocklist mOnUpdateBlocklist = null;
307 private int updateBlocklistListenerCount = 0;
308 private int rosterChangedListenerCount = 0;
309 private OnMucRosterUpdate mOnMucRosterUpdate = null;
310 private int mucRosterChangedListenerCount = 0;
311 private SecureRandom mRandom;
312 private OpenPgpServiceConnection pgpServiceConnection;
313 private PgpEngine mPgpEngine = null;
314 private WakeLock wakeLock;
315 private PowerManager pm;
316 private LruCache<String, Bitmap> mBitmapCache;
317 private Thread mPhoneContactMergerThread;
318
319 private boolean mRestoredFromDatabase = false;
320 public boolean areMessagesInitialized() {
321 return this.mRestoredFromDatabase;
322 }
323
324 public PgpEngine getPgpEngine() {
325 if (pgpServiceConnection.isBound()) {
326 if (this.mPgpEngine == null) {
327 this.mPgpEngine = new PgpEngine(new OpenPgpApi(
328 getApplicationContext(),
329 pgpServiceConnection.getService()), this);
330 }
331 return mPgpEngine;
332 } else {
333 return null;
334 }
335
336 }
337
338 public FileBackend getFileBackend() {
339 return this.fileBackend;
340 }
341
342 public AvatarService getAvatarService() {
343 return this.mAvatarService;
344 }
345
346 public void attachLocationToConversation(final Conversation conversation,
347 final Uri uri,
348 final UiCallback<Message> callback) {
349 int encryption = conversation.getNextEncryption(forceEncryption());
350 if (encryption == Message.ENCRYPTION_PGP) {
351 encryption = Message.ENCRYPTION_DECRYPTED;
352 }
353 Message message = new Message(conversation,uri.toString(),encryption);
354 if (conversation.getNextCounterpart() != null) {
355 message.setCounterpart(conversation.getNextCounterpart());
356 }
357 if (encryption == Message.ENCRYPTION_DECRYPTED) {
358 getPgpEngine().encrypt(message, callback);
359 } else {
360 callback.success(message);
361 }
362 }
363
364 public void attachFileToConversation(final Conversation conversation,
365 final Uri uri,
366 final UiCallback<Message> callback) {
367 final Message message;
368 if (conversation.getNextEncryption(forceEncryption()) == Message.ENCRYPTION_PGP) {
369 message = new Message(conversation, "",
370 Message.ENCRYPTION_DECRYPTED);
371 } else {
372 message = new Message(conversation, "",
373 conversation.getNextEncryption(forceEncryption()));
374 }
375 message.setCounterpart(conversation.getNextCounterpart());
376 message.setType(Message.TYPE_FILE);
377 String path = getFileBackend().getOriginalPath(uri);
378 if (path!=null) {
379 message.setRelativeFilePath(path);
380 getFileBackend().updateFileParams(message);
381 if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
382 getPgpEngine().encrypt(message, callback);
383 } else {
384 callback.success(message);
385 }
386 } else {
387 mFileAddingExecutor.execute(new Runnable() {
388 @Override
389 public void run() {
390 try {
391 getFileBackend().copyFileToPrivateStorage(message, uri);
392 getFileBackend().updateFileParams(message);
393 if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
394 getPgpEngine().encrypt(message, callback);
395 } else {
396 callback.success(message);
397 }
398 } catch (FileBackend.FileCopyException e) {
399 callback.error(e.getResId(), message);
400 }
401 }
402 });
403 }
404 }
405
406 public void attachImageToConversation(final Conversation conversation,
407 final Uri uri, final UiCallback<Message> callback) {
408 final Message message;
409 if (conversation.getNextEncryption(forceEncryption()) == Message.ENCRYPTION_PGP) {
410 message = new Message(conversation, "",
411 Message.ENCRYPTION_DECRYPTED);
412 } else {
413 message = new Message(conversation, "",
414 conversation.getNextEncryption(forceEncryption()));
415 }
416 message.setCounterpart(conversation.getNextCounterpart());
417 message.setType(Message.TYPE_IMAGE);
418 mFileAddingExecutor.execute(new Runnable() {
419
420 @Override
421 public void run() {
422 try {
423 getFileBackend().copyImageToPrivateStorage(message, uri);
424 if (conversation.getNextEncryption(forceEncryption()) == Message.ENCRYPTION_PGP) {
425 getPgpEngine().encrypt(message, callback);
426 } else {
427 callback.success(message);
428 }
429 } catch (final FileBackend.FileCopyException e) {
430 callback.error(e.getResId(), message);
431 }
432 }
433 });
434 }
435
436 public Conversation find(Bookmark bookmark) {
437 return find(bookmark.getAccount(), bookmark.getJid());
438 }
439
440 public Conversation find(final Account account, final Jid jid) {
441 return find(getConversations(), account, jid);
442 }
443
444 @Override
445 public int onStartCommand(Intent intent, int flags, int startId) {
446 final String action = intent == null ? null : intent.getAction();
447 if (action != null) {
448 switch (action) {
449 case ConnectivityManager.CONNECTIVITY_ACTION:
450 if (hasInternetConnection() && Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
451 resetAllAttemptCounts(true);
452 }
453 break;
454 case ACTION_MERGE_PHONE_CONTACTS:
455 if (mRestoredFromDatabase) {
456 PhoneHelper.loadPhoneContacts(getApplicationContext(),
457 new CopyOnWriteArrayList<Bundle>(),
458 this);
459 }
460 return START_STICKY;
461 case Intent.ACTION_SHUTDOWN:
462 logoutAndSave();
463 return START_NOT_STICKY;
464 case ACTION_CLEAR_NOTIFICATION:
465 mNotificationService.clear();
466 break;
467 case ACTION_DISABLE_FOREGROUND:
468 getPreferences().edit().putBoolean("keep_foreground_service",false).commit();
469 toggleForegroundService();
470 break;
471 case ACTION_TRY_AGAIN:
472 resetAllAttemptCounts(false);
473 break;
474 case ACTION_DISABLE_ACCOUNT:
475 try {
476 String jid = intent.getStringExtra("account");
477 Account account = jid == null ? null : findAccountByJid(Jid.fromString(jid));
478 if (account != null) {
479 account.setOption(Account.OPTION_DISABLED,true);
480 updateAccount(account);
481 }
482 } catch (final InvalidJidException ignored) {
483 break;
484 }
485 break;
486 }
487 }
488 this.wakeLock.acquire();
489
490 for (Account account : accounts) {
491 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
492 if (!hasInternetConnection()) {
493 account.setStatus(Account.State.NO_INTERNET);
494 if (statusListener != null) {
495 statusListener.onStatusChanged(account);
496 }
497 } else {
498 if (account.getStatus() == Account.State.NO_INTERNET) {
499 account.setStatus(Account.State.OFFLINE);
500 if (statusListener != null) {
501 statusListener.onStatusChanged(account);
502 }
503 }
504 if (account.getStatus() == Account.State.ONLINE) {
505 long lastReceived = account.getXmppConnection().getLastPacketReceived();
506 long lastSent = account.getXmppConnection().getLastPingSent();
507 long pingInterval = "ui".equals(action) ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
508 long msToNextPing = (Math.max(lastReceived,lastSent) + pingInterval) - SystemClock.elapsedRealtime();
509 long pingTimeoutIn = (lastSent + Config.PING_TIMEOUT * 1000) - SystemClock.elapsedRealtime();
510 if (lastSent > lastReceived) {
511 if (pingTimeoutIn < 0) {
512 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": ping timeout");
513 this.reconnectAccount(account, true);
514 } else {
515 int secs = (int) (pingTimeoutIn / 1000);
516 this.scheduleWakeUpCall(secs,account.getUuid().hashCode());
517 }
518 } else if (msToNextPing <= 0) {
519 account.getXmppConnection().sendPing();
520 Log.d(Config.LOGTAG, account.getJid().toBareJid()+" send ping");
521 this.scheduleWakeUpCall(Config.PING_TIMEOUT,account.getUuid().hashCode());
522 } else {
523 this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
524 }
525 } else if (account.getStatus() == Account.State.OFFLINE) {
526 reconnectAccount(account,true);
527 } else if (account.getStatus() == Account.State.CONNECTING) {
528 long timeout = Config.CONNECT_TIMEOUT - ((SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000);
529 if (timeout < 0) {
530 Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting");
531 reconnectAccount(account, true);
532 } else {
533 scheduleWakeUpCall((int) timeout,account.getUuid().hashCode());
534 }
535 } else {
536 if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
537 reconnectAccount(account, true);
538 }
539 }
540
541 }
542 if (mOnAccountUpdate != null) {
543 mOnAccountUpdate.onAccountUpdate();
544 }
545 }
546 }
547 /*PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
548 if (!pm.isScreenOn()) {
549 removeStaleListeners();
550 }*/
551 if (wakeLock.isHeld()) {
552 try {
553 wakeLock.release();
554 } catch (final RuntimeException ignored) {
555 }
556 }
557 return START_STICKY;
558 }
559
560 private void resetAllAttemptCounts(boolean reallyAll) {
561 Log.d(Config.LOGTAG,"resetting all attepmt counts");
562 for(Account account : accounts) {
563 if (account.hasErrorStatus() || reallyAll) {
564 final XmppConnection connection = account.getXmppConnection();
565 if (connection != null) {
566 connection.resetAttemptCount();
567 }
568 }
569 }
570 }
571
572 public boolean hasInternetConnection() {
573 ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
574 .getSystemService(Context.CONNECTIVITY_SERVICE);
575 NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
576 return activeNetwork != null && activeNetwork.isConnected();
577 }
578
579 @SuppressLint("TrulyRandom")
580 @Override
581 public void onCreate() {
582 ExceptionHelper.init(getApplicationContext());
583 PRNGFixes.apply();
584 this.mRandom = new SecureRandom();
585 updateMemorizingTrustmanager();
586 final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
587 final int cacheSize = maxMemory / 8;
588 this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
589 @Override
590 protected int sizeOf(final String key, final Bitmap bitmap) {
591 return bitmap.getByteCount() / 1024;
592 }
593 };
594
595 this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
596 this.accounts = databaseBackend.getAccounts();
597
598 for (final Account account : this.accounts) {
599 account.initAccountServices(this);
600 }
601 restoreFromDatabase();
602
603 getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
604 this.fileObserver.startWatching();
605 this.pgpServiceConnection = new OpenPgpServiceConnection(getApplicationContext(), "org.sufficientlysecure.keychain");
606 this.pgpServiceConnection.bindToService();
607
608 this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
609 this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"XmppConnectionService");
610 toggleForegroundService();
611 updateUnreadCountBadge();
612 }
613
614 public void toggleForegroundService() {
615 if (getPreferences().getBoolean("keep_foreground_service",false)) {
616 startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
617 } else {
618 stopForeground(true);
619 }
620 }
621
622 @Override
623 public void onTaskRemoved(final Intent rootIntent) {
624 super.onTaskRemoved(rootIntent);
625 if (!getPreferences().getBoolean("keep_foreground_service",false)) {
626 this.logoutAndSave();
627 }
628 }
629
630 private void logoutAndSave() {
631 for (final Account account : accounts) {
632 databaseBackend.writeRoster(account.getRoster());
633 if (account.getXmppConnection() != null) {
634 disconnect(account, false);
635 }
636 }
637 Context context = getApplicationContext();
638 AlarmManager alarmManager = (AlarmManager) context
639 .getSystemService(Context.ALARM_SERVICE);
640 Intent intent = new Intent(context, EventReceiver.class);
641 alarmManager.cancel(PendingIntent.getBroadcast(context, 0, intent, 0));
642 Log.d(Config.LOGTAG, "good bye");
643 stopSelf();
644 }
645
646 protected void scheduleWakeUpCall(int seconds, int requestCode) {
647 final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
648
649 Context context = getApplicationContext();
650 AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
651
652 Intent intent = new Intent(context, EventReceiver.class);
653 intent.setAction("ping");
654 PendingIntent alarmIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0);
655 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, alarmIntent);
656 }
657
658 public XmppConnection createConnection(final Account account) {
659 final SharedPreferences sharedPref = getPreferences();
660 account.setResource(sharedPref.getString("resource", "mobile")
661 .toLowerCase(Locale.getDefault()));
662 final XmppConnection connection = new XmppConnection(account, this);
663 connection.setOnMessagePacketReceivedListener(this.mMessageParser);
664 connection.setOnStatusChangedListener(this.statusListener);
665 connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
666 connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
667 connection.setOnJinglePacketReceivedListener(this.jingleListener);
668 connection.setOnBindListener(this.mOnBindListener);
669 connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
670 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
671 return connection;
672 }
673
674 public void sendChatState(Conversation conversation) {
675 if (sendChatStates()) {
676 MessagePacket packet = mMessageGenerator.generateChatState(conversation);
677 sendMessagePacket(conversation.getAccount(), packet);
678 }
679 }
680
681 private void sendFileMessage(final Message message) {
682 Log.d(Config.LOGTAG, "send file message");
683 final Account account = message.getConversation().getAccount();
684 final XmppConnection connection = account.getXmppConnection();
685 if (connection != null && connection.getFeatures().httpUpload()) {
686 mHttpConnectionManager.createNewUploadConnection(message);
687 } else {
688 mJingleConnectionManager.createNewConnection(message);
689 }
690 }
691
692 public void sendMessage(final Message message) {
693 sendMessage(message, false);
694 }
695
696 private void sendMessage(final Message message, final boolean resend) {
697 final Account account = message.getConversation().getAccount();
698 final Conversation conversation = message.getConversation();
699 account.deactivateGracePeriod();
700 MessagePacket packet = null;
701 boolean saveInDb = true;
702 message.setStatus(Message.STATUS_WAITING);
703
704 if (!resend && message.getEncryption() != Message.ENCRYPTION_OTR) {
705 message.getConversation().endOtrIfNeeded();
706 message.getConversation().findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR,
707 new Conversation.OnMessageFound() {
708 @Override
709 public void onMessageFound(Message message) {
710 markMessage(message,Message.STATUS_SEND_FAILED);
711 }
712 });
713 }
714
715 if (account.isOnlineAndConnected()) {
716 switch (message.getEncryption()) {
717 case Message.ENCRYPTION_NONE:
718 if (message.needsUploading()) {
719 if (account.httpUploadAvailable() || message.fixCounterpart()) {
720 this.sendFileMessage(message);
721 } else {
722 break;
723 }
724 } else {
725 packet = mMessageGenerator.generateChat(message,resend);
726 }
727 break;
728 case Message.ENCRYPTION_PGP:
729 case Message.ENCRYPTION_DECRYPTED:
730 if (message.needsUploading()) {
731 if (account.httpUploadAvailable() || message.fixCounterpart()) {
732 this.sendFileMessage(message);
733 } else {
734 break;
735 }
736 } else {
737 packet = mMessageGenerator.generatePgpChat(message,resend);
738 }
739 break;
740 case Message.ENCRYPTION_OTR:
741 SessionImpl otrSession = conversation.getOtrSession();
742 if (otrSession != null && otrSession.getSessionStatus() == SessionStatus.ENCRYPTED) {
743 try {
744 message.setCounterpart(Jid.fromSessionID(otrSession.getSessionID()));
745 } catch (InvalidJidException e) {
746 break;
747 }
748 if (message.needsUploading()) {
749 mJingleConnectionManager.createNewConnection(message);
750 } else {
751 packet = mMessageGenerator.generateOtrChat(message,resend);
752 }
753 } else if (otrSession == null) {
754 if (message.fixCounterpart()) {
755 conversation.startOtrSession(message.getCounterpart().getResourcepart(), true);
756 } else {
757 break;
758 }
759 }
760 break;
761 case Message.ENCRYPTION_AXOLOTL:
762 message.setStatus(Message.STATUS_WAITING);
763 account.getAxolotlService().sendMessage(message);
764 break;
765
766 }
767 if (packet != null) {
768 if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
769 message.setStatus(Message.STATUS_UNSEND);
770 } else {
771 message.setStatus(Message.STATUS_SEND);
772 }
773 }
774 } else {
775 switch(message.getEncryption()) {
776 case Message.ENCRYPTION_DECRYPTED:
777 if (!message.needsUploading()) {
778 String pgpBody = message.getEncryptedBody();
779 String decryptedBody = message.getBody();
780 message.setBody(pgpBody);
781 message.setEncryption(Message.ENCRYPTION_PGP);
782 databaseBackend.createMessage(message);
783 saveInDb = false;
784 message.setBody(decryptedBody);
785 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
786 }
787 break;
788 case Message.ENCRYPTION_OTR:
789 if (!conversation.hasValidOtrSession() && message.getCounterpart() != null) {
790 conversation.startOtrSession(message.getCounterpart().getResourcepart(), false);
791 }
792 break;
793 }
794 }
795
796 if (resend) {
797 if (packet != null) {
798 if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
799 markMessage(message,Message.STATUS_UNSEND);
800 } else {
801 markMessage(message,Message.STATUS_SEND);
802 }
803 }
804 } else {
805 conversation.add(message);
806 if (saveInDb && (message.getEncryption() == Message.ENCRYPTION_NONE || saveEncryptedMessages())) {
807 databaseBackend.createMessage(message);
808 }
809 updateConversationUi();
810 }
811 if (packet != null) {
812 if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
813 if (this.sendChatStates()) {
814 packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
815 }
816 }
817 sendMessagePacket(account, packet);
818 }
819 }
820
821 private void sendUnsentMessages(final Conversation conversation) {
822 conversation.findWaitingMessages(new Conversation.OnMessageFound() {
823
824 @Override
825 public void onMessageFound(Message message) {
826 resendMessage(message);
827 }
828 });
829 }
830
831 public void resendMessage(final Message message) {
832 sendMessage(message, true);
833 }
834
835 public void fetchRosterFromServer(final Account account) {
836 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
837 if (!"".equals(account.getRosterVersion())) {
838 Log.d(Config.LOGTAG, account.getJid().toBareJid()
839 + ": fetching roster version " + account.getRosterVersion());
840 } else {
841 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
842 }
843 iqPacket.query(Xmlns.ROSTER).setAttribute("ver",account.getRosterVersion());
844 sendIqPacket(account,iqPacket,mIqParser);
845 }
846
847 public void fetchBookmarks(final Account account) {
848 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
849 final Element query = iqPacket.query("jabber:iq:private");
850 query.addChild("storage", "storage:bookmarks");
851 final OnIqPacketReceived callback = new OnIqPacketReceived() {
852
853 @Override
854 public void onIqPacketReceived(final Account account, final IqPacket packet) {
855 final Element query = packet.query();
856 final List<Bookmark> bookmarks = new CopyOnWriteArrayList<>();
857 final Element storage = query.findChild("storage",
858 "storage:bookmarks");
859 if (storage != null) {
860 for (final Element item : storage.getChildren()) {
861 if (item.getName().equals("conference")) {
862 final Bookmark bookmark = Bookmark.parse(item, account);
863 bookmarks.add(bookmark);
864 Conversation conversation = find(bookmark);
865 if (conversation != null) {
866 conversation.setBookmark(bookmark);
867 } else if (bookmark.autojoin() && bookmark.getJid() != null) {
868 conversation = findOrCreateConversation(
869 account, bookmark.getJid(), true);
870 conversation.setBookmark(bookmark);
871 joinMuc(conversation);
872 }
873 }
874 }
875 }
876 account.setBookmarks(bookmarks);
877 }
878 };
879 sendIqPacket(account, iqPacket, callback);
880 }
881
882 public void pushBookmarks(Account account) {
883 IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
884 Element query = iqPacket.query("jabber:iq:private");
885 Element storage = query.addChild("storage", "storage:bookmarks");
886 for (Bookmark bookmark : account.getBookmarks()) {
887 storage.addChild(bookmark);
888 }
889 sendIqPacket(account, iqPacket, mDefaultIqHandler);
890 }
891
892 public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
893 if (mPhoneContactMergerThread != null) {
894 mPhoneContactMergerThread.interrupt();
895 }
896 mPhoneContactMergerThread = new Thread(new Runnable() {
897 @Override
898 public void run() {
899 Log.d(Config.LOGTAG,"start merging phone contacts with roster");
900 for (Account account : accounts) {
901 List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
902 for (Bundle phoneContact : phoneContacts) {
903 if (Thread.interrupted()) {
904 Log.d(Config.LOGTAG,"interrupted merging phone contacts");
905 return;
906 }
907 Jid jid;
908 try {
909 jid = Jid.fromString(phoneContact.getString("jid"));
910 } catch (final InvalidJidException e) {
911 continue;
912 }
913 final Contact contact = account.getRoster().getContact(jid);
914 String systemAccount = phoneContact.getInt("phoneid")
915 + "#"
916 + phoneContact.getString("lookup");
917 contact.setSystemAccount(systemAccount);
918 if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
919 getAvatarService().clear(contact);
920 }
921 contact.setSystemName(phoneContact.getString("displayname"));
922 withSystemAccounts.remove(contact);
923 }
924 for(Contact contact : withSystemAccounts) {
925 contact.setSystemAccount(null);
926 contact.setSystemName(null);
927 if (contact.setPhotoUri(null)) {
928 getAvatarService().clear(contact);
929 }
930 }
931 }
932 Log.d(Config.LOGTAG,"finished merging phone contacts");
933 updateAccountUi();
934 }
935 });
936 mPhoneContactMergerThread.start();
937 }
938
939 private void restoreFromDatabase() {
940 synchronized (this.conversations) {
941 final Map<String, Account> accountLookupTable = new Hashtable<>();
942 for (Account account : this.accounts) {
943 accountLookupTable.put(account.getUuid(), account);
944 }
945 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
946 for (Conversation conversation : this.conversations) {
947 Account account = accountLookupTable.get(conversation.getAccountUuid());
948 conversation.setAccount(account);
949 }
950 Runnable runnable =new Runnable() {
951 @Override
952 public void run() {
953 Log.d(Config.LOGTAG,"restoring roster");
954 for(Account account : accounts) {
955 databaseBackend.readRoster(account.getRoster());
956 }
957 getBitmapCache().evictAll();
958 Looper.prepare();
959 PhoneHelper.loadPhoneContacts(getApplicationContext(),
960 new CopyOnWriteArrayList<Bundle>(),
961 XmppConnectionService.this);
962 Log.d(Config.LOGTAG,"restoring messages");
963 for (Conversation conversation : conversations) {
964 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
965 checkDeletedFiles(conversation);
966 }
967 mRestoredFromDatabase = true;
968 Log.d(Config.LOGTAG,"restored all messages");
969 updateConversationUi();
970 }
971 };
972 mDatabaseExecutor.execute(runnable);
973 }
974 }
975
976 public List<Conversation> getConversations() {
977 return this.conversations;
978 }
979
980 private void checkDeletedFiles(Conversation conversation) {
981 conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
982
983 @Override
984 public void onMessageFound(Message message) {
985 if (!getFileBackend().isFileAvailable(message)) {
986 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
987 }
988 }
989 });
990 }
991
992 private void markFileDeleted(String uuid) {
993 for (Conversation conversation : getConversations()) {
994 Message message = conversation.findMessageWithFileAndUuid(uuid);
995 if (message != null) {
996 if (!getFileBackend().isFileAvailable(message)) {
997 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
998 updateConversationUi();
999 }
1000 return;
1001 }
1002 }
1003 }
1004
1005 public void populateWithOrderedConversations(final List<Conversation> list) {
1006 populateWithOrderedConversations(list, true);
1007 }
1008
1009 public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1010 list.clear();
1011 if (includeNoFileUpload) {
1012 list.addAll(getConversations());
1013 } else {
1014 for (Conversation conversation : getConversations()) {
1015 if (conversation.getMode() == Conversation.MODE_SINGLE
1016 || conversation.getAccount().httpUploadAvailable()) {
1017 list.add(conversation);
1018 }
1019 }
1020 }
1021 Collections.sort(list, new Comparator<Conversation>() {
1022 @Override
1023 public int compare(Conversation lhs, Conversation rhs) {
1024 Message left = lhs.getLatestMessage();
1025 Message right = rhs.getLatestMessage();
1026 if (left.getTimeSent() > right.getTimeSent()) {
1027 return -1;
1028 } else if (left.getTimeSent() < right.getTimeSent()) {
1029 return 1;
1030 } else {
1031 return 0;
1032 }
1033 }
1034 });
1035 }
1036
1037 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1038 Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1039 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation,callback)) {
1040 return;
1041 }
1042 Runnable runnable = new Runnable() {
1043 @Override
1044 public void run() {
1045 final Account account = conversation.getAccount();
1046 List<Message> messages = databaseBackend.getMessages(conversation, 50,timestamp);
1047 if (messages.size() > 0) {
1048 conversation.addAll(0, messages);
1049 checkDeletedFiles(conversation);
1050 callback.onMoreMessagesLoaded(messages.size(), conversation);
1051 } else if (conversation.hasMessagesLeftOnServer()
1052 && account.isOnlineAndConnected()
1053 && account.getXmppConnection().getFeatures().mam()) {
1054 MessageArchiveService.Query query = getMessageArchiveService().query(conversation,0,timestamp - 1);
1055 if (query != null) {
1056 query.setCallback(callback);
1057 }
1058 callback.informUser(R.string.fetching_history_from_server);
1059 }
1060 }
1061 };
1062 mDatabaseExecutor.execute(runnable);
1063 }
1064
1065 public List<Account> getAccounts() {
1066 return this.accounts;
1067 }
1068
1069 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1070 for (final Conversation conversation : haystack) {
1071 if (conversation.getContact() == contact) {
1072 return conversation;
1073 }
1074 }
1075 return null;
1076 }
1077
1078 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1079 if (jid == null) {
1080 return null;
1081 }
1082 for (final Conversation conversation : haystack) {
1083 if ((account == null || conversation.getAccount() == account)
1084 && (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1085 return conversation;
1086 }
1087 }
1088 return null;
1089 }
1090
1091 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1092 return this.findOrCreateConversation(account, jid, muc, null);
1093 }
1094
1095 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1096 synchronized (this.conversations) {
1097 Conversation conversation = find(account, jid);
1098 if (conversation != null) {
1099 return conversation;
1100 }
1101 conversation = databaseBackend.findConversation(account, jid);
1102 if (conversation != null) {
1103 conversation.setStatus(Conversation.STATUS_AVAILABLE);
1104 conversation.setAccount(account);
1105 if (muc) {
1106 conversation.setMode(Conversation.MODE_MULTI);
1107 conversation.setContactJid(jid);
1108 } else {
1109 conversation.setMode(Conversation.MODE_SINGLE);
1110 conversation.setContactJid(jid.toBareJid());
1111 }
1112 conversation.setNextEncryption(-1);
1113 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1114 this.databaseBackend.updateConversation(conversation);
1115 } else {
1116 String conversationName;
1117 Contact contact = account.getRoster().getContact(jid);
1118 if (contact != null) {
1119 conversationName = contact.getDisplayName();
1120 } else {
1121 conversationName = jid.getLocalpart();
1122 }
1123 if (muc) {
1124 conversation = new Conversation(conversationName, account, jid,
1125 Conversation.MODE_MULTI);
1126 } else {
1127 conversation = new Conversation(conversationName, account, jid.toBareJid(),
1128 Conversation.MODE_SINGLE);
1129 }
1130 this.databaseBackend.createConversation(conversation);
1131 }
1132 if (account.getXmppConnection() != null
1133 && account.getXmppConnection().getFeatures().mam()
1134 && !muc) {
1135 if (query == null) {
1136 this.mMessageArchiveService.query(conversation);
1137 } else {
1138 if (query.getConversation() == null) {
1139 this.mMessageArchiveService.query(conversation, query.getStart());
1140 }
1141 }
1142 }
1143 checkDeletedFiles(conversation);
1144 this.conversations.add(conversation);
1145 updateConversationUi();
1146 return conversation;
1147 }
1148 }
1149
1150 public void archiveConversation(Conversation conversation) {
1151 getNotificationService().clear(conversation);
1152 conversation.setStatus(Conversation.STATUS_ARCHIVED);
1153 conversation.setNextEncryption(-1);
1154 synchronized (this.conversations) {
1155 if (conversation.getMode() == Conversation.MODE_MULTI) {
1156 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1157 Bookmark bookmark = conversation.getBookmark();
1158 if (bookmark != null && bookmark.autojoin()) {
1159 bookmark.setAutojoin(false);
1160 pushBookmarks(bookmark.getAccount());
1161 }
1162 }
1163 leaveMuc(conversation);
1164 } else {
1165 conversation.endOtrIfNeeded();
1166 }
1167 this.databaseBackend.updateConversation(conversation);
1168 this.conversations.remove(conversation);
1169 updateConversationUi();
1170 }
1171 }
1172
1173 public void createAccount(final Account account) {
1174 account.initAccountServices(this);
1175 databaseBackend.createAccount(account);
1176 this.accounts.add(account);
1177 this.reconnectAccountInBackground(account);
1178 updateAccountUi();
1179 }
1180
1181 public void updateAccount(final Account account) {
1182 this.statusListener.onStatusChanged(account);
1183 databaseBackend.updateAccount(account);
1184 reconnectAccount(account, false);
1185 updateAccountUi();
1186 getNotificationService().updateErrorNotification();
1187 }
1188
1189 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1190 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1191 sendIqPacket(account, iq, new OnIqPacketReceived() {
1192 @Override
1193 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1194 if (packet.getType() == IqPacket.TYPE.RESULT) {
1195 account.setPassword(newPassword);
1196 databaseBackend.updateAccount(account);
1197 callback.onPasswordChangeSucceeded();
1198 } else {
1199 callback.onPasswordChangeFailed();
1200 }
1201 }
1202 });
1203 }
1204
1205 public void deleteAccount(final Account account) {
1206 synchronized (this.conversations) {
1207 for (final Conversation conversation : conversations) {
1208 if (conversation.getAccount() == account) {
1209 if (conversation.getMode() == Conversation.MODE_MULTI) {
1210 leaveMuc(conversation);
1211 } else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1212 conversation.endOtrIfNeeded();
1213 }
1214 conversations.remove(conversation);
1215 }
1216 }
1217 if (account.getXmppConnection() != null) {
1218 this.disconnect(account, true);
1219 }
1220 databaseBackend.deleteAccount(account);
1221 this.accounts.remove(account);
1222 updateAccountUi();
1223 getNotificationService().updateErrorNotification();
1224 }
1225 }
1226
1227 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1228 synchronized (this) {
1229 if (checkListeners()) {
1230 switchToForeground();
1231 }
1232 this.mOnConversationUpdate = listener;
1233 this.mNotificationService.setIsInForeground(true);
1234 if (this.convChangedListenerCount < 2) {
1235 this.convChangedListenerCount++;
1236 }
1237 }
1238 }
1239
1240 public void removeOnConversationListChangedListener() {
1241 synchronized (this) {
1242 this.convChangedListenerCount--;
1243 if (this.convChangedListenerCount <= 0) {
1244 this.convChangedListenerCount = 0;
1245 this.mOnConversationUpdate = null;
1246 this.mNotificationService.setIsInForeground(false);
1247 if (checkListeners()) {
1248 switchToBackground();
1249 }
1250 }
1251 }
1252 }
1253
1254 public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1255 synchronized (this) {
1256 if (checkListeners()) {
1257 switchToForeground();
1258 }
1259 this.mOnShowErrorToast = onShowErrorToast;
1260 if (this.showErrorToastListenerCount < 2) {
1261 this.showErrorToastListenerCount++;
1262 }
1263 }
1264 this.mOnShowErrorToast = onShowErrorToast;
1265 }
1266
1267 public void removeOnShowErrorToastListener() {
1268 synchronized (this) {
1269 this.showErrorToastListenerCount--;
1270 if (this.showErrorToastListenerCount <= 0) {
1271 this.showErrorToastListenerCount = 0;
1272 this.mOnShowErrorToast = null;
1273 if (checkListeners()) {
1274 switchToBackground();
1275 }
1276 }
1277 }
1278 }
1279
1280 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1281 synchronized (this) {
1282 if (checkListeners()) {
1283 switchToForeground();
1284 }
1285 this.mOnAccountUpdate = listener;
1286 if (this.accountChangedListenerCount < 2) {
1287 this.accountChangedListenerCount++;
1288 }
1289 }
1290 }
1291
1292 public void removeOnAccountListChangedListener() {
1293 synchronized (this) {
1294 this.accountChangedListenerCount--;
1295 if (this.accountChangedListenerCount <= 0) {
1296 this.mOnAccountUpdate = null;
1297 this.accountChangedListenerCount = 0;
1298 if (checkListeners()) {
1299 switchToBackground();
1300 }
1301 }
1302 }
1303 }
1304
1305 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1306 synchronized (this) {
1307 if (checkListeners()) {
1308 switchToForeground();
1309 }
1310 this.mOnRosterUpdate = listener;
1311 if (this.rosterChangedListenerCount < 2) {
1312 this.rosterChangedListenerCount++;
1313 }
1314 }
1315 }
1316
1317 public void removeOnRosterUpdateListener() {
1318 synchronized (this) {
1319 this.rosterChangedListenerCount--;
1320 if (this.rosterChangedListenerCount <= 0) {
1321 this.rosterChangedListenerCount = 0;
1322 this.mOnRosterUpdate = null;
1323 if (checkListeners()) {
1324 switchToBackground();
1325 }
1326 }
1327 }
1328 }
1329
1330 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1331 synchronized (this) {
1332 if (checkListeners()) {
1333 switchToForeground();
1334 }
1335 this.mOnUpdateBlocklist = listener;
1336 if (this.updateBlocklistListenerCount < 2) {
1337 this.updateBlocklistListenerCount++;
1338 }
1339 }
1340 }
1341
1342 public void removeOnUpdateBlocklistListener() {
1343 synchronized (this) {
1344 this.updateBlocklistListenerCount--;
1345 if (this.updateBlocklistListenerCount <= 0) {
1346 this.updateBlocklistListenerCount = 0;
1347 this.mOnUpdateBlocklist = null;
1348 if (checkListeners()) {
1349 switchToBackground();
1350 }
1351 }
1352 }
1353 }
1354
1355 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1356 synchronized (this) {
1357 if (checkListeners()) {
1358 switchToForeground();
1359 }
1360 this.mOnMucRosterUpdate = listener;
1361 if (this.mucRosterChangedListenerCount < 2) {
1362 this.mucRosterChangedListenerCount++;
1363 }
1364 }
1365 }
1366
1367 public void removeOnMucRosterUpdateListener() {
1368 synchronized (this) {
1369 this.mucRosterChangedListenerCount--;
1370 if (this.mucRosterChangedListenerCount <= 0) {
1371 this.mucRosterChangedListenerCount = 0;
1372 this.mOnMucRosterUpdate = null;
1373 if (checkListeners()) {
1374 switchToBackground();
1375 }
1376 }
1377 }
1378 }
1379
1380 private boolean checkListeners() {
1381 return (this.mOnAccountUpdate == null
1382 && this.mOnConversationUpdate == null
1383 && this.mOnRosterUpdate == null
1384 && this.mOnUpdateBlocklist == null
1385 && this.mOnShowErrorToast == null);
1386 }
1387
1388 private void switchToForeground() {
1389 for (Account account : getAccounts()) {
1390 if (account.getStatus() == Account.State.ONLINE) {
1391 XmppConnection connection = account.getXmppConnection();
1392 if (connection != null && connection.getFeatures().csi()) {
1393 connection.sendActive();
1394 }
1395 }
1396 }
1397 Log.d(Config.LOGTAG, "app switched into foreground");
1398 }
1399
1400 private void switchToBackground() {
1401 for (Account account : getAccounts()) {
1402 if (account.getStatus() == Account.State.ONLINE) {
1403 XmppConnection connection = account.getXmppConnection();
1404 if (connection != null && connection.getFeatures().csi()) {
1405 connection.sendInactive();
1406 }
1407 }
1408 }
1409 for(Conversation conversation : getConversations()) {
1410 conversation.setIncomingChatState(ChatState.ACTIVE);
1411 }
1412 this.mNotificationService.setIsInForeground(false);
1413 Log.d(Config.LOGTAG, "app switched into background");
1414 }
1415
1416 private void connectMultiModeConversations(Account account) {
1417 List<Conversation> conversations = getConversations();
1418 for (Conversation conversation : conversations) {
1419 if ((conversation.getMode() == Conversation.MODE_MULTI)
1420 && (conversation.getAccount() == account)) {
1421 conversation.resetMucOptions();
1422 joinMuc(conversation);
1423 }
1424 }
1425 }
1426
1427 public void joinMuc(Conversation conversation) {
1428 Account account = conversation.getAccount();
1429 account.pendingConferenceJoins.remove(conversation);
1430 account.pendingConferenceLeaves.remove(conversation);
1431 if (account.getStatus() == Account.State.ONLINE) {
1432 final String nick = conversation.getMucOptions().getProposedNick();
1433 final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1434 if (joinJid == null) {
1435 return; //safety net
1436 }
1437 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1438 PresencePacket packet = new PresencePacket();
1439 packet.setFrom(conversation.getAccount().getJid());
1440 packet.setTo(joinJid);
1441 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1442 if (conversation.getMucOptions().getPassword() != null) {
1443 x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1444 }
1445 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1446 String sig = account.getPgpSignature();
1447 if (sig != null) {
1448 packet.addChild("status").setContent("online");
1449 packet.addChild("x", "jabber:x:signed").setContent(sig);
1450 }
1451 sendPresencePacket(account, packet);
1452 fetchConferenceConfiguration(conversation);
1453 if (!joinJid.equals(conversation.getJid())) {
1454 conversation.setContactJid(joinJid);
1455 databaseBackend.updateConversation(conversation);
1456 }
1457 conversation.setHasMessagesLeftOnServer(false);
1458 } else {
1459 account.pendingConferenceJoins.add(conversation);
1460 }
1461 }
1462
1463 public void providePasswordForMuc(Conversation conversation, String password) {
1464 if (conversation.getMode() == Conversation.MODE_MULTI) {
1465 conversation.getMucOptions().setPassword(password);
1466 if (conversation.getBookmark() != null) {
1467 conversation.getBookmark().setAutojoin(true);
1468 pushBookmarks(conversation.getAccount());
1469 }
1470 databaseBackend.updateConversation(conversation);
1471 joinMuc(conversation);
1472 }
1473 }
1474
1475 public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1476 final MucOptions options = conversation.getMucOptions();
1477 final Jid joinJid = options.createJoinJid(nick);
1478 if (options.online()) {
1479 Account account = conversation.getAccount();
1480 options.setOnRenameListener(new OnRenameListener() {
1481
1482 @Override
1483 public void onSuccess() {
1484 conversation.setContactJid(joinJid);
1485 databaseBackend.updateConversation(conversation);
1486 Bookmark bookmark = conversation.getBookmark();
1487 if (bookmark != null) {
1488 bookmark.setNick(nick);
1489 pushBookmarks(bookmark.getAccount());
1490 }
1491 callback.success(conversation);
1492 }
1493
1494 @Override
1495 public void onFailure() {
1496 callback.error(R.string.nick_in_use, conversation);
1497 }
1498 });
1499
1500 PresencePacket packet = new PresencePacket();
1501 packet.setTo(joinJid);
1502 packet.setFrom(conversation.getAccount().getJid());
1503
1504 String sig = account.getPgpSignature();
1505 if (sig != null) {
1506 packet.addChild("status").setContent("online");
1507 packet.addChild("x", "jabber:x:signed").setContent(sig);
1508 }
1509 sendPresencePacket(account, packet);
1510 } else {
1511 conversation.setContactJid(joinJid);
1512 databaseBackend.updateConversation(conversation);
1513 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1514 Bookmark bookmark = conversation.getBookmark();
1515 if (bookmark != null) {
1516 bookmark.setNick(nick);
1517 pushBookmarks(bookmark.getAccount());
1518 }
1519 joinMuc(conversation);
1520 }
1521 }
1522 }
1523
1524 public void leaveMuc(Conversation conversation) {
1525 Account account = conversation.getAccount();
1526 account.pendingConferenceJoins.remove(conversation);
1527 account.pendingConferenceLeaves.remove(conversation);
1528 if (account.getStatus() == Account.State.ONLINE) {
1529 PresencePacket packet = new PresencePacket();
1530 packet.setTo(conversation.getJid());
1531 packet.setFrom(conversation.getAccount().getJid());
1532 packet.setAttribute("type", "unavailable");
1533 sendPresencePacket(conversation.getAccount(), packet);
1534 conversation.getMucOptions().setOffline();
1535 conversation.deregisterWithBookmark();
1536 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1537 + ": leaving muc " + conversation.getJid());
1538 } else {
1539 account.pendingConferenceLeaves.add(conversation);
1540 }
1541 }
1542
1543 private String findConferenceServer(final Account account) {
1544 String server;
1545 if (account.getXmppConnection() != null) {
1546 server = account.getXmppConnection().getMucServer();
1547 if (server != null) {
1548 return server;
1549 }
1550 }
1551 for (Account other : getAccounts()) {
1552 if (other != account && other.getXmppConnection() != null) {
1553 server = other.getXmppConnection().getMucServer();
1554 if (server != null) {
1555 return server;
1556 }
1557 }
1558 }
1559 return null;
1560 }
1561
1562 public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1563 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1564 if (account.getStatus() == Account.State.ONLINE) {
1565 try {
1566 String server = findConferenceServer(account);
1567 if (server == null) {
1568 if (callback != null) {
1569 callback.error(R.string.no_conference_server_found, null);
1570 }
1571 return;
1572 }
1573 String name = new BigInteger(75, getRNG()).toString(32);
1574 Jid jid = Jid.fromParts(name, server, null);
1575 final Conversation conversation = findOrCreateConversation(account, jid, true);
1576 joinMuc(conversation);
1577 Bundle options = new Bundle();
1578 options.putString("muc#roomconfig_persistentroom", "1");
1579 options.putString("muc#roomconfig_membersonly", "1");
1580 options.putString("muc#roomconfig_publicroom", "0");
1581 options.putString("muc#roomconfig_whois", "anyone");
1582 pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1583 @Override
1584 public void onPushSucceeded() {
1585 for (Jid invite : jids) {
1586 invite(conversation, invite);
1587 }
1588 if (account.countPresences() > 1) {
1589 directInvite(conversation, account.getJid().toBareJid());
1590 }
1591 if (callback != null) {
1592 callback.success(conversation);
1593 }
1594 }
1595
1596 @Override
1597 public void onPushFailed() {
1598 if (callback != null) {
1599 callback.error(R.string.conference_creation_failed, conversation);
1600 }
1601 }
1602 });
1603
1604 } catch (InvalidJidException e) {
1605 if (callback != null) {
1606 callback.error(R.string.conference_creation_failed, null);
1607 }
1608 }
1609 } else {
1610 if (callback != null) {
1611 callback.error(R.string.not_connected_try_again, null);
1612 }
1613 }
1614 }
1615
1616 public void fetchConferenceConfiguration(final Conversation conversation) {
1617 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1618 request.setTo(conversation.getJid().toBareJid());
1619 request.query("http://jabber.org/protocol/disco#info");
1620 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1621 @Override
1622 public void onIqPacketReceived(Account account, IqPacket packet) {
1623 if (packet.getType() != IqPacket.TYPE.ERROR) {
1624 ArrayList<String> features = new ArrayList<>();
1625 for (Element child : packet.query().getChildren()) {
1626 if (child != null && child.getName().equals("feature")) {
1627 String var = child.getAttribute("var");
1628 if (var != null) {
1629 features.add(var);
1630 }
1631 }
1632 }
1633 conversation.getMucOptions().updateFeatures(features);
1634 updateConversationUi();
1635 }
1636 }
1637 });
1638 }
1639
1640 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1641 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1642 request.setTo(conversation.getJid().toBareJid());
1643 request.query("http://jabber.org/protocol/muc#owner");
1644 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1645 @Override
1646 public void onIqPacketReceived(Account account, IqPacket packet) {
1647 if (packet.getType() != IqPacket.TYPE.ERROR) {
1648 Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1649 for (Field field : data.getFields()) {
1650 if (options.containsKey(field.getName())) {
1651 field.setValue(options.getString(field.getName()));
1652 }
1653 }
1654 data.submit();
1655 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1656 set.setTo(conversation.getJid().toBareJid());
1657 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1658 sendIqPacket(account, set, new OnIqPacketReceived() {
1659 @Override
1660 public void onIqPacketReceived(Account account, IqPacket packet) {
1661 if (packet.getType() == IqPacket.TYPE.RESULT) {
1662 if (callback != null) {
1663 callback.onPushSucceeded();
1664 }
1665 } else {
1666 if (callback != null) {
1667 callback.onPushFailed();
1668 }
1669 }
1670 }
1671 });
1672 } else {
1673 if (callback != null) {
1674 callback.onPushFailed();
1675 }
1676 }
1677 }
1678 });
1679 }
1680
1681 public void pushSubjectToConference(final Conversation conference, final String subject) {
1682 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1683 this.sendMessagePacket(conference.getAccount(), packet);
1684 final MucOptions mucOptions = conference.getMucOptions();
1685 final MucOptions.User self = mucOptions.getSelf();
1686 if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1687 Bundle options = new Bundle();
1688 options.putString("muc#roomconfig_persistentroom", "1");
1689 this.pushConferenceConfiguration(conference, options, null);
1690 }
1691 }
1692
1693 public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1694 final Jid jid = user.toBareJid();
1695 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
1696 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1697 @Override
1698 public void onIqPacketReceived(Account account, IqPacket packet) {
1699 if (packet.getType() == IqPacket.TYPE.RESULT) {
1700 callback.onAffiliationChangedSuccessful(jid);
1701 } else {
1702 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
1703 }
1704 }
1705 });
1706 }
1707
1708 public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
1709 List<Jid> jids = new ArrayList<>();
1710 for (MucOptions.User user : conference.getMucOptions().getUsers()) {
1711 if (user.getAffiliation() == before && user.getJid() != null) {
1712 jids.add(user.getJid());
1713 }
1714 }
1715 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
1716 sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
1717 }
1718
1719 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
1720 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
1721 Log.d(Config.LOGTAG, request.toString());
1722 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1723 @Override
1724 public void onIqPacketReceived(Account account, IqPacket packet) {
1725 Log.d(Config.LOGTAG, packet.toString());
1726 if (packet.getType() == IqPacket.TYPE.RESULT) {
1727 callback.onRoleChangedSuccessful(nick);
1728 } else {
1729 callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
1730 }
1731 }
1732 });
1733 }
1734
1735 public void disconnect(Account account, boolean force) {
1736 if ((account.getStatus() == Account.State.ONLINE)
1737 || (account.getStatus() == Account.State.DISABLED)) {
1738 if (!force) {
1739 List<Conversation> conversations = getConversations();
1740 for (Conversation conversation : conversations) {
1741 if (conversation.getAccount() == account) {
1742 if (conversation.getMode() == Conversation.MODE_MULTI) {
1743 leaveMuc(conversation);
1744 } else {
1745 if (conversation.endOtrIfNeeded()) {
1746 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1747 + ": ended otr session with "
1748 + conversation.getJid());
1749 }
1750 }
1751 }
1752 }
1753 sendOfflinePresence(account);
1754 }
1755 account.getXmppConnection().disconnect(force);
1756 }
1757 }
1758
1759 @Override
1760 public IBinder onBind(Intent intent) {
1761 return mBinder;
1762 }
1763
1764 public void updateMessage(Message message) {
1765 databaseBackend.updateMessage(message);
1766 updateConversationUi();
1767 }
1768
1769 protected void syncDirtyContacts(Account account) {
1770 for (Contact contact : account.getRoster().getContacts()) {
1771 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1772 pushContactToServer(contact);
1773 }
1774 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1775 deleteContactOnServer(contact);
1776 }
1777 }
1778 }
1779
1780 public void createContact(Contact contact) {
1781 SharedPreferences sharedPref = getPreferences();
1782 boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1783 if (autoGrant) {
1784 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1785 contact.setOption(Contact.Options.ASKING);
1786 }
1787 pushContactToServer(contact);
1788 }
1789
1790 public void onOtrSessionEstablished(Conversation conversation) {
1791 final Account account = conversation.getAccount();
1792 final Session otrSession = conversation.getOtrSession();
1793 Log.d(Config.LOGTAG,
1794 account.getJid().toBareJid() + " otr session established with "
1795 + conversation.getJid() + "/"
1796 + otrSession.getSessionID().getUserID());
1797 conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
1798
1799 @Override
1800 public void onMessageFound(Message message) {
1801 SessionID id = otrSession.getSessionID();
1802 try {
1803 message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
1804 } catch (InvalidJidException e) {
1805 return;
1806 }
1807 if (message.needsUploading()) {
1808 mJingleConnectionManager.createNewConnection(message);
1809 } else {
1810 MessagePacket outPacket = mMessageGenerator.generateOtrChat(message, true);
1811 if (outPacket != null) {
1812 message.setStatus(Message.STATUS_SEND);
1813 databaseBackend.updateMessage(message);
1814 sendMessagePacket(account, outPacket);
1815 }
1816 }
1817 updateConversationUi();
1818 }
1819 });
1820 }
1821
1822 public boolean renewSymmetricKey(Conversation conversation) {
1823 Account account = conversation.getAccount();
1824 byte[] symmetricKey = new byte[32];
1825 this.mRandom.nextBytes(symmetricKey);
1826 Session otrSession = conversation.getOtrSession();
1827 if (otrSession != null) {
1828 MessagePacket packet = new MessagePacket();
1829 packet.setType(MessagePacket.TYPE_CHAT);
1830 packet.setFrom(account.getJid());
1831 packet.addChild("private", "urn:xmpp:carbons:2");
1832 packet.addChild("no-copy", "urn:xmpp:hints");
1833 packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
1834 + otrSession.getSessionID().getUserID());
1835 try {
1836 packet.setBody(otrSession
1837 .transformSending(CryptoHelper.FILETRANSFER
1838 + CryptoHelper.bytesToHex(symmetricKey))[0]);
1839 sendMessagePacket(account, packet);
1840 conversation.setSymmetricKey(symmetricKey);
1841 return true;
1842 } catch (OtrException e) {
1843 return false;
1844 }
1845 }
1846 return false;
1847 }
1848
1849 public void pushContactToServer(final Contact contact) {
1850 contact.resetOption(Contact.Options.DIRTY_DELETE);
1851 contact.setOption(Contact.Options.DIRTY_PUSH);
1852 final Account account = contact.getAccount();
1853 if (account.getStatus() == Account.State.ONLINE) {
1854 final boolean ask = contact.getOption(Contact.Options.ASKING);
1855 final boolean sendUpdates = contact
1856 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
1857 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
1858 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1859 iq.query(Xmlns.ROSTER).addChild(contact.asElement());
1860 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
1861 if (sendUpdates) {
1862 sendPresencePacket(account,
1863 mPresenceGenerator.sendPresenceUpdatesTo(contact));
1864 }
1865 if (ask) {
1866 sendPresencePacket(account,
1867 mPresenceGenerator.requestPresenceUpdatesFrom(contact));
1868 }
1869 }
1870 }
1871
1872 public void publishAvatar(final Account account,
1873 final Uri image,
1874 final UiCallback<Avatar> callback) {
1875 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
1876 final int size = Config.AVATAR_SIZE;
1877 final Avatar avatar = getFileBackend()
1878 .getPepAvatar(image, size, format);
1879 if (avatar != null) {
1880 avatar.height = size;
1881 avatar.width = size;
1882 if (format.equals(Bitmap.CompressFormat.WEBP)) {
1883 avatar.type = "image/webp";
1884 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1885 avatar.type = "image/jpeg";
1886 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
1887 avatar.type = "image/png";
1888 }
1889 if (!getFileBackend().save(avatar)) {
1890 callback.error(R.string.error_saving_avatar, avatar);
1891 return;
1892 }
1893 final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
1894 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1895
1896 @Override
1897 public void onIqPacketReceived(Account account, IqPacket result) {
1898 if (result.getType() == IqPacket.TYPE.RESULT) {
1899 final IqPacket packet = XmppConnectionService.this.mIqGenerator
1900 .publishAvatarMetadata(avatar);
1901 sendIqPacket(account, packet, new OnIqPacketReceived() {
1902
1903 @Override
1904 public void onIqPacketReceived(Account account,
1905 IqPacket result) {
1906 if (result.getType() == IqPacket.TYPE.RESULT) {
1907 if (account.setAvatar(avatar.getFilename())) {
1908 getAvatarService().clear(account);
1909 databaseBackend.updateAccount(account);
1910 }
1911 callback.success(avatar);
1912 } else {
1913 callback.error(
1914 R.string.error_publish_avatar_server_reject,
1915 avatar);
1916 }
1917 }
1918 });
1919 } else {
1920 callback.error(
1921 R.string.error_publish_avatar_server_reject,
1922 avatar);
1923 }
1924 }
1925 });
1926 } else {
1927 callback.error(R.string.error_publish_avatar_converting, null);
1928 }
1929 }
1930
1931 public void fetchAvatar(Account account, Avatar avatar) {
1932 fetchAvatar(account, avatar, null);
1933 }
1934
1935 private static String generateFetchKey(Account account, final Avatar avatar) {
1936 return account.getJid().toBareJid()+"_"+avatar.owner+"_"+avatar.sha1sum;
1937 }
1938
1939 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
1940 final String KEY = generateFetchKey(account, avatar);
1941 synchronized(this.mInProgressAvatarFetches) {
1942 if (this.mInProgressAvatarFetches.contains(KEY)) {
1943 return;
1944 } else {
1945 switch (avatar.origin) {
1946 case PEP:
1947 this.mInProgressAvatarFetches.add(KEY);
1948 fetchAvatarPep(account, avatar, callback);
1949 break;
1950 case VCARD:
1951 this.mInProgressAvatarFetches.add(KEY);
1952 fetchAvatarVcard(account, avatar, callback);
1953 break;
1954 }
1955 }
1956 }
1957 }
1958
1959 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
1960 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
1961 sendIqPacket(account, packet, new OnIqPacketReceived() {
1962
1963 @Override
1964 public void onIqPacketReceived(Account account, IqPacket result) {
1965 synchronized (mInProgressAvatarFetches) {
1966 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
1967 }
1968 final String ERROR = account.getJid().toBareJid()
1969 + ": fetching avatar for " + avatar.owner + " failed ";
1970 if (result.getType() == IqPacket.TYPE.RESULT) {
1971 avatar.image = mIqParser.avatarData(result);
1972 if (avatar.image != null) {
1973 if (getFileBackend().save(avatar)) {
1974 if (account.getJid().toBareJid().equals(avatar.owner)) {
1975 if (account.setAvatar(avatar.getFilename())) {
1976 databaseBackend.updateAccount(account);
1977 }
1978 getAvatarService().clear(account);
1979 updateConversationUi();
1980 updateAccountUi();
1981 } else {
1982 Contact contact = account.getRoster()
1983 .getContact(avatar.owner);
1984 contact.setAvatar(avatar);
1985 getAvatarService().clear(contact);
1986 updateConversationUi();
1987 updateRosterUi();
1988 }
1989 if (callback != null) {
1990 callback.success(avatar);
1991 }
1992 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1993 + ": succesfuly fetched pep avatar for " + avatar.owner);
1994 return;
1995 }
1996 } else {
1997
1998 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
1999 }
2000 } else {
2001 Element error = result.findChild("error");
2002 if (error == null) {
2003 Log.d(Config.LOGTAG, ERROR + "(server error)");
2004 } else {
2005 Log.d(Config.LOGTAG, ERROR + error.toString());
2006 }
2007 }
2008 if (callback != null) {
2009 callback.error(0, null);
2010 }
2011
2012 }
2013 });
2014 }
2015
2016 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2017 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2018 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2019 @Override
2020 public void onIqPacketReceived(Account account, IqPacket packet) {
2021 synchronized (mInProgressAvatarFetches) {
2022 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2023 }
2024 if (packet.getType() == IqPacket.TYPE.RESULT) {
2025 Element vCard = packet.findChild("vCard", "vcard-temp");
2026 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2027 String image = photo != null ? photo.findChildContent("BINVAL") : null;
2028 if (image != null) {
2029 avatar.image = image;
2030 if (getFileBackend().save(avatar)) {
2031 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2032 + ": successfully fetched vCard avatar for " + avatar.owner);
2033 Contact contact = account.getRoster()
2034 .getContact(avatar.owner);
2035 contact.setAvatar(avatar);
2036 getAvatarService().clear(contact);
2037 updateConversationUi();
2038 updateRosterUi();
2039 }
2040 }
2041 }
2042 }
2043 });
2044 }
2045
2046 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2047 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2048 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2049
2050 @Override
2051 public void onIqPacketReceived(Account account, IqPacket packet) {
2052 if (packet.getType() == IqPacket.TYPE.RESULT) {
2053 Element pubsub = packet.findChild("pubsub",
2054 "http://jabber.org/protocol/pubsub");
2055 if (pubsub != null) {
2056 Element items = pubsub.findChild("items");
2057 if (items != null) {
2058 Avatar avatar = Avatar.parseMetadata(items);
2059 if (avatar != null) {
2060 avatar.owner = account.getJid().toBareJid();
2061 if (fileBackend.isAvatarCached(avatar)) {
2062 if (account.setAvatar(avatar.getFilename())) {
2063 databaseBackend.updateAccount(account);
2064 }
2065 getAvatarService().clear(account);
2066 callback.success(avatar);
2067 } else {
2068 fetchAvatarPep(account, avatar, callback);
2069 }
2070 return;
2071 }
2072 }
2073 }
2074 }
2075 callback.error(0, null);
2076 }
2077 });
2078 }
2079
2080 public void deleteContactOnServer(Contact contact) {
2081 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2082 contact.resetOption(Contact.Options.DIRTY_PUSH);
2083 contact.setOption(Contact.Options.DIRTY_DELETE);
2084 Account account = contact.getAccount();
2085 if (account.getStatus() == Account.State.ONLINE) {
2086 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2087 Element item = iq.query(Xmlns.ROSTER).addChild("item");
2088 item.setAttribute("jid", contact.getJid().toString());
2089 item.setAttribute("subscription", "remove");
2090 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2091 }
2092 }
2093
2094 public void updateConversation(Conversation conversation) {
2095 this.databaseBackend.updateConversation(conversation);
2096 }
2097
2098 public void reconnectAccount(final Account account, final boolean force) {
2099 synchronized (account) {
2100 if (account.getXmppConnection() != null) {
2101 disconnect(account, force);
2102 }
2103 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2104
2105 synchronized (this.mInProgressAvatarFetches) {
2106 for(Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext();) {
2107 final String KEY = iterator.next();
2108 if (KEY.startsWith(account.getJid().toBareJid()+"_")) {
2109 iterator.remove();
2110 }
2111 }
2112 }
2113
2114 if (account.getXmppConnection() == null) {
2115 account.setXmppConnection(createConnection(account));
2116 }
2117 Thread thread = new Thread(account.getXmppConnection());
2118 thread.start();
2119 scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
2120 } else {
2121 account.getRoster().clearPresences();
2122 account.setXmppConnection(null);
2123 }
2124 }
2125 }
2126
2127 public void reconnectAccountInBackground(final Account account) {
2128 new Thread(new Runnable() {
2129 @Override
2130 public void run() {
2131 reconnectAccount(account,false);
2132 }
2133 }).start();
2134 }
2135
2136 public void invite(Conversation conversation, Jid contact) {
2137 Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": inviting "+contact+" to "+conversation.getJid().toBareJid());
2138 MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2139 sendMessagePacket(conversation.getAccount(), packet);
2140 }
2141
2142 public void directInvite(Conversation conversation, Jid jid) {
2143 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2144 sendMessagePacket(conversation.getAccount(),packet);
2145 }
2146
2147 public void resetSendingToWaiting(Account account) {
2148 for (Conversation conversation : getConversations()) {
2149 if (conversation.getAccount() == account) {
2150 conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2151
2152 @Override
2153 public void onMessageFound(Message message) {
2154 markMessage(message, Message.STATUS_WAITING);
2155 }
2156 });
2157 }
2158 }
2159 }
2160
2161 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2162 if (uuid == null) {
2163 return null;
2164 }
2165 for (Conversation conversation : getConversations()) {
2166 if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2167 final Message message = conversation.findSentMessageWithUuid(uuid);
2168 if (message != null) {
2169 markMessage(message, status);
2170 }
2171 return message;
2172 }
2173 }
2174 return null;
2175 }
2176
2177 public boolean markMessage(Conversation conversation, String uuid,
2178 int status) {
2179 if (uuid == null) {
2180 return false;
2181 } else {
2182 Message message = conversation.findSentMessageWithUuid(uuid);
2183 if (message != null) {
2184 markMessage(message, status);
2185 return true;
2186 } else {
2187 return false;
2188 }
2189 }
2190 }
2191
2192 public void markMessage(Message message, int status) {
2193 if (status == Message.STATUS_SEND_FAILED
2194 && (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2195 .getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2196 return;
2197 }
2198 message.setStatus(status);
2199 databaseBackend.updateMessage(message);
2200 updateConversationUi();
2201 }
2202
2203 public SharedPreferences getPreferences() {
2204 return PreferenceManager
2205 .getDefaultSharedPreferences(getApplicationContext());
2206 }
2207
2208 public boolean forceEncryption() {
2209 return getPreferences().getBoolean("force_encryption", false);
2210 }
2211
2212 public boolean confirmMessages() {
2213 return getPreferences().getBoolean("confirm_messages", true);
2214 }
2215
2216 public boolean sendChatStates() {
2217 return getPreferences().getBoolean("chat_states", false);
2218 }
2219
2220 public boolean saveEncryptedMessages() {
2221 return !getPreferences().getBoolean("dont_save_encrypted", false);
2222 }
2223
2224 public boolean indicateReceived() {
2225 return getPreferences().getBoolean("indicate_received", false);
2226 }
2227
2228 public int unreadCount() {
2229 int count = 0;
2230 for(Conversation conversation : getConversations()) {
2231 count += conversation.unreadCount();
2232 }
2233 return count;
2234 }
2235
2236
2237 public void showErrorToastInUi(int resId) {
2238 if (mOnShowErrorToast != null) {
2239 mOnShowErrorToast.onShowErrorToast(resId);
2240 }
2241 }
2242
2243 public void updateConversationUi() {
2244 if (mOnConversationUpdate != null) {
2245 mOnConversationUpdate.onConversationUpdate();
2246 }
2247 }
2248
2249 public void updateAccountUi() {
2250 if (mOnAccountUpdate != null) {
2251 mOnAccountUpdate.onAccountUpdate();
2252 }
2253 }
2254
2255 public void updateRosterUi() {
2256 if (mOnRosterUpdate != null) {
2257 mOnRosterUpdate.onRosterUpdate();
2258 }
2259 }
2260
2261 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2262 if (mOnUpdateBlocklist != null) {
2263 mOnUpdateBlocklist.OnUpdateBlocklist(status);
2264 }
2265 }
2266
2267 public void updateMucRosterUi() {
2268 if (mOnMucRosterUpdate != null) {
2269 mOnMucRosterUpdate.onMucRosterUpdate();
2270 }
2271 }
2272
2273 public Account findAccountByJid(final Jid accountJid) {
2274 for (Account account : this.accounts) {
2275 if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2276 return account;
2277 }
2278 }
2279 return null;
2280 }
2281
2282 public Conversation findConversationByUuid(String uuid) {
2283 for (Conversation conversation : getConversations()) {
2284 if (conversation.getUuid().equals(uuid)) {
2285 return conversation;
2286 }
2287 }
2288 return null;
2289 }
2290
2291 public void markRead(final Conversation conversation) {
2292 mNotificationService.clear(conversation);
2293 conversation.markRead();
2294 updateUnreadCountBadge();
2295 }
2296
2297 public synchronized void updateUnreadCountBadge() {
2298 int count = unreadCount();
2299 if (unreadCount != count) {
2300 Log.d(Config.LOGTAG, "update unread count to " + count);
2301 if (count > 0) {
2302 ShortcutBadger.with(getApplicationContext()).count(count);
2303 } else {
2304 ShortcutBadger.with(getApplicationContext()).remove();
2305 }
2306 unreadCount = count;
2307 }
2308 }
2309
2310 public void sendReadMarker(final Conversation conversation) {
2311 final Message markable = conversation.getLatestMarkableMessage();
2312 this.markRead(conversation);
2313 if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2314 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2315 Account account = conversation.getAccount();
2316 final Jid to = markable.getCounterpart();
2317 MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2318 this.sendMessagePacket(conversation.getAccount(), packet);
2319 }
2320 updateConversationUi();
2321 }
2322
2323 public SecureRandom getRNG() {
2324 return this.mRandom;
2325 }
2326
2327 public MemorizingTrustManager getMemorizingTrustManager() {
2328 return this.mMemorizingTrustManager;
2329 }
2330
2331 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2332 this.mMemorizingTrustManager = trustManager;
2333 }
2334
2335 public void updateMemorizingTrustmanager() {
2336 final MemorizingTrustManager tm;
2337 final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2338 if (dontTrustSystemCAs) {
2339 tm = new MemorizingTrustManager(getApplicationContext(), null);
2340 } else {
2341 tm = new MemorizingTrustManager(getApplicationContext());
2342 }
2343 setMemorizingTrustManager(tm);
2344 }
2345
2346 public PowerManager getPowerManager() {
2347 return this.pm;
2348 }
2349
2350 public LruCache<String, Bitmap> getBitmapCache() {
2351 return this.mBitmapCache;
2352 }
2353
2354 public void syncRosterToDisk(final Account account) {
2355 Runnable runnable = new Runnable() {
2356
2357 @Override
2358 public void run() {
2359 databaseBackend.writeRoster(account.getRoster());
2360 }
2361 };
2362 mDatabaseExecutor.execute(runnable);
2363
2364 }
2365
2366 public List<String> getKnownHosts() {
2367 final List<String> hosts = new ArrayList<>();
2368 for (final Account account : getAccounts()) {
2369 if (!hosts.contains(account.getServer().toString())) {
2370 hosts.add(account.getServer().toString());
2371 }
2372 for (final Contact contact : account.getRoster().getContacts()) {
2373 if (contact.showInRoster()) {
2374 final String server = contact.getServer().toString();
2375 if (server != null && !hosts.contains(server)) {
2376 hosts.add(server);
2377 }
2378 }
2379 }
2380 }
2381 return hosts;
2382 }
2383
2384 public List<String> getKnownConferenceHosts() {
2385 final ArrayList<String> mucServers = new ArrayList<>();
2386 for (final Account account : accounts) {
2387 if (account.getXmppConnection() != null) {
2388 final String server = account.getXmppConnection().getMucServer();
2389 if (server != null && !mucServers.contains(server)) {
2390 mucServers.add(server);
2391 }
2392 }
2393 }
2394 return mucServers;
2395 }
2396
2397 public void sendMessagePacket(Account account, MessagePacket packet) {
2398 XmppConnection connection = account.getXmppConnection();
2399 if (connection != null) {
2400 connection.sendMessagePacket(packet);
2401 }
2402 }
2403
2404 public void sendPresencePacket(Account account, PresencePacket packet) {
2405 XmppConnection connection = account.getXmppConnection();
2406 if (connection != null) {
2407 connection.sendPresencePacket(packet);
2408 }
2409 }
2410
2411 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2412 final XmppConnection connection = account.getXmppConnection();
2413 if (connection != null) {
2414 connection.sendIqPacket(packet, callback);
2415 }
2416 }
2417
2418 public void sendPresence(final Account account) {
2419 sendPresencePacket(account, mPresenceGenerator.sendPresence(account));
2420 }
2421
2422 public void sendOfflinePresence(final Account account) {
2423 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2424 }
2425
2426 public MessageGenerator getMessageGenerator() {
2427 return this.mMessageGenerator;
2428 }
2429
2430 public PresenceGenerator getPresenceGenerator() {
2431 return this.mPresenceGenerator;
2432 }
2433
2434 public IqGenerator getIqGenerator() {
2435 return this.mIqGenerator;
2436 }
2437
2438 public IqParser getIqParser() {
2439 return this.mIqParser;
2440 }
2441
2442 public JingleConnectionManager getJingleConnectionManager() {
2443 return this.mJingleConnectionManager;
2444 }
2445
2446 public MessageArchiveService getMessageArchiveService() {
2447 return this.mMessageArchiveService;
2448 }
2449
2450 public List<Contact> findContacts(Jid jid) {
2451 ArrayList<Contact> contacts = new ArrayList<>();
2452 for (Account account : getAccounts()) {
2453 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2454 Contact contact = account.getRoster().getContactFromRoster(jid);
2455 if (contact != null) {
2456 contacts.add(contact);
2457 }
2458 }
2459 }
2460 return contacts;
2461 }
2462
2463 public NotificationService getNotificationService() {
2464 return this.mNotificationService;
2465 }
2466
2467 public HttpConnectionManager getHttpConnectionManager() {
2468 return this.mHttpConnectionManager;
2469 }
2470
2471 public void resendFailedMessages(final Message message) {
2472 final Collection<Message> messages = new ArrayList<>();
2473 Message current = message;
2474 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2475 messages.add(current);
2476 if (current.mergeable(current.next())) {
2477 current = current.next();
2478 } else {
2479 break;
2480 }
2481 }
2482 for (final Message msg : messages) {
2483 markMessage(msg, Message.STATUS_WAITING);
2484 this.resendMessage(msg);
2485 }
2486 }
2487
2488 public void clearConversationHistory(final Conversation conversation) {
2489 conversation.clearMessages();
2490 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2491 new Thread(new Runnable() {
2492 @Override
2493 public void run() {
2494 databaseBackend.deleteMessagesInConversation(conversation);
2495 }
2496 }).start();
2497 }
2498
2499 public void sendBlockRequest(final Blockable blockable) {
2500 if (blockable != null && blockable.getBlockedJid() != null) {
2501 final Jid jid = blockable.getBlockedJid();
2502 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2503
2504 @Override
2505 public void onIqPacketReceived(final Account account, final IqPacket packet) {
2506 if (packet.getType() == IqPacket.TYPE.RESULT) {
2507 account.getBlocklist().add(jid);
2508 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2509 }
2510 }
2511 });
2512 }
2513 }
2514
2515 public void sendUnblockRequest(final Blockable blockable) {
2516 if (blockable != null && blockable.getJid() != null) {
2517 final Jid jid = blockable.getBlockedJid();
2518 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2519 @Override
2520 public void onIqPacketReceived(final Account account, final IqPacket packet) {
2521 if (packet.getType() == IqPacket.TYPE.RESULT) {
2522 account.getBlocklist().remove(jid);
2523 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2524 }
2525 }
2526 });
2527 }
2528 }
2529
2530 public interface OnMoreMessagesLoaded {
2531 public void onMoreMessagesLoaded(int count, Conversation conversation);
2532
2533 public void informUser(int r);
2534 }
2535
2536 public interface OnAccountPasswordChanged {
2537 public void onPasswordChangeSucceeded();
2538
2539 public void onPasswordChangeFailed();
2540 }
2541
2542 public interface OnAffiliationChanged {
2543 public void onAffiliationChangedSuccessful(Jid jid);
2544
2545 public void onAffiliationChangeFailed(Jid jid, int resId);
2546 }
2547
2548 public interface OnRoleChanged {
2549 public void onRoleChangedSuccessful(String nick);
2550
2551 public void onRoleChangeFailed(String nick, int resid);
2552 }
2553
2554 public interface OnConversationUpdate {
2555 public void onConversationUpdate();
2556 }
2557
2558 public interface OnAccountUpdate {
2559 public void onAccountUpdate();
2560 }
2561
2562 public interface OnRosterUpdate {
2563 public void onRosterUpdate();
2564 }
2565
2566 public interface OnMucRosterUpdate {
2567 public void onMucRosterUpdate();
2568 }
2569
2570 public interface OnConferenceOptionsPushed {
2571 public void onPushSucceeded();
2572
2573 public void onPushFailed();
2574 }
2575
2576 public interface OnShowErrorToast {
2577 void onShowErrorToast(int resId);
2578 }
2579
2580 public class XmppConnectionBinder extends Binder {
2581 public XmppConnectionService getService() {
2582 return XmppConnectionService.this;
2583 }
2584 }
2585}