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