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().findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
707 @Override
708 public void onMessageFound(Message message) {
709 markMessage(message,Message.STATUS_SEND_FAILED);
710 }
711 });
712 }
713
714 if (account.isOnlineAndConnected()) {
715 switch (message.getEncryption()) {
716 case Message.ENCRYPTION_NONE:
717 if (message.needsUploading()) {
718 if (account.httpUploadAvailable() || message.fixCounterpart()) {
719 this.sendFileMessage(message);
720 } else {
721 break;
722 }
723 } else {
724 packet = mMessageGenerator.generateChat(message,resend);
725 }
726 break;
727 case Message.ENCRYPTION_PGP:
728 case Message.ENCRYPTION_DECRYPTED:
729 if (message.needsUploading()) {
730 if (account.httpUploadAvailable() || message.fixCounterpart()) {
731 this.sendFileMessage(message);
732 } else {
733 break;
734 }
735 } else {
736 packet = mMessageGenerator.generatePgpChat(message,resend);
737 }
738 break;
739 case Message.ENCRYPTION_OTR:
740 SessionImpl otrSession = conversation.getOtrSession();
741 if (otrSession != null && otrSession.getSessionStatus() == SessionStatus.ENCRYPTED) {
742 try {
743 message.setCounterpart(Jid.fromSessionID(otrSession.getSessionID()));
744 } catch (InvalidJidException e) {
745 break;
746 }
747 if (message.needsUploading()) {
748 mJingleConnectionManager.createNewConnection(message);
749 } else {
750 packet = mMessageGenerator.generateOtrChat(message,resend);
751 }
752 } else if (otrSession == null) {
753 if (message.fixCounterpart()) {
754 conversation.startOtrSession(message.getCounterpart().getResourcepart(), true);
755 } else {
756 break;
757 }
758 }
759 break;
760 case Message.ENCRYPTION_AXOLOTL:
761 try {
762 packet = mMessageGenerator.generateAxolotlChat(message);
763 Log.d(Config.LOGTAG, "Succeeded generating axolotl chat message!");
764 } catch (NoSessionsCreatedException e) {
765 message.setStatus(Message.STATUS_WAITING);
766 }
767 break;
768
769 }
770 if (packet != null) {
771 if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
772 message.setStatus(Message.STATUS_UNSEND);
773 } else {
774 message.setStatus(Message.STATUS_SEND);
775 }
776 }
777 } else {
778 switch(message.getEncryption()) {
779 case Message.ENCRYPTION_DECRYPTED:
780 if (!message.needsUploading()) {
781 String pgpBody = message.getEncryptedBody();
782 String decryptedBody = message.getBody();
783 message.setBody(pgpBody);
784 message.setEncryption(Message.ENCRYPTION_PGP);
785 databaseBackend.createMessage(message);
786 saveInDb = false;
787 message.setBody(decryptedBody);
788 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
789 }
790 break;
791 case Message.ENCRYPTION_OTR:
792 if (!conversation.hasValidOtrSession() && message.getCounterpart() != null) {
793 conversation.startOtrSession(message.getCounterpart().getResourcepart(), false);
794 }
795 break;
796 }
797 }
798
799 if (resend) {
800 if (packet != null) {
801 if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
802 markMessage(message,Message.STATUS_UNSEND);
803 } else {
804 markMessage(message,Message.STATUS_SEND);
805 }
806 }
807 } else {
808 conversation.add(message);
809 if (saveInDb && (message.getEncryption() == Message.ENCRYPTION_NONE || saveEncryptedMessages())) {
810 databaseBackend.createMessage(message);
811 }
812 updateConversationUi();
813 }
814 if (packet != null) {
815 if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
816 if (this.sendChatStates()) {
817 packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
818 }
819 }
820 sendMessagePacket(account, packet);
821 }
822 }
823
824 private void sendUnsentMessages(final Conversation conversation) {
825 conversation.findWaitingMessages(new Conversation.OnMessageFound() {
826
827 @Override
828 public void onMessageFound(Message message) {
829 resendMessage(message);
830 }
831 });
832 }
833
834 public void resendMessage(final Message message) {
835 sendMessage(message, true);
836 }
837
838 public void fetchRosterFromServer(final Account account) {
839 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
840 if (!"".equals(account.getRosterVersion())) {
841 Log.d(Config.LOGTAG, account.getJid().toBareJid()
842 + ": fetching roster version " + account.getRosterVersion());
843 } else {
844 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
845 }
846 iqPacket.query(Xmlns.ROSTER).setAttribute("ver",account.getRosterVersion());
847 sendIqPacket(account,iqPacket,mIqParser);
848 }
849
850 public void fetchBookmarks(final Account account) {
851 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
852 final Element query = iqPacket.query("jabber:iq:private");
853 query.addChild("storage", "storage:bookmarks");
854 final OnIqPacketReceived callback = new OnIqPacketReceived() {
855
856 @Override
857 public void onIqPacketReceived(final Account account, final IqPacket packet) {
858 final Element query = packet.query();
859 final List<Bookmark> bookmarks = new CopyOnWriteArrayList<>();
860 final Element storage = query.findChild("storage",
861 "storage:bookmarks");
862 if (storage != null) {
863 for (final Element item : storage.getChildren()) {
864 if (item.getName().equals("conference")) {
865 final Bookmark bookmark = Bookmark.parse(item, account);
866 bookmarks.add(bookmark);
867 Conversation conversation = find(bookmark);
868 if (conversation != null) {
869 conversation.setBookmark(bookmark);
870 } else if (bookmark.autojoin() && bookmark.getJid() != null) {
871 conversation = findOrCreateConversation(
872 account, bookmark.getJid(), true);
873 conversation.setBookmark(bookmark);
874 joinMuc(conversation);
875 }
876 }
877 }
878 }
879 account.setBookmarks(bookmarks);
880 }
881 };
882 sendIqPacket(account, iqPacket, callback);
883 }
884
885 public void pushBookmarks(Account account) {
886 IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
887 Element query = iqPacket.query("jabber:iq:private");
888 Element storage = query.addChild("storage", "storage:bookmarks");
889 for (Bookmark bookmark : account.getBookmarks()) {
890 storage.addChild(bookmark);
891 }
892 sendIqPacket(account, iqPacket, mDefaultIqHandler);
893 }
894
895 public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
896 if (mPhoneContactMergerThread != null) {
897 mPhoneContactMergerThread.interrupt();
898 }
899 mPhoneContactMergerThread = new Thread(new Runnable() {
900 @Override
901 public void run() {
902 Log.d(Config.LOGTAG,"start merging phone contacts with roster");
903 for (Account account : accounts) {
904 List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
905 for (Bundle phoneContact : phoneContacts) {
906 if (Thread.interrupted()) {
907 Log.d(Config.LOGTAG,"interrupted merging phone contacts");
908 return;
909 }
910 Jid jid;
911 try {
912 jid = Jid.fromString(phoneContact.getString("jid"));
913 } catch (final InvalidJidException e) {
914 continue;
915 }
916 final Contact contact = account.getRoster().getContact(jid);
917 String systemAccount = phoneContact.getInt("phoneid")
918 + "#"
919 + phoneContact.getString("lookup");
920 contact.setSystemAccount(systemAccount);
921 if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
922 getAvatarService().clear(contact);
923 }
924 contact.setSystemName(phoneContact.getString("displayname"));
925 withSystemAccounts.remove(contact);
926 }
927 for(Contact contact : withSystemAccounts) {
928 contact.setSystemAccount(null);
929 contact.setSystemName(null);
930 if (contact.setPhotoUri(null)) {
931 getAvatarService().clear(contact);
932 }
933 }
934 }
935 Log.d(Config.LOGTAG,"finished merging phone contacts");
936 updateAccountUi();
937 }
938 });
939 mPhoneContactMergerThread.start();
940 }
941
942 private void restoreFromDatabase() {
943 synchronized (this.conversations) {
944 final Map<String, Account> accountLookupTable = new Hashtable<>();
945 for (Account account : this.accounts) {
946 accountLookupTable.put(account.getUuid(), account);
947 }
948 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
949 for (Conversation conversation : this.conversations) {
950 Account account = accountLookupTable.get(conversation.getAccountUuid());
951 conversation.setAccount(account);
952 }
953 Runnable runnable =new Runnable() {
954 @Override
955 public void run() {
956 Log.d(Config.LOGTAG,"restoring roster");
957 for(Account account : accounts) {
958 databaseBackend.readRoster(account.getRoster());
959 }
960 getBitmapCache().evictAll();
961 Looper.prepare();
962 PhoneHelper.loadPhoneContacts(getApplicationContext(),
963 new CopyOnWriteArrayList<Bundle>(),
964 XmppConnectionService.this);
965 Log.d(Config.LOGTAG,"restoring messages");
966 for (Conversation conversation : conversations) {
967 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
968 checkDeletedFiles(conversation);
969 }
970 mRestoredFromDatabase = true;
971 Log.d(Config.LOGTAG,"restored all messages");
972 updateConversationUi();
973 }
974 };
975 mDatabaseExecutor.execute(runnable);
976 }
977 }
978
979 public List<Conversation> getConversations() {
980 return this.conversations;
981 }
982
983 private void checkDeletedFiles(Conversation conversation) {
984 conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
985
986 @Override
987 public void onMessageFound(Message message) {
988 if (!getFileBackend().isFileAvailable(message)) {
989 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
990 }
991 }
992 });
993 }
994
995 private void markFileDeleted(String uuid) {
996 for (Conversation conversation : getConversations()) {
997 Message message = conversation.findMessageWithFileAndUuid(uuid);
998 if (message != null) {
999 if (!getFileBackend().isFileAvailable(message)) {
1000 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1001 updateConversationUi();
1002 }
1003 return;
1004 }
1005 }
1006 }
1007
1008 public void populateWithOrderedConversations(final List<Conversation> list) {
1009 populateWithOrderedConversations(list, true);
1010 }
1011
1012 public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1013 list.clear();
1014 if (includeNoFileUpload) {
1015 list.addAll(getConversations());
1016 } else {
1017 for (Conversation conversation : getConversations()) {
1018 if (conversation.getMode() == Conversation.MODE_SINGLE
1019 || conversation.getAccount().httpUploadAvailable()) {
1020 list.add(conversation);
1021 }
1022 }
1023 }
1024 Collections.sort(list, new Comparator<Conversation>() {
1025 @Override
1026 public int compare(Conversation lhs, Conversation rhs) {
1027 Message left = lhs.getLatestMessage();
1028 Message right = rhs.getLatestMessage();
1029 if (left.getTimeSent() > right.getTimeSent()) {
1030 return -1;
1031 } else if (left.getTimeSent() < right.getTimeSent()) {
1032 return 1;
1033 } else {
1034 return 0;
1035 }
1036 }
1037 });
1038 }
1039
1040 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1041 Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1042 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation,callback)) {
1043 return;
1044 }
1045 Runnable runnable = new Runnable() {
1046 @Override
1047 public void run() {
1048 final Account account = conversation.getAccount();
1049 List<Message> messages = databaseBackend.getMessages(conversation, 50,timestamp);
1050 if (messages.size() > 0) {
1051 conversation.addAll(0, messages);
1052 checkDeletedFiles(conversation);
1053 callback.onMoreMessagesLoaded(messages.size(), conversation);
1054 } else if (conversation.hasMessagesLeftOnServer()
1055 && account.isOnlineAndConnected()
1056 && account.getXmppConnection().getFeatures().mam()) {
1057 MessageArchiveService.Query query = getMessageArchiveService().query(conversation,0,timestamp - 1);
1058 if (query != null) {
1059 query.setCallback(callback);
1060 }
1061 callback.informUser(R.string.fetching_history_from_server);
1062 }
1063 }
1064 };
1065 mDatabaseExecutor.execute(runnable);
1066 }
1067
1068 public List<Account> getAccounts() {
1069 return this.accounts;
1070 }
1071
1072 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1073 for (final Conversation conversation : haystack) {
1074 if (conversation.getContact() == contact) {
1075 return conversation;
1076 }
1077 }
1078 return null;
1079 }
1080
1081 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1082 if (jid == null) {
1083 return null;
1084 }
1085 for (final Conversation conversation : haystack) {
1086 if ((account == null || conversation.getAccount() == account)
1087 && (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1088 return conversation;
1089 }
1090 }
1091 return null;
1092 }
1093
1094 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1095 return this.findOrCreateConversation(account, jid, muc, null);
1096 }
1097
1098 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1099 synchronized (this.conversations) {
1100 Conversation conversation = find(account, jid);
1101 if (conversation != null) {
1102 return conversation;
1103 }
1104 conversation = databaseBackend.findConversation(account, jid);
1105 if (conversation != null) {
1106 conversation.setStatus(Conversation.STATUS_AVAILABLE);
1107 conversation.setAccount(account);
1108 if (muc) {
1109 conversation.setMode(Conversation.MODE_MULTI);
1110 conversation.setContactJid(jid);
1111 } else {
1112 conversation.setMode(Conversation.MODE_SINGLE);
1113 conversation.setContactJid(jid.toBareJid());
1114 }
1115 conversation.setNextEncryption(-1);
1116 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1117 this.databaseBackend.updateConversation(conversation);
1118 } else {
1119 String conversationName;
1120 Contact contact = account.getRoster().getContact(jid);
1121 if (contact != null) {
1122 conversationName = contact.getDisplayName();
1123 } else {
1124 conversationName = jid.getLocalpart();
1125 }
1126 if (muc) {
1127 conversation = new Conversation(conversationName, account, jid,
1128 Conversation.MODE_MULTI);
1129 } else {
1130 conversation = new Conversation(conversationName, account, jid.toBareJid(),
1131 Conversation.MODE_SINGLE);
1132 }
1133 this.databaseBackend.createConversation(conversation);
1134 }
1135 if (account.getXmppConnection() != null
1136 && account.getXmppConnection().getFeatures().mam()
1137 && !muc) {
1138 if (query == null) {
1139 this.mMessageArchiveService.query(conversation);
1140 } else {
1141 if (query.getConversation() == null) {
1142 this.mMessageArchiveService.query(conversation, query.getStart());
1143 }
1144 }
1145 }
1146 checkDeletedFiles(conversation);
1147 this.conversations.add(conversation);
1148 updateConversationUi();
1149 return conversation;
1150 }
1151 }
1152
1153 public void archiveConversation(Conversation conversation) {
1154 getNotificationService().clear(conversation);
1155 conversation.setStatus(Conversation.STATUS_ARCHIVED);
1156 conversation.setNextEncryption(-1);
1157 synchronized (this.conversations) {
1158 if (conversation.getMode() == Conversation.MODE_MULTI) {
1159 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1160 Bookmark bookmark = conversation.getBookmark();
1161 if (bookmark != null && bookmark.autojoin()) {
1162 bookmark.setAutojoin(false);
1163 pushBookmarks(bookmark.getAccount());
1164 }
1165 }
1166 leaveMuc(conversation);
1167 } else {
1168 conversation.endOtrIfNeeded();
1169 }
1170 this.databaseBackend.updateConversation(conversation);
1171 this.conversations.remove(conversation);
1172 updateConversationUi();
1173 }
1174 }
1175
1176 public void createAccount(final Account account) {
1177 account.initAccountServices(this);
1178 databaseBackend.createAccount(account);
1179 this.accounts.add(account);
1180 this.reconnectAccountInBackground(account);
1181 updateAccountUi();
1182 }
1183
1184 public void updateAccount(final Account account) {
1185 this.statusListener.onStatusChanged(account);
1186 databaseBackend.updateAccount(account);
1187 reconnectAccount(account, false);
1188 updateAccountUi();
1189 getNotificationService().updateErrorNotification();
1190 }
1191
1192 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1193 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1194 sendIqPacket(account, iq, new OnIqPacketReceived() {
1195 @Override
1196 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1197 if (packet.getType() == IqPacket.TYPE.RESULT) {
1198 account.setPassword(newPassword);
1199 databaseBackend.updateAccount(account);
1200 callback.onPasswordChangeSucceeded();
1201 } else {
1202 callback.onPasswordChangeFailed();
1203 }
1204 }
1205 });
1206 }
1207
1208 public void deleteAccount(final Account account) {
1209 synchronized (this.conversations) {
1210 for (final Conversation conversation : conversations) {
1211 if (conversation.getAccount() == account) {
1212 if (conversation.getMode() == Conversation.MODE_MULTI) {
1213 leaveMuc(conversation);
1214 } else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1215 conversation.endOtrIfNeeded();
1216 }
1217 conversations.remove(conversation);
1218 }
1219 }
1220 if (account.getXmppConnection() != null) {
1221 this.disconnect(account, true);
1222 }
1223 databaseBackend.deleteAccount(account);
1224 this.accounts.remove(account);
1225 updateAccountUi();
1226 getNotificationService().updateErrorNotification();
1227 }
1228 }
1229
1230 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1231 synchronized (this) {
1232 if (checkListeners()) {
1233 switchToForeground();
1234 }
1235 this.mOnConversationUpdate = listener;
1236 this.mNotificationService.setIsInForeground(true);
1237 if (this.convChangedListenerCount < 2) {
1238 this.convChangedListenerCount++;
1239 }
1240 }
1241 }
1242
1243 public void removeOnConversationListChangedListener() {
1244 synchronized (this) {
1245 this.convChangedListenerCount--;
1246 if (this.convChangedListenerCount <= 0) {
1247 this.convChangedListenerCount = 0;
1248 this.mOnConversationUpdate = null;
1249 this.mNotificationService.setIsInForeground(false);
1250 if (checkListeners()) {
1251 switchToBackground();
1252 }
1253 }
1254 }
1255 }
1256
1257 public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1258 synchronized (this) {
1259 if (checkListeners()) {
1260 switchToForeground();
1261 }
1262 this.mOnShowErrorToast = onShowErrorToast;
1263 if (this.showErrorToastListenerCount < 2) {
1264 this.showErrorToastListenerCount++;
1265 }
1266 }
1267 this.mOnShowErrorToast = onShowErrorToast;
1268 }
1269
1270 public void removeOnShowErrorToastListener() {
1271 synchronized (this) {
1272 this.showErrorToastListenerCount--;
1273 if (this.showErrorToastListenerCount <= 0) {
1274 this.showErrorToastListenerCount = 0;
1275 this.mOnShowErrorToast = null;
1276 if (checkListeners()) {
1277 switchToBackground();
1278 }
1279 }
1280 }
1281 }
1282
1283 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1284 synchronized (this) {
1285 if (checkListeners()) {
1286 switchToForeground();
1287 }
1288 this.mOnAccountUpdate = listener;
1289 if (this.accountChangedListenerCount < 2) {
1290 this.accountChangedListenerCount++;
1291 }
1292 }
1293 }
1294
1295 public void removeOnAccountListChangedListener() {
1296 synchronized (this) {
1297 this.accountChangedListenerCount--;
1298 if (this.accountChangedListenerCount <= 0) {
1299 this.mOnAccountUpdate = null;
1300 this.accountChangedListenerCount = 0;
1301 if (checkListeners()) {
1302 switchToBackground();
1303 }
1304 }
1305 }
1306 }
1307
1308 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1309 synchronized (this) {
1310 if (checkListeners()) {
1311 switchToForeground();
1312 }
1313 this.mOnRosterUpdate = listener;
1314 if (this.rosterChangedListenerCount < 2) {
1315 this.rosterChangedListenerCount++;
1316 }
1317 }
1318 }
1319
1320 public void removeOnRosterUpdateListener() {
1321 synchronized (this) {
1322 this.rosterChangedListenerCount--;
1323 if (this.rosterChangedListenerCount <= 0) {
1324 this.rosterChangedListenerCount = 0;
1325 this.mOnRosterUpdate = null;
1326 if (checkListeners()) {
1327 switchToBackground();
1328 }
1329 }
1330 }
1331 }
1332
1333 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1334 synchronized (this) {
1335 if (checkListeners()) {
1336 switchToForeground();
1337 }
1338 this.mOnUpdateBlocklist = listener;
1339 if (this.updateBlocklistListenerCount < 2) {
1340 this.updateBlocklistListenerCount++;
1341 }
1342 }
1343 }
1344
1345 public void removeOnUpdateBlocklistListener() {
1346 synchronized (this) {
1347 this.updateBlocklistListenerCount--;
1348 if (this.updateBlocklistListenerCount <= 0) {
1349 this.updateBlocklistListenerCount = 0;
1350 this.mOnUpdateBlocklist = null;
1351 if (checkListeners()) {
1352 switchToBackground();
1353 }
1354 }
1355 }
1356 }
1357
1358 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1359 synchronized (this) {
1360 if (checkListeners()) {
1361 switchToForeground();
1362 }
1363 this.mOnMucRosterUpdate = listener;
1364 if (this.mucRosterChangedListenerCount < 2) {
1365 this.mucRosterChangedListenerCount++;
1366 }
1367 }
1368 }
1369
1370 public void removeOnMucRosterUpdateListener() {
1371 synchronized (this) {
1372 this.mucRosterChangedListenerCount--;
1373 if (this.mucRosterChangedListenerCount <= 0) {
1374 this.mucRosterChangedListenerCount = 0;
1375 this.mOnMucRosterUpdate = null;
1376 if (checkListeners()) {
1377 switchToBackground();
1378 }
1379 }
1380 }
1381 }
1382
1383 private boolean checkListeners() {
1384 return (this.mOnAccountUpdate == null
1385 && this.mOnConversationUpdate == null
1386 && this.mOnRosterUpdate == null
1387 && this.mOnUpdateBlocklist == null
1388 && this.mOnShowErrorToast == null);
1389 }
1390
1391 private void switchToForeground() {
1392 for (Account account : getAccounts()) {
1393 if (account.getStatus() == Account.State.ONLINE) {
1394 XmppConnection connection = account.getXmppConnection();
1395 if (connection != null && connection.getFeatures().csi()) {
1396 connection.sendActive();
1397 }
1398 }
1399 }
1400 Log.d(Config.LOGTAG, "app switched into foreground");
1401 }
1402
1403 private void switchToBackground() {
1404 for (Account account : getAccounts()) {
1405 if (account.getStatus() == Account.State.ONLINE) {
1406 XmppConnection connection = account.getXmppConnection();
1407 if (connection != null && connection.getFeatures().csi()) {
1408 connection.sendInactive();
1409 }
1410 }
1411 }
1412 for(Conversation conversation : getConversations()) {
1413 conversation.setIncomingChatState(ChatState.ACTIVE);
1414 }
1415 this.mNotificationService.setIsInForeground(false);
1416 Log.d(Config.LOGTAG, "app switched into background");
1417 }
1418
1419 private void connectMultiModeConversations(Account account) {
1420 List<Conversation> conversations = getConversations();
1421 for (Conversation conversation : conversations) {
1422 if ((conversation.getMode() == Conversation.MODE_MULTI)
1423 && (conversation.getAccount() == account)) {
1424 conversation.resetMucOptions();
1425 joinMuc(conversation);
1426 }
1427 }
1428 }
1429
1430 public void joinMuc(Conversation conversation) {
1431 Account account = conversation.getAccount();
1432 account.pendingConferenceJoins.remove(conversation);
1433 account.pendingConferenceLeaves.remove(conversation);
1434 if (account.getStatus() == Account.State.ONLINE) {
1435 final String nick = conversation.getMucOptions().getProposedNick();
1436 final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1437 if (joinJid == null) {
1438 return; //safety net
1439 }
1440 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1441 PresencePacket packet = new PresencePacket();
1442 packet.setFrom(conversation.getAccount().getJid());
1443 packet.setTo(joinJid);
1444 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1445 if (conversation.getMucOptions().getPassword() != null) {
1446 x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1447 }
1448 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1449 String sig = account.getPgpSignature();
1450 if (sig != null) {
1451 packet.addChild("status").setContent("online");
1452 packet.addChild("x", "jabber:x:signed").setContent(sig);
1453 }
1454 sendPresencePacket(account, packet);
1455 fetchConferenceConfiguration(conversation);
1456 if (!joinJid.equals(conversation.getJid())) {
1457 conversation.setContactJid(joinJid);
1458 databaseBackend.updateConversation(conversation);
1459 }
1460 conversation.setHasMessagesLeftOnServer(false);
1461 } else {
1462 account.pendingConferenceJoins.add(conversation);
1463 }
1464 }
1465
1466 public void providePasswordForMuc(Conversation conversation, String password) {
1467 if (conversation.getMode() == Conversation.MODE_MULTI) {
1468 conversation.getMucOptions().setPassword(password);
1469 if (conversation.getBookmark() != null) {
1470 conversation.getBookmark().setAutojoin(true);
1471 pushBookmarks(conversation.getAccount());
1472 }
1473 databaseBackend.updateConversation(conversation);
1474 joinMuc(conversation);
1475 }
1476 }
1477
1478 public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1479 final MucOptions options = conversation.getMucOptions();
1480 final Jid joinJid = options.createJoinJid(nick);
1481 if (options.online()) {
1482 Account account = conversation.getAccount();
1483 options.setOnRenameListener(new OnRenameListener() {
1484
1485 @Override
1486 public void onSuccess() {
1487 conversation.setContactJid(joinJid);
1488 databaseBackend.updateConversation(conversation);
1489 Bookmark bookmark = conversation.getBookmark();
1490 if (bookmark != null) {
1491 bookmark.setNick(nick);
1492 pushBookmarks(bookmark.getAccount());
1493 }
1494 callback.success(conversation);
1495 }
1496
1497 @Override
1498 public void onFailure() {
1499 callback.error(R.string.nick_in_use, conversation);
1500 }
1501 });
1502
1503 PresencePacket packet = new PresencePacket();
1504 packet.setTo(joinJid);
1505 packet.setFrom(conversation.getAccount().getJid());
1506
1507 String sig = account.getPgpSignature();
1508 if (sig != null) {
1509 packet.addChild("status").setContent("online");
1510 packet.addChild("x", "jabber:x:signed").setContent(sig);
1511 }
1512 sendPresencePacket(account, packet);
1513 } else {
1514 conversation.setContactJid(joinJid);
1515 databaseBackend.updateConversation(conversation);
1516 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1517 Bookmark bookmark = conversation.getBookmark();
1518 if (bookmark != null) {
1519 bookmark.setNick(nick);
1520 pushBookmarks(bookmark.getAccount());
1521 }
1522 joinMuc(conversation);
1523 }
1524 }
1525 }
1526
1527 public void leaveMuc(Conversation conversation) {
1528 Account account = conversation.getAccount();
1529 account.pendingConferenceJoins.remove(conversation);
1530 account.pendingConferenceLeaves.remove(conversation);
1531 if (account.getStatus() == Account.State.ONLINE) {
1532 PresencePacket packet = new PresencePacket();
1533 packet.setTo(conversation.getJid());
1534 packet.setFrom(conversation.getAccount().getJid());
1535 packet.setAttribute("type", "unavailable");
1536 sendPresencePacket(conversation.getAccount(), packet);
1537 conversation.getMucOptions().setOffline();
1538 conversation.deregisterWithBookmark();
1539 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1540 + ": leaving muc " + conversation.getJid());
1541 } else {
1542 account.pendingConferenceLeaves.add(conversation);
1543 }
1544 }
1545
1546 private String findConferenceServer(final Account account) {
1547 String server;
1548 if (account.getXmppConnection() != null) {
1549 server = account.getXmppConnection().getMucServer();
1550 if (server != null) {
1551 return server;
1552 }
1553 }
1554 for (Account other : getAccounts()) {
1555 if (other != account && other.getXmppConnection() != null) {
1556 server = other.getXmppConnection().getMucServer();
1557 if (server != null) {
1558 return server;
1559 }
1560 }
1561 }
1562 return null;
1563 }
1564
1565 public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1566 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1567 if (account.getStatus() == Account.State.ONLINE) {
1568 try {
1569 String server = findConferenceServer(account);
1570 if (server == null) {
1571 if (callback != null) {
1572 callback.error(R.string.no_conference_server_found, null);
1573 }
1574 return;
1575 }
1576 String name = new BigInteger(75, getRNG()).toString(32);
1577 Jid jid = Jid.fromParts(name, server, null);
1578 final Conversation conversation = findOrCreateConversation(account, jid, true);
1579 joinMuc(conversation);
1580 Bundle options = new Bundle();
1581 options.putString("muc#roomconfig_persistentroom", "1");
1582 options.putString("muc#roomconfig_membersonly", "1");
1583 options.putString("muc#roomconfig_publicroom", "0");
1584 options.putString("muc#roomconfig_whois", "anyone");
1585 pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1586 @Override
1587 public void onPushSucceeded() {
1588 for (Jid invite : jids) {
1589 invite(conversation, invite);
1590 }
1591 if (account.countPresences() > 1) {
1592 directInvite(conversation, account.getJid().toBareJid());
1593 }
1594 if (callback != null) {
1595 callback.success(conversation);
1596 }
1597 }
1598
1599 @Override
1600 public void onPushFailed() {
1601 if (callback != null) {
1602 callback.error(R.string.conference_creation_failed, conversation);
1603 }
1604 }
1605 });
1606
1607 } catch (InvalidJidException e) {
1608 if (callback != null) {
1609 callback.error(R.string.conference_creation_failed, null);
1610 }
1611 }
1612 } else {
1613 if (callback != null) {
1614 callback.error(R.string.not_connected_try_again, null);
1615 }
1616 }
1617 }
1618
1619 public void fetchConferenceConfiguration(final Conversation conversation) {
1620 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1621 request.setTo(conversation.getJid().toBareJid());
1622 request.query("http://jabber.org/protocol/disco#info");
1623 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1624 @Override
1625 public void onIqPacketReceived(Account account, IqPacket packet) {
1626 if (packet.getType() != IqPacket.TYPE.ERROR) {
1627 ArrayList<String> features = new ArrayList<>();
1628 for (Element child : packet.query().getChildren()) {
1629 if (child != null && child.getName().equals("feature")) {
1630 String var = child.getAttribute("var");
1631 if (var != null) {
1632 features.add(var);
1633 }
1634 }
1635 }
1636 conversation.getMucOptions().updateFeatures(features);
1637 updateConversationUi();
1638 }
1639 }
1640 });
1641 }
1642
1643 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1644 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1645 request.setTo(conversation.getJid().toBareJid());
1646 request.query("http://jabber.org/protocol/muc#owner");
1647 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1648 @Override
1649 public void onIqPacketReceived(Account account, IqPacket packet) {
1650 if (packet.getType() != IqPacket.TYPE.ERROR) {
1651 Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1652 for (Field field : data.getFields()) {
1653 if (options.containsKey(field.getName())) {
1654 field.setValue(options.getString(field.getName()));
1655 }
1656 }
1657 data.submit();
1658 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1659 set.setTo(conversation.getJid().toBareJid());
1660 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1661 sendIqPacket(account, set, new OnIqPacketReceived() {
1662 @Override
1663 public void onIqPacketReceived(Account account, IqPacket packet) {
1664 if (packet.getType() == IqPacket.TYPE.RESULT) {
1665 if (callback != null) {
1666 callback.onPushSucceeded();
1667 }
1668 } else {
1669 if (callback != null) {
1670 callback.onPushFailed();
1671 }
1672 }
1673 }
1674 });
1675 } else {
1676 if (callback != null) {
1677 callback.onPushFailed();
1678 }
1679 }
1680 }
1681 });
1682 }
1683
1684 public void pushSubjectToConference(final Conversation conference, final String subject) {
1685 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1686 this.sendMessagePacket(conference.getAccount(), packet);
1687 final MucOptions mucOptions = conference.getMucOptions();
1688 final MucOptions.User self = mucOptions.getSelf();
1689 if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1690 Bundle options = new Bundle();
1691 options.putString("muc#roomconfig_persistentroom", "1");
1692 this.pushConferenceConfiguration(conference, options, null);
1693 }
1694 }
1695
1696 public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1697 final Jid jid = user.toBareJid();
1698 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
1699 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1700 @Override
1701 public void onIqPacketReceived(Account account, IqPacket packet) {
1702 if (packet.getType() == IqPacket.TYPE.RESULT) {
1703 callback.onAffiliationChangedSuccessful(jid);
1704 } else {
1705 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
1706 }
1707 }
1708 });
1709 }
1710
1711 public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
1712 List<Jid> jids = new ArrayList<>();
1713 for (MucOptions.User user : conference.getMucOptions().getUsers()) {
1714 if (user.getAffiliation() == before && user.getJid() != null) {
1715 jids.add(user.getJid());
1716 }
1717 }
1718 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
1719 sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
1720 }
1721
1722 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
1723 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
1724 Log.d(Config.LOGTAG, request.toString());
1725 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1726 @Override
1727 public void onIqPacketReceived(Account account, IqPacket packet) {
1728 Log.d(Config.LOGTAG, packet.toString());
1729 if (packet.getType() == IqPacket.TYPE.RESULT) {
1730 callback.onRoleChangedSuccessful(nick);
1731 } else {
1732 callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
1733 }
1734 }
1735 });
1736 }
1737
1738 public void disconnect(Account account, boolean force) {
1739 if ((account.getStatus() == Account.State.ONLINE)
1740 || (account.getStatus() == Account.State.DISABLED)) {
1741 if (!force) {
1742 List<Conversation> conversations = getConversations();
1743 for (Conversation conversation : conversations) {
1744 if (conversation.getAccount() == account) {
1745 if (conversation.getMode() == Conversation.MODE_MULTI) {
1746 leaveMuc(conversation);
1747 } else {
1748 if (conversation.endOtrIfNeeded()) {
1749 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1750 + ": ended otr session with "
1751 + conversation.getJid());
1752 }
1753 }
1754 }
1755 }
1756 sendOfflinePresence(account);
1757 }
1758 account.getXmppConnection().disconnect(force);
1759 }
1760 }
1761
1762 @Override
1763 public IBinder onBind(Intent intent) {
1764 return mBinder;
1765 }
1766
1767 public void updateMessage(Message message) {
1768 databaseBackend.updateMessage(message);
1769 updateConversationUi();
1770 }
1771
1772 protected void syncDirtyContacts(Account account) {
1773 for (Contact contact : account.getRoster().getContacts()) {
1774 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1775 pushContactToServer(contact);
1776 }
1777 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1778 deleteContactOnServer(contact);
1779 }
1780 }
1781 }
1782
1783 public void createContact(Contact contact) {
1784 SharedPreferences sharedPref = getPreferences();
1785 boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1786 if (autoGrant) {
1787 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1788 contact.setOption(Contact.Options.ASKING);
1789 }
1790 pushContactToServer(contact);
1791 }
1792
1793 public void onOtrSessionEstablished(Conversation conversation) {
1794 final Account account = conversation.getAccount();
1795 final Session otrSession = conversation.getOtrSession();
1796 Log.d(Config.LOGTAG,
1797 account.getJid().toBareJid() + " otr session established with "
1798 + conversation.getJid() + "/"
1799 + otrSession.getSessionID().getUserID());
1800 conversation.findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
1801
1802 @Override
1803 public void onMessageFound(Message message) {
1804 SessionID id = otrSession.getSessionID();
1805 try {
1806 message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
1807 } catch (InvalidJidException e) {
1808 return;
1809 }
1810 if (message.needsUploading()) {
1811 mJingleConnectionManager.createNewConnection(message);
1812 } else {
1813 MessagePacket outPacket = mMessageGenerator.generateOtrChat(message, true);
1814 if (outPacket != null) {
1815 message.setStatus(Message.STATUS_SEND);
1816 databaseBackend.updateMessage(message);
1817 sendMessagePacket(account, outPacket);
1818 }
1819 }
1820 updateConversationUi();
1821 }
1822 });
1823 }
1824
1825 public boolean renewSymmetricKey(Conversation conversation) {
1826 Account account = conversation.getAccount();
1827 byte[] symmetricKey = new byte[32];
1828 this.mRandom.nextBytes(symmetricKey);
1829 Session otrSession = conversation.getOtrSession();
1830 if (otrSession != null) {
1831 MessagePacket packet = new MessagePacket();
1832 packet.setType(MessagePacket.TYPE_CHAT);
1833 packet.setFrom(account.getJid());
1834 packet.addChild("private", "urn:xmpp:carbons:2");
1835 packet.addChild("no-copy", "urn:xmpp:hints");
1836 packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
1837 + otrSession.getSessionID().getUserID());
1838 try {
1839 packet.setBody(otrSession
1840 .transformSending(CryptoHelper.FILETRANSFER
1841 + CryptoHelper.bytesToHex(symmetricKey))[0]);
1842 sendMessagePacket(account, packet);
1843 conversation.setSymmetricKey(symmetricKey);
1844 return true;
1845 } catch (OtrException e) {
1846 return false;
1847 }
1848 }
1849 return false;
1850 }
1851
1852 public void pushContactToServer(final Contact contact) {
1853 contact.resetOption(Contact.Options.DIRTY_DELETE);
1854 contact.setOption(Contact.Options.DIRTY_PUSH);
1855 final Account account = contact.getAccount();
1856 if (account.getStatus() == Account.State.ONLINE) {
1857 final boolean ask = contact.getOption(Contact.Options.ASKING);
1858 final boolean sendUpdates = contact
1859 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
1860 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
1861 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1862 iq.query(Xmlns.ROSTER).addChild(contact.asElement());
1863 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
1864 if (sendUpdates) {
1865 sendPresencePacket(account,
1866 mPresenceGenerator.sendPresenceUpdatesTo(contact));
1867 }
1868 if (ask) {
1869 sendPresencePacket(account,
1870 mPresenceGenerator.requestPresenceUpdatesFrom(contact));
1871 }
1872 }
1873 }
1874
1875 public void publishAvatar(final Account account,
1876 final Uri image,
1877 final UiCallback<Avatar> callback) {
1878 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
1879 final int size = Config.AVATAR_SIZE;
1880 final Avatar avatar = getFileBackend()
1881 .getPepAvatar(image, size, format);
1882 if (avatar != null) {
1883 avatar.height = size;
1884 avatar.width = size;
1885 if (format.equals(Bitmap.CompressFormat.WEBP)) {
1886 avatar.type = "image/webp";
1887 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1888 avatar.type = "image/jpeg";
1889 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
1890 avatar.type = "image/png";
1891 }
1892 if (!getFileBackend().save(avatar)) {
1893 callback.error(R.string.error_saving_avatar, avatar);
1894 return;
1895 }
1896 final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
1897 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1898
1899 @Override
1900 public void onIqPacketReceived(Account account, IqPacket result) {
1901 if (result.getType() == IqPacket.TYPE.RESULT) {
1902 final IqPacket packet = XmppConnectionService.this.mIqGenerator
1903 .publishAvatarMetadata(avatar);
1904 sendIqPacket(account, packet, new OnIqPacketReceived() {
1905
1906 @Override
1907 public void onIqPacketReceived(Account account,
1908 IqPacket result) {
1909 if (result.getType() == IqPacket.TYPE.RESULT) {
1910 if (account.setAvatar(avatar.getFilename())) {
1911 getAvatarService().clear(account);
1912 databaseBackend.updateAccount(account);
1913 }
1914 callback.success(avatar);
1915 } else {
1916 callback.error(
1917 R.string.error_publish_avatar_server_reject,
1918 avatar);
1919 }
1920 }
1921 });
1922 } else {
1923 callback.error(
1924 R.string.error_publish_avatar_server_reject,
1925 avatar);
1926 }
1927 }
1928 });
1929 } else {
1930 callback.error(R.string.error_publish_avatar_converting, null);
1931 }
1932 }
1933
1934 public void fetchAvatar(Account account, Avatar avatar) {
1935 fetchAvatar(account, avatar, null);
1936 }
1937
1938 private static String generateFetchKey(Account account, final Avatar avatar) {
1939 return account.getJid().toBareJid()+"_"+avatar.owner+"_"+avatar.sha1sum;
1940 }
1941
1942 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
1943 final String KEY = generateFetchKey(account, avatar);
1944 synchronized(this.mInProgressAvatarFetches) {
1945 if (this.mInProgressAvatarFetches.contains(KEY)) {
1946 return;
1947 } else {
1948 switch (avatar.origin) {
1949 case PEP:
1950 this.mInProgressAvatarFetches.add(KEY);
1951 fetchAvatarPep(account, avatar, callback);
1952 break;
1953 case VCARD:
1954 this.mInProgressAvatarFetches.add(KEY);
1955 fetchAvatarVcard(account, avatar, callback);
1956 break;
1957 }
1958 }
1959 }
1960 }
1961
1962 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
1963 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
1964 sendIqPacket(account, packet, new OnIqPacketReceived() {
1965
1966 @Override
1967 public void onIqPacketReceived(Account account, IqPacket result) {
1968 synchronized (mInProgressAvatarFetches) {
1969 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
1970 }
1971 final String ERROR = account.getJid().toBareJid()
1972 + ": fetching avatar for " + avatar.owner + " failed ";
1973 if (result.getType() == IqPacket.TYPE.RESULT) {
1974 avatar.image = mIqParser.avatarData(result);
1975 if (avatar.image != null) {
1976 if (getFileBackend().save(avatar)) {
1977 if (account.getJid().toBareJid().equals(avatar.owner)) {
1978 if (account.setAvatar(avatar.getFilename())) {
1979 databaseBackend.updateAccount(account);
1980 }
1981 getAvatarService().clear(account);
1982 updateConversationUi();
1983 updateAccountUi();
1984 } else {
1985 Contact contact = account.getRoster()
1986 .getContact(avatar.owner);
1987 contact.setAvatar(avatar);
1988 getAvatarService().clear(contact);
1989 updateConversationUi();
1990 updateRosterUi();
1991 }
1992 if (callback != null) {
1993 callback.success(avatar);
1994 }
1995 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1996 + ": succesfuly fetched pep avatar for " + avatar.owner);
1997 return;
1998 }
1999 } else {
2000
2001 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2002 }
2003 } else {
2004 Element error = result.findChild("error");
2005 if (error == null) {
2006 Log.d(Config.LOGTAG, ERROR + "(server error)");
2007 } else {
2008 Log.d(Config.LOGTAG, ERROR + error.toString());
2009 }
2010 }
2011 if (callback != null) {
2012 callback.error(0, null);
2013 }
2014
2015 }
2016 });
2017 }
2018
2019 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2020 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2021 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2022 @Override
2023 public void onIqPacketReceived(Account account, IqPacket packet) {
2024 synchronized (mInProgressAvatarFetches) {
2025 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2026 }
2027 if (packet.getType() == IqPacket.TYPE.RESULT) {
2028 Element vCard = packet.findChild("vCard", "vcard-temp");
2029 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2030 String image = photo != null ? photo.findChildContent("BINVAL") : null;
2031 if (image != null) {
2032 avatar.image = image;
2033 if (getFileBackend().save(avatar)) {
2034 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2035 + ": successfully fetched vCard avatar for " + avatar.owner);
2036 Contact contact = account.getRoster()
2037 .getContact(avatar.owner);
2038 contact.setAvatar(avatar);
2039 getAvatarService().clear(contact);
2040 updateConversationUi();
2041 updateRosterUi();
2042 }
2043 }
2044 }
2045 }
2046 });
2047 }
2048
2049 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2050 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2051 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2052
2053 @Override
2054 public void onIqPacketReceived(Account account, IqPacket packet) {
2055 if (packet.getType() == IqPacket.TYPE.RESULT) {
2056 Element pubsub = packet.findChild("pubsub",
2057 "http://jabber.org/protocol/pubsub");
2058 if (pubsub != null) {
2059 Element items = pubsub.findChild("items");
2060 if (items != null) {
2061 Avatar avatar = Avatar.parseMetadata(items);
2062 if (avatar != null) {
2063 avatar.owner = account.getJid().toBareJid();
2064 if (fileBackend.isAvatarCached(avatar)) {
2065 if (account.setAvatar(avatar.getFilename())) {
2066 databaseBackend.updateAccount(account);
2067 }
2068 getAvatarService().clear(account);
2069 callback.success(avatar);
2070 } else {
2071 fetchAvatarPep(account, avatar, callback);
2072 }
2073 return;
2074 }
2075 }
2076 }
2077 }
2078 callback.error(0, null);
2079 }
2080 });
2081 }
2082
2083 public void deleteContactOnServer(Contact contact) {
2084 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2085 contact.resetOption(Contact.Options.DIRTY_PUSH);
2086 contact.setOption(Contact.Options.DIRTY_DELETE);
2087 Account account = contact.getAccount();
2088 if (account.getStatus() == Account.State.ONLINE) {
2089 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2090 Element item = iq.query(Xmlns.ROSTER).addChild("item");
2091 item.setAttribute("jid", contact.getJid().toString());
2092 item.setAttribute("subscription", "remove");
2093 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2094 }
2095 }
2096
2097 public void updateConversation(Conversation conversation) {
2098 this.databaseBackend.updateConversation(conversation);
2099 }
2100
2101 public void reconnectAccount(final Account account, final boolean force) {
2102 synchronized (account) {
2103 if (account.getXmppConnection() != null) {
2104 disconnect(account, force);
2105 }
2106 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2107
2108 synchronized (this.mInProgressAvatarFetches) {
2109 for(Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext();) {
2110 final String KEY = iterator.next();
2111 if (KEY.startsWith(account.getJid().toBareJid()+"_")) {
2112 iterator.remove();
2113 }
2114 }
2115 }
2116
2117 if (account.getXmppConnection() == null) {
2118 account.setXmppConnection(createConnection(account));
2119 }
2120 Thread thread = new Thread(account.getXmppConnection());
2121 thread.start();
2122 scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
2123 } else {
2124 account.getRoster().clearPresences();
2125 account.setXmppConnection(null);
2126 }
2127 }
2128 }
2129
2130 public void reconnectAccountInBackground(final Account account) {
2131 new Thread(new Runnable() {
2132 @Override
2133 public void run() {
2134 reconnectAccount(account,false);
2135 }
2136 }).start();
2137 }
2138
2139 public void invite(Conversation conversation, Jid contact) {
2140 Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": inviting "+contact+" to "+conversation.getJid().toBareJid());
2141 MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2142 sendMessagePacket(conversation.getAccount(), packet);
2143 }
2144
2145 public void directInvite(Conversation conversation, Jid jid) {
2146 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2147 sendMessagePacket(conversation.getAccount(),packet);
2148 }
2149
2150 public void resetSendingToWaiting(Account account) {
2151 for (Conversation conversation : getConversations()) {
2152 if (conversation.getAccount() == account) {
2153 conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2154
2155 @Override
2156 public void onMessageFound(Message message) {
2157 markMessage(message, Message.STATUS_WAITING);
2158 }
2159 });
2160 }
2161 }
2162 }
2163
2164 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2165 if (uuid == null) {
2166 return null;
2167 }
2168 for (Conversation conversation : getConversations()) {
2169 if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2170 final Message message = conversation.findSentMessageWithUuid(uuid);
2171 if (message != null) {
2172 markMessage(message, status);
2173 }
2174 return message;
2175 }
2176 }
2177 return null;
2178 }
2179
2180 public boolean markMessage(Conversation conversation, String uuid,
2181 int status) {
2182 if (uuid == null) {
2183 return false;
2184 } else {
2185 Message message = conversation.findSentMessageWithUuid(uuid);
2186 if (message != null) {
2187 markMessage(message, status);
2188 return true;
2189 } else {
2190 return false;
2191 }
2192 }
2193 }
2194
2195 public void markMessage(Message message, int status) {
2196 if (status == Message.STATUS_SEND_FAILED
2197 && (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2198 .getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2199 return;
2200 }
2201 message.setStatus(status);
2202 databaseBackend.updateMessage(message);
2203 updateConversationUi();
2204 }
2205
2206 public SharedPreferences getPreferences() {
2207 return PreferenceManager
2208 .getDefaultSharedPreferences(getApplicationContext());
2209 }
2210
2211 public boolean forceEncryption() {
2212 return getPreferences().getBoolean("force_encryption", false);
2213 }
2214
2215 public boolean confirmMessages() {
2216 return getPreferences().getBoolean("confirm_messages", true);
2217 }
2218
2219 public boolean sendChatStates() {
2220 return getPreferences().getBoolean("chat_states", false);
2221 }
2222
2223 public boolean saveEncryptedMessages() {
2224 return !getPreferences().getBoolean("dont_save_encrypted", false);
2225 }
2226
2227 public boolean indicateReceived() {
2228 return getPreferences().getBoolean("indicate_received", false);
2229 }
2230
2231 public int unreadCount() {
2232 int count = 0;
2233 for(Conversation conversation : getConversations()) {
2234 count += conversation.unreadCount();
2235 }
2236 return count;
2237 }
2238
2239
2240 public void showErrorToastInUi(int resId) {
2241 if (mOnShowErrorToast != null) {
2242 mOnShowErrorToast.onShowErrorToast(resId);
2243 }
2244 }
2245
2246 public void updateConversationUi() {
2247 if (mOnConversationUpdate != null) {
2248 mOnConversationUpdate.onConversationUpdate();
2249 }
2250 }
2251
2252 public void updateAccountUi() {
2253 if (mOnAccountUpdate != null) {
2254 mOnAccountUpdate.onAccountUpdate();
2255 }
2256 }
2257
2258 public void updateRosterUi() {
2259 if (mOnRosterUpdate != null) {
2260 mOnRosterUpdate.onRosterUpdate();
2261 }
2262 }
2263
2264 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2265 if (mOnUpdateBlocklist != null) {
2266 mOnUpdateBlocklist.OnUpdateBlocklist(status);
2267 }
2268 }
2269
2270 public void updateMucRosterUi() {
2271 if (mOnMucRosterUpdate != null) {
2272 mOnMucRosterUpdate.onMucRosterUpdate();
2273 }
2274 }
2275
2276 public Account findAccountByJid(final Jid accountJid) {
2277 for (Account account : this.accounts) {
2278 if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2279 return account;
2280 }
2281 }
2282 return null;
2283 }
2284
2285 public Conversation findConversationByUuid(String uuid) {
2286 for (Conversation conversation : getConversations()) {
2287 if (conversation.getUuid().equals(uuid)) {
2288 return conversation;
2289 }
2290 }
2291 return null;
2292 }
2293
2294 public void markRead(final Conversation conversation) {
2295 mNotificationService.clear(conversation);
2296 conversation.markRead();
2297 updateUnreadCountBadge();
2298 }
2299
2300 public synchronized void updateUnreadCountBadge() {
2301 int count = unreadCount();
2302 if (unreadCount != count) {
2303 Log.d(Config.LOGTAG, "update unread count to " + count);
2304 if (count > 0) {
2305 ShortcutBadger.with(getApplicationContext()).count(count);
2306 } else {
2307 ShortcutBadger.with(getApplicationContext()).remove();
2308 }
2309 unreadCount = count;
2310 }
2311 }
2312
2313 public void sendReadMarker(final Conversation conversation) {
2314 final Message markable = conversation.getLatestMarkableMessage();
2315 this.markRead(conversation);
2316 if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2317 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2318 Account account = conversation.getAccount();
2319 final Jid to = markable.getCounterpart();
2320 MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2321 this.sendMessagePacket(conversation.getAccount(), packet);
2322 }
2323 updateConversationUi();
2324 }
2325
2326 public SecureRandom getRNG() {
2327 return this.mRandom;
2328 }
2329
2330 public MemorizingTrustManager getMemorizingTrustManager() {
2331 return this.mMemorizingTrustManager;
2332 }
2333
2334 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2335 this.mMemorizingTrustManager = trustManager;
2336 }
2337
2338 public void updateMemorizingTrustmanager() {
2339 final MemorizingTrustManager tm;
2340 final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2341 if (dontTrustSystemCAs) {
2342 tm = new MemorizingTrustManager(getApplicationContext(), null);
2343 } else {
2344 tm = new MemorizingTrustManager(getApplicationContext());
2345 }
2346 setMemorizingTrustManager(tm);
2347 }
2348
2349 public PowerManager getPowerManager() {
2350 return this.pm;
2351 }
2352
2353 public LruCache<String, Bitmap> getBitmapCache() {
2354 return this.mBitmapCache;
2355 }
2356
2357 public void syncRosterToDisk(final Account account) {
2358 Runnable runnable = new Runnable() {
2359
2360 @Override
2361 public void run() {
2362 databaseBackend.writeRoster(account.getRoster());
2363 }
2364 };
2365 mDatabaseExecutor.execute(runnable);
2366
2367 }
2368
2369 public List<String> getKnownHosts() {
2370 final List<String> hosts = new ArrayList<>();
2371 for (final Account account : getAccounts()) {
2372 if (!hosts.contains(account.getServer().toString())) {
2373 hosts.add(account.getServer().toString());
2374 }
2375 for (final Contact contact : account.getRoster().getContacts()) {
2376 if (contact.showInRoster()) {
2377 final String server = contact.getServer().toString();
2378 if (server != null && !hosts.contains(server)) {
2379 hosts.add(server);
2380 }
2381 }
2382 }
2383 }
2384 return hosts;
2385 }
2386
2387 public List<String> getKnownConferenceHosts() {
2388 final ArrayList<String> mucServers = new ArrayList<>();
2389 for (final Account account : accounts) {
2390 if (account.getXmppConnection() != null) {
2391 final String server = account.getXmppConnection().getMucServer();
2392 if (server != null && !mucServers.contains(server)) {
2393 mucServers.add(server);
2394 }
2395 }
2396 }
2397 return mucServers;
2398 }
2399
2400 public void sendMessagePacket(Account account, MessagePacket packet) {
2401 XmppConnection connection = account.getXmppConnection();
2402 if (connection != null) {
2403 connection.sendMessagePacket(packet);
2404 }
2405 }
2406
2407 public void sendPresencePacket(Account account, PresencePacket packet) {
2408 XmppConnection connection = account.getXmppConnection();
2409 if (connection != null) {
2410 connection.sendPresencePacket(packet);
2411 }
2412 }
2413
2414 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2415 final XmppConnection connection = account.getXmppConnection();
2416 if (connection != null) {
2417 connection.sendIqPacket(packet, callback);
2418 }
2419 }
2420
2421 public void sendPresence(final Account account) {
2422 sendPresencePacket(account, mPresenceGenerator.sendPresence(account));
2423 }
2424
2425 public void sendOfflinePresence(final Account account) {
2426 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2427 }
2428
2429 public MessageGenerator getMessageGenerator() {
2430 return this.mMessageGenerator;
2431 }
2432
2433 public PresenceGenerator getPresenceGenerator() {
2434 return this.mPresenceGenerator;
2435 }
2436
2437 public IqGenerator getIqGenerator() {
2438 return this.mIqGenerator;
2439 }
2440
2441 public IqParser getIqParser() {
2442 return this.mIqParser;
2443 }
2444
2445 public JingleConnectionManager getJingleConnectionManager() {
2446 return this.mJingleConnectionManager;
2447 }
2448
2449 public MessageArchiveService getMessageArchiveService() {
2450 return this.mMessageArchiveService;
2451 }
2452
2453 public List<Contact> findContacts(Jid jid) {
2454 ArrayList<Contact> contacts = new ArrayList<>();
2455 for (Account account : getAccounts()) {
2456 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2457 Contact contact = account.getRoster().getContactFromRoster(jid);
2458 if (contact != null) {
2459 contacts.add(contact);
2460 }
2461 }
2462 }
2463 return contacts;
2464 }
2465
2466 public NotificationService getNotificationService() {
2467 return this.mNotificationService;
2468 }
2469
2470 public HttpConnectionManager getHttpConnectionManager() {
2471 return this.mHttpConnectionManager;
2472 }
2473
2474 public void resendFailedMessages(final Message message) {
2475 final Collection<Message> messages = new ArrayList<>();
2476 Message current = message;
2477 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2478 messages.add(current);
2479 if (current.mergeable(current.next())) {
2480 current = current.next();
2481 } else {
2482 break;
2483 }
2484 }
2485 for (final Message msg : messages) {
2486 markMessage(msg, Message.STATUS_WAITING);
2487 this.resendMessage(msg);
2488 }
2489 }
2490
2491 public void clearConversationHistory(final Conversation conversation) {
2492 conversation.clearMessages();
2493 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2494 new Thread(new Runnable() {
2495 @Override
2496 public void run() {
2497 databaseBackend.deleteMessagesInConversation(conversation);
2498 }
2499 }).start();
2500 }
2501
2502 public void sendBlockRequest(final Blockable blockable) {
2503 if (blockable != null && blockable.getBlockedJid() != null) {
2504 final Jid jid = blockable.getBlockedJid();
2505 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2506
2507 @Override
2508 public void onIqPacketReceived(final Account account, final IqPacket packet) {
2509 if (packet.getType() == IqPacket.TYPE.RESULT) {
2510 account.getBlocklist().add(jid);
2511 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2512 }
2513 }
2514 });
2515 }
2516 }
2517
2518 public void sendUnblockRequest(final Blockable blockable) {
2519 if (blockable != null && blockable.getJid() != null) {
2520 final Jid jid = blockable.getBlockedJid();
2521 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2522 @Override
2523 public void onIqPacketReceived(final Account account, final IqPacket packet) {
2524 if (packet.getType() == IqPacket.TYPE.RESULT) {
2525 account.getBlocklist().remove(jid);
2526 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2527 }
2528 }
2529 });
2530 }
2531 }
2532
2533 public interface OnMoreMessagesLoaded {
2534 public void onMoreMessagesLoaded(int count, Conversation conversation);
2535
2536 public void informUser(int r);
2537 }
2538
2539 public interface OnAccountPasswordChanged {
2540 public void onPasswordChangeSucceeded();
2541
2542 public void onPasswordChangeFailed();
2543 }
2544
2545 public interface OnAffiliationChanged {
2546 public void onAffiliationChangedSuccessful(Jid jid);
2547
2548 public void onAffiliationChangeFailed(Jid jid, int resId);
2549 }
2550
2551 public interface OnRoleChanged {
2552 public void onRoleChangedSuccessful(String nick);
2553
2554 public void onRoleChangeFailed(String nick, int resid);
2555 }
2556
2557 public interface OnConversationUpdate {
2558 public void onConversationUpdate();
2559 }
2560
2561 public interface OnAccountUpdate {
2562 public void onAccountUpdate();
2563 }
2564
2565 public interface OnRosterUpdate {
2566 public void onRosterUpdate();
2567 }
2568
2569 public interface OnMucRosterUpdate {
2570 public void onMucRosterUpdate();
2571 }
2572
2573 public interface OnConferenceOptionsPushed {
2574 public void onPushSucceeded();
2575
2576 public void onPushFailed();
2577 }
2578
2579 public interface OnShowErrorToast {
2580 void onShowErrorToast(int resId);
2581 }
2582
2583 public class XmppConnectionBinder extends Binder {
2584 public XmppConnectionService getService() {
2585 return XmppConnectionService.this;
2586 }
2587 }
2588}