1package eu.siacs.conversations.services;
2
3import android.annotation.SuppressLint;
4import android.annotation.TargetApi;
5import android.app.AlarmManager;
6import android.app.PendingIntent;
7import android.app.Service;
8import android.content.Context;
9import android.content.Intent;
10import android.content.IntentFilter;
11import android.content.SharedPreferences;
12import android.database.ContentObserver;
13import android.graphics.Bitmap;
14import android.media.AudioManager;
15import android.net.ConnectivityManager;
16import android.net.NetworkInfo;
17import android.net.Uri;
18import android.os.Binder;
19import android.os.Build;
20import android.os.Bundle;
21import android.os.Environment;
22import android.os.IBinder;
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.support.annotation.BoolRes;
30import android.support.annotation.IntegerRes;
31import android.support.v4.app.RemoteInput;
32import android.util.DisplayMetrics;
33import android.util.Log;
34import android.util.LruCache;
35import android.util.Pair;
36
37import org.openintents.openpgp.IOpenPgpService2;
38import org.openintents.openpgp.util.OpenPgpApi;
39import org.openintents.openpgp.util.OpenPgpServiceConnection;
40
41import java.math.BigInteger;
42import java.net.URL;
43import java.security.SecureRandom;
44import java.security.cert.CertificateException;
45import java.security.cert.X509Certificate;
46import java.util.ArrayList;
47import java.util.Arrays;
48import java.util.Collection;
49import java.util.Collections;
50import java.util.HashMap;
51import java.util.HashSet;
52import java.util.Hashtable;
53import java.util.Iterator;
54import java.util.List;
55import java.util.ListIterator;
56import java.util.Locale;
57import java.util.Map;
58import java.util.Set;
59import java.util.concurrent.CopyOnWriteArrayList;
60import java.util.concurrent.CountDownLatch;
61import java.util.concurrent.atomic.AtomicBoolean;
62import java.util.concurrent.atomic.AtomicLong;
63
64import eu.siacs.conversations.Config;
65import eu.siacs.conversations.R;
66import eu.siacs.conversations.crypto.OmemoSetting;
67import eu.siacs.conversations.crypto.PgpDecryptionService;
68import eu.siacs.conversations.crypto.PgpEngine;
69import eu.siacs.conversations.crypto.axolotl.AxolotlService;
70import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
71import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
72import eu.siacs.conversations.entities.Account;
73import eu.siacs.conversations.entities.Blockable;
74import eu.siacs.conversations.entities.Bookmark;
75import eu.siacs.conversations.entities.Contact;
76import eu.siacs.conversations.entities.Conversation;
77import eu.siacs.conversations.entities.DownloadableFile;
78import eu.siacs.conversations.entities.Message;
79import eu.siacs.conversations.entities.MucOptions;
80import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
81import eu.siacs.conversations.entities.Presence;
82import eu.siacs.conversations.entities.PresenceTemplate;
83import eu.siacs.conversations.entities.Roster;
84import eu.siacs.conversations.entities.ServiceDiscoveryResult;
85import eu.siacs.conversations.entities.Transferable;
86import eu.siacs.conversations.entities.TransferablePlaceholder;
87import eu.siacs.conversations.generator.AbstractGenerator;
88import eu.siacs.conversations.generator.IqGenerator;
89import eu.siacs.conversations.generator.MessageGenerator;
90import eu.siacs.conversations.generator.PresenceGenerator;
91import eu.siacs.conversations.http.HttpConnectionManager;
92import eu.siacs.conversations.http.AesGcmURLStreamHandlerFactory;
93import eu.siacs.conversations.parser.AbstractParser;
94import eu.siacs.conversations.parser.IqParser;
95import eu.siacs.conversations.parser.MessageParser;
96import eu.siacs.conversations.parser.PresenceParser;
97import eu.siacs.conversations.persistance.DatabaseBackend;
98import eu.siacs.conversations.persistance.FileBackend;
99import eu.siacs.conversations.ui.SettingsActivity;
100import eu.siacs.conversations.ui.UiCallback;
101import eu.siacs.conversations.utils.ConversationsFileObserver;
102import eu.siacs.conversations.utils.CryptoHelper;
103import eu.siacs.conversations.utils.ExceptionHelper;
104import eu.siacs.conversations.utils.MimeUtils;
105import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
106import eu.siacs.conversations.utils.PRNGFixes;
107import eu.siacs.conversations.utils.PhoneHelper;
108import eu.siacs.conversations.utils.QuickLoader;
109import eu.siacs.conversations.utils.ReplacingSerialSingleThreadExecutor;
110import eu.siacs.conversations.utils.ReplacingTaskManager;
111import eu.siacs.conversations.utils.Resolver;
112import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
113import eu.siacs.conversations.xml.Namespace;
114import eu.siacs.conversations.utils.XmppUri;
115import eu.siacs.conversations.xml.Element;
116import eu.siacs.conversations.xmpp.OnBindListener;
117import eu.siacs.conversations.xmpp.OnContactStatusChanged;
118import eu.siacs.conversations.xmpp.OnIqPacketReceived;
119import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
120import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
121import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
122import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
123import eu.siacs.conversations.xmpp.OnStatusChanged;
124import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
125import eu.siacs.conversations.xmpp.Patches;
126import eu.siacs.conversations.xmpp.XmppConnection;
127import eu.siacs.conversations.xmpp.chatstate.ChatState;
128import eu.siacs.conversations.xmpp.forms.Data;
129import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
130import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
131import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
132import eu.siacs.conversations.xmpp.mam.MamReference;
133import eu.siacs.conversations.xmpp.pep.Avatar;
134import eu.siacs.conversations.xmpp.stanzas.IqPacket;
135import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
136import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
137import me.leolin.shortcutbadger.ShortcutBadger;
138import rocks.xmpp.addr.Jid;
139
140public class XmppConnectionService extends Service {
141
142 public static final String ACTION_REPLY_TO_CONVERSATION = "reply_to_conversations";
143 public static final String ACTION_MARK_AS_READ = "mark_as_read";
144 public static final String ACTION_SNOOZE = "snooze";
145 public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification";
146 public static final String ACTION_DISMISS_ERROR_NOTIFICATIONS = "dismiss_error";
147 public static final String ACTION_TRY_AGAIN = "try_again";
148 public static final String ACTION_IDLE_PING = "idle_ping";
149 public static final String ACTION_GCM_TOKEN_REFRESH = "gcm_token_refresh";
150 public static final String ACTION_GCM_MESSAGE_RECEIVED = "gcm_message_received";
151 private static final String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
152
153 static {
154 URL.setURLStreamHandlerFactory(new AesGcmURLStreamHandlerFactory());
155 }
156
157 public final CountDownLatch restoredFromDatabaseLatch = new CountDownLatch(1);
158 private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor("FileAdding");
159 private final SerialSingleThreadExecutor mVideoCompressionExecutor = new SerialSingleThreadExecutor("VideoCompression");
160 private final SerialSingleThreadExecutor mDatabaseWriterExecutor = new SerialSingleThreadExecutor("DatabaseWriter");
161 private final SerialSingleThreadExecutor mDatabaseReaderExecutor = new SerialSingleThreadExecutor("DatabaseReader");
162 private final SerialSingleThreadExecutor mNotificationExecutor = new SerialSingleThreadExecutor("NotificationExecutor");
163 private final ReplacingTaskManager mRosterSyncTaskManager = new ReplacingTaskManager();
164 private final IBinder mBinder = new XmppConnectionBinder();
165 private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
166 private final IqGenerator mIqGenerator = new IqGenerator(this);
167 private final List<String> mInProgressAvatarFetches = new ArrayList<>();
168 private final HashSet<Jid> mLowPingTimeoutMode = new HashSet<>();
169 public DatabaseBackend databaseBackend;
170 private ReplacingSerialSingleThreadExecutor mContactMergerExecutor = new ReplacingSerialSingleThreadExecutor(true);
171 private long mLastActivity = 0;
172 private ContentObserver contactObserver = new ContentObserver(null) {
173 @Override
174 public void onChange(boolean selfChange) {
175 super.onChange(selfChange);
176 Intent intent = new Intent(getApplicationContext(),
177 XmppConnectionService.class);
178 intent.setAction(ACTION_MERGE_PHONE_CONTACTS);
179 startService(intent);
180 }
181 };
182 private FileBackend fileBackend = new FileBackend(this);
183 private MemorizingTrustManager mMemorizingTrustManager;
184 private NotificationService mNotificationService = new NotificationService(this);
185 private ShortcutService mShortcutService = new ShortcutService(this);
186 private AtomicBoolean mInitialAddressbookSyncCompleted = new AtomicBoolean(false);
187 private AtomicBoolean mForceForegroundService = new AtomicBoolean(false);
188 private OnMessagePacketReceived mMessageParser = new MessageParser(this);
189 private OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
190 private IqParser mIqParser = new IqParser(this);
191 private final OnIqPacketReceived mDefaultIqHandler = (account, packet) -> {
192 if (packet.getType() != IqPacket.TYPE.RESULT) {
193 Element error = packet.findChild("error");
194 String text = error != null ? error.findChildContent("text") : null;
195 if (text != null) {
196 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received iq error - " + text);
197 }
198 }
199 };
200 private MessageGenerator mMessageGenerator = new MessageGenerator(this);
201 public OnContactStatusChanged onContactStatusChanged = (contact, online) -> {
202 Conversation conversation = find(getConversations(), contact);
203 if (conversation != null) {
204 if (online) {
205 if (contact.getPresences().size() == 1) {
206 sendUnsentMessages(conversation);
207 }
208 }
209 }
210 };
211 private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
212 private List<Account> accounts;
213 private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
214 this);
215 private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
216
217 @Override
218 public void onJinglePacketReceived(Account account, JinglePacket packet) {
219 mJingleConnectionManager.deliverPacket(account, packet);
220 }
221 };
222 private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(
223 this);
224 private AvatarService mAvatarService = new AvatarService(this);
225 private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
226 private PushManagementService mPushManagementService = new PushManagementService(this);
227 private OnConversationUpdate mOnConversationUpdate = null;
228 private final ConversationsFileObserver fileObserver = new ConversationsFileObserver(
229 Environment.getExternalStorageDirectory().getAbsolutePath()
230 ) {
231 @Override
232 public void onEvent(int event, String path) {
233 markFileDeleted(path);
234 }
235 };
236 private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
237
238 @Override
239 public void onMessageAcknowledged(Account account, String uuid) {
240 for (final Conversation conversation : getConversations()) {
241 if (conversation.getAccount() == account) {
242 Message message = conversation.findUnsentMessageWithUuid(uuid);
243 if (message != null) {
244 markMessage(message, Message.STATUS_SEND);
245 }
246 }
247 }
248 }
249 };
250 private int convChangedListenerCount = 0;
251 private OnShowErrorToast mOnShowErrorToast = null;
252 private int showErrorToastListenerCount = 0;
253 private int unreadCount = -1;
254 private OnAccountUpdate mOnAccountUpdate = null;
255 private OnCaptchaRequested mOnCaptchaRequested = null;
256 private int accountChangedListenerCount = 0;
257 private int captchaRequestedListenerCount = 0;
258 private OnRosterUpdate mOnRosterUpdate = null;
259 private OnUpdateBlocklist mOnUpdateBlocklist = null;
260 private int updateBlocklistListenerCount = 0;
261 private int rosterChangedListenerCount = 0;
262 private OnMucRosterUpdate mOnMucRosterUpdate = null;
263 private int mucRosterChangedListenerCount = 0;
264 private OnKeyStatusUpdated mOnKeyStatusUpdated = null;
265 private final OnBindListener mOnBindListener = new OnBindListener() {
266
267 @Override
268 public void onBind(final Account account) {
269 synchronized (mInProgressAvatarFetches) {
270 for (Iterator<String> iterator = mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
271 final String KEY = iterator.next();
272 if (KEY.startsWith(account.getJid().asBareJid() + "_")) {
273 iterator.remove();
274 }
275 }
276 }
277 boolean needsUpdating = account.setOption(Account.OPTION_LOGGED_IN_SUCCESSFULLY, true);
278 needsUpdating |= account.setOption(Account.OPTION_HTTP_UPLOAD_AVAILABLE, account.getXmppConnection().getFeatures().httpUpload(0));
279 if (needsUpdating) {
280 databaseBackend.updateAccount(account);
281 }
282 account.getRoster().clearPresences();
283 mJingleConnectionManager.cancelInTransmission();
284 fetchRosterFromServer(account);
285 fetchBookmarks(account);
286 final boolean flexible = account.getXmppConnection().getFeatures().flexibleOfflineMessageRetrieval();
287 final boolean catchup = getMessageArchiveService().inCatchup(account);
288 if (flexible && catchup) {
289 sendIqPacket(account, mIqGenerator.purgeOfflineMessages(), (acc, packet) -> {
290 if (packet.getType() == IqPacket.TYPE.RESULT) {
291 Log.d(Config.LOGTAG, acc.getJid().asBareJid() + ": successfully purged offline messages");
292 }
293 });
294 }
295 sendPresence(account);
296 if (mPushManagementService.available(account)) {
297 mPushManagementService.registerPushTokenOnServer(account);
298 }
299 connectMultiModeConversations(account);
300 syncDirtyContacts(account);
301 }
302 };
303 private int keyStatusUpdatedListenerCount = 0;
304 private AtomicLong mLastExpiryRun = new AtomicLong(0);
305 private SecureRandom mRandom;
306 private LruCache<Pair<String, String>, ServiceDiscoveryResult> discoCache = new LruCache<>(20);
307 private OnStatusChanged statusListener = new OnStatusChanged() {
308
309 @Override
310 public void onStatusChanged(final Account account) {
311 XmppConnection connection = account.getXmppConnection();
312 if (mOnAccountUpdate != null) {
313 mOnAccountUpdate.onAccountUpdate();
314 }
315 if (account.getStatus() == Account.State.ONLINE) {
316 synchronized (mLowPingTimeoutMode) {
317 if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
318 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": leaving low ping timeout mode");
319 }
320 }
321 if (account.setShowErrorNotification(true)) {
322 databaseBackend.updateAccount(account);
323 }
324 mMessageArchiveService.executePendingQueries(account);
325 if (connection != null && connection.getFeatures().csi()) {
326 if (checkListeners()) {
327 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " sending csi//inactive");
328 connection.sendInactive();
329 } else {
330 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " sending csi//active");
331 connection.sendActive();
332 }
333 }
334 List<Conversation> conversations = getConversations();
335 for (Conversation conversation : conversations) {
336 if (conversation.getAccount() == account && !account.pendingConferenceJoins.contains(conversation)) {
337 sendUnsentMessages(conversation);
338 }
339 }
340 for (Conversation conversation : account.pendingConferenceLeaves) {
341 leaveMuc(conversation);
342 }
343 account.pendingConferenceLeaves.clear();
344 for (Conversation conversation : account.pendingConferenceJoins) {
345 joinMuc(conversation);
346 }
347 account.pendingConferenceJoins.clear();
348 scheduleWakeUpCall(Config.PING_MAX_INTERVAL, account.getUuid().hashCode());
349 } else if (account.getStatus() == Account.State.OFFLINE || account.getStatus() == Account.State.DISABLED) {
350 resetSendingToWaiting(account);
351 if (account.isEnabled() && isInLowPingTimeoutMode(account)) {
352 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": went into offline state during low ping mode. reconnecting now");
353 reconnectAccount(account, true, false);
354 } else {
355 int timeToReconnect = mRandom.nextInt(10) + 2;
356 scheduleWakeUpCall(timeToReconnect, account.getUuid().hashCode());
357 }
358 } else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
359 databaseBackend.updateAccount(account);
360 reconnectAccount(account, true, false);
361 } else if (account.getStatus() != Account.State.CONNECTING && account.getStatus() != Account.State.NO_INTERNET) {
362 resetSendingToWaiting(account);
363 if (connection != null && account.getStatus().isAttemptReconnect()) {
364 final int next = connection.getTimeToNextAttempt();
365 final boolean lowPingTimeoutMode = isInLowPingTimeoutMode(account);
366 if (next <= 0) {
367 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error connecting account. reconnecting now. lowPingTimeout=" + Boolean.toString(lowPingTimeoutMode));
368 reconnectAccount(account, true, false);
369 } else {
370 final int attempt = connection.getAttempt() + 1;
371 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error connecting account. try again in " + next + "s for the " + attempt + " time. lowPingTimeout=" + Boolean.toString(lowPingTimeoutMode));
372 scheduleWakeUpCall(next, account.getUuid().hashCode());
373 }
374 }
375 }
376 getNotificationService().updateErrorNotification();
377 }
378 };
379 private OpenPgpServiceConnection pgpServiceConnection;
380 private PgpEngine mPgpEngine = null;
381 private WakeLock wakeLock;
382 private PowerManager pm;
383 private LruCache<String, Bitmap> mBitmapCache;
384 private EventReceiver mEventReceiver = new EventReceiver();
385
386 private static String generateFetchKey(Account account, final Avatar avatar) {
387 return account.getJid().asBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum;
388 }
389
390 private boolean isInLowPingTimeoutMode(Account account) {
391 synchronized (mLowPingTimeoutMode) {
392 return mLowPingTimeoutMode.contains(account.getJid().asBareJid());
393 }
394 }
395
396 public void startForcingForegroundNotification() {
397 mForceForegroundService.set(true);
398 toggleForegroundService();
399 }
400
401 public void stopForcingForegroundNotification() {
402 mForceForegroundService.set(false);
403 toggleForegroundService();
404 }
405
406 public boolean areMessagesInitialized() {
407 return this.restoredFromDatabaseLatch.getCount() == 0;
408 }
409
410 public PgpEngine getPgpEngine() {
411 if (!Config.supportOpenPgp()) {
412 return null;
413 } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
414 if (this.mPgpEngine == null) {
415 this.mPgpEngine = new PgpEngine(new OpenPgpApi(
416 getApplicationContext(),
417 pgpServiceConnection.getService()), this);
418 }
419 return mPgpEngine;
420 } else {
421 return null;
422 }
423
424 }
425
426 public OpenPgpApi getOpenPgpApi() {
427 if (!Config.supportOpenPgp()) {
428 return null;
429 } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
430 return new OpenPgpApi(this, pgpServiceConnection.getService());
431 } else {
432 return null;
433 }
434 }
435
436 public FileBackend getFileBackend() {
437 return this.fileBackend;
438 }
439
440 public AvatarService getAvatarService() {
441 return this.mAvatarService;
442 }
443
444 public void attachLocationToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
445 int encryption = conversation.getNextEncryption();
446 if (encryption == Message.ENCRYPTION_PGP) {
447 encryption = Message.ENCRYPTION_DECRYPTED;
448 }
449 Message message = new Message(conversation, uri.toString(), encryption);
450 if (conversation.getNextCounterpart() != null) {
451 message.setCounterpart(conversation.getNextCounterpart());
452 }
453 if (encryption == Message.ENCRYPTION_DECRYPTED) {
454 getPgpEngine().encrypt(message, callback);
455 } else {
456 sendMessage(message);
457 callback.success(message);
458 }
459 }
460
461 public void attachFileToConversation(final Conversation conversation, final Uri uri, final String type, final UiCallback<Message> callback) {
462 if (FileBackend.weOwnFile(this, uri)) {
463 Log.d(Config.LOGTAG, "trying to attach file that belonged to us");
464 callback.error(R.string.security_error_invalid_file_access, null);
465 return;
466 }
467 final Message message;
468 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
469 message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
470 } else {
471 message = new Message(conversation, "", conversation.getNextEncryption());
472 }
473 message.setCounterpart(conversation.getNextCounterpart());
474 message.setType(Message.TYPE_FILE);
475 final AttachFileToConversationRunnable runnable = new AttachFileToConversationRunnable(this, uri, type, message, callback);
476 if (runnable.isVideoMessage()) {
477 mVideoCompressionExecutor.execute(runnable);
478 } else {
479 mFileAddingExecutor.execute(runnable);
480 }
481 }
482
483 public void attachImageToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
484 if (FileBackend.weOwnFile(this, uri)) {
485 Log.d(Config.LOGTAG, "trying to attach file that belonged to us");
486 callback.error(R.string.security_error_invalid_file_access, null);
487 return;
488 }
489
490 final String mimeType = MimeUtils.guessMimeTypeFromUri(this, uri);
491 final String compressPictures = getCompressPicturesPreference();
492
493 if ("never".equals(compressPictures)
494 || ("auto".equals(compressPictures) && getFileBackend().useImageAsIs(uri))
495 || (mimeType != null && mimeType.endsWith("/gif"))) {
496 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": not compressing picture. sending as file");
497 attachFileToConversation(conversation, uri, mimeType, callback);
498 return;
499 }
500 final Message message;
501 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
502 message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
503 } else {
504 message = new Message(conversation, "", conversation.getNextEncryption());
505 }
506 message.setCounterpart(conversation.getNextCounterpart());
507 message.setType(Message.TYPE_IMAGE);
508 mFileAddingExecutor.execute(() -> {
509 try {
510 getFileBackend().copyImageToPrivateStorage(message, uri);
511 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
512 final PgpEngine pgpEngine = getPgpEngine();
513 if (pgpEngine != null) {
514 pgpEngine.encrypt(message, callback);
515 } else if (callback != null) {
516 callback.error(R.string.unable_to_connect_to_keychain, null);
517 }
518 } else {
519 sendMessage(message);
520 callback.success(message);
521 }
522 } catch (final FileBackend.FileCopyException e) {
523 callback.error(e.getResId(), message);
524 }
525 });
526 }
527
528 public Conversation find(Bookmark bookmark) {
529 return find(bookmark.getAccount(), bookmark.getJid());
530 }
531
532 public Conversation find(final Account account, final Jid jid) {
533 return find(getConversations(), account, jid);
534 }
535
536 @Override
537 public int onStartCommand(Intent intent, int flags, int startId) {
538 final String action = intent == null ? null : intent.getAction();
539 String pushedAccountHash = null;
540 boolean interactive = false;
541 if (action != null) {
542 final String uuid = intent.getStringExtra("uuid");
543 switch (action) {
544 case ConnectivityManager.CONNECTIVITY_ACTION:
545 if (hasInternetConnection() && Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
546 resetAllAttemptCounts(true, false);
547 }
548 break;
549 case ACTION_MERGE_PHONE_CONTACTS:
550 if (restoredFromDatabaseLatch.getCount() == 0) {
551 loadPhoneContacts();
552 }
553 return START_STICKY;
554 case Intent.ACTION_SHUTDOWN:
555 logoutAndSave(true);
556 return START_NOT_STICKY;
557 case ACTION_CLEAR_NOTIFICATION:
558 mNotificationExecutor.execute(() -> {
559 try {
560 final Conversation c = findConversationByUuid(uuid);
561 if (c != null) {
562 mNotificationService.clear(c);
563 } else {
564 mNotificationService.clear();
565 }
566 restoredFromDatabaseLatch.await();
567
568 } catch (InterruptedException e) {
569 Log.d(Config.LOGTAG, "unable to process clear notification");
570 }
571 });
572 break;
573 case ACTION_DISMISS_ERROR_NOTIFICATIONS:
574 dismissErrorNotifications();
575 break;
576 case ACTION_TRY_AGAIN:
577 resetAllAttemptCounts(false, true);
578 interactive = true;
579 break;
580 case ACTION_REPLY_TO_CONVERSATION:
581 Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
582 if (remoteInput == null) {
583 break;
584 }
585 final CharSequence body = remoteInput.getCharSequence("text_reply");
586 final boolean dismissNotification = intent.getBooleanExtra("dismiss_notification", false);
587 if (body == null || body.length() <= 0) {
588 break;
589 }
590 mNotificationExecutor.execute(() -> {
591 try {
592 restoredFromDatabaseLatch.await();
593 final Conversation c = findConversationByUuid(uuid);
594 if (c != null) {
595 directReply(c, body.toString(), dismissNotification);
596 }
597 } catch (InterruptedException e) {
598 Log.d(Config.LOGTAG, "unable to process direct reply");
599 }
600 });
601 break;
602 case ACTION_MARK_AS_READ:
603 mNotificationExecutor.execute(() -> {
604 final Conversation c = findConversationByUuid(uuid);
605 if (c == null) {
606 Log.d(Config.LOGTAG, "received mark read intent for unknown conversation (" + uuid + ")");
607 return;
608 }
609 try {
610 restoredFromDatabaseLatch.await();
611 sendReadMarker(c, null);
612 } catch (InterruptedException e) {
613 Log.d(Config.LOGTAG, "unable to process notification read marker for conversation " + c.getName());
614 }
615
616 });
617 break;
618 case ACTION_SNOOZE:
619 mNotificationExecutor.execute(() -> {
620 final Conversation c = findConversationByUuid(uuid);
621 if (c == null) {
622 Log.d(Config.LOGTAG, "received snooze intent for unknown conversation (" + uuid + ")");
623 return;
624 }
625 c.setMutedTill(System.currentTimeMillis() + 30 * 60 * 1000);
626 mNotificationService.clear(c);
627 updateConversation(c);
628 });
629 case AudioManager.RINGER_MODE_CHANGED_ACTION:
630 if (dndOnSilentMode()) {
631 refreshAllPresences();
632 }
633 break;
634 case Intent.ACTION_SCREEN_ON:
635 deactivateGracePeriod();
636 case Intent.ACTION_SCREEN_OFF:
637 if (awayWhenScreenOff()) {
638 refreshAllPresences();
639 }
640 break;
641 case ACTION_GCM_TOKEN_REFRESH:
642 refreshAllGcmTokens();
643 break;
644 case ACTION_IDLE_PING:
645 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
646 scheduleNextIdlePing();
647 }
648 break;
649 case ACTION_GCM_MESSAGE_RECEIVED:
650 Log.d(Config.LOGTAG, "gcm push message arrived in service. extras=" + intent.getExtras());
651 pushedAccountHash = intent.getStringExtra("account");
652 break;
653 case Intent.ACTION_SEND:
654 Uri uri = intent.getData();
655 if (uri != null) {
656 Log.d(Config.LOGTAG, "received uri permission for " + uri.toString());
657 }
658 return START_STICKY;
659 }
660 }
661 synchronized (this) {
662 this.wakeLock.acquire();
663 boolean pingNow = ConnectivityManager.CONNECTIVITY_ACTION.equals(action);
664 HashSet<Account> pingCandidates = new HashSet<>();
665 for (Account account : accounts) {
666 pingNow |= processAccountState(account,
667 interactive,
668 "ui".equals(action),
669 CryptoHelper.getAccountFingerprint(account).equals(pushedAccountHash),
670 pingCandidates);
671 }
672 if (pingNow) {
673 for (Account account : pingCandidates) {
674 final boolean lowTimeout = isInLowPingTimeoutMode(account);
675 account.getXmppConnection().sendPing();
676 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " send ping (action=" + action + ",lowTimeout=" + Boolean.toString(lowTimeout) + ")");
677 scheduleWakeUpCall(lowTimeout ? Config.LOW_PING_TIMEOUT : Config.PING_TIMEOUT, account.getUuid().hashCode());
678 }
679 }
680 if (wakeLock.isHeld()) {
681 try {
682 wakeLock.release();
683 } catch (final RuntimeException ignored) {
684 }
685 }
686 }
687 if (SystemClock.elapsedRealtime() - mLastExpiryRun.get() >= Config.EXPIRY_INTERVAL) {
688 expireOldMessages();
689 }
690 return START_STICKY;
691 }
692
693 private boolean processAccountState(Account account, boolean interactive, boolean isUiAction, boolean isAccountPushed, HashSet<Account> pingCandidates) {
694 boolean pingNow = false;
695 if (account.getStatus().isAttemptReconnect()) {
696 if (!hasInternetConnection()) {
697 account.setStatus(Account.State.NO_INTERNET);
698 if (statusListener != null) {
699 statusListener.onStatusChanged(account);
700 }
701 } else {
702 if (account.getStatus() == Account.State.NO_INTERNET) {
703 account.setStatus(Account.State.OFFLINE);
704 if (statusListener != null) {
705 statusListener.onStatusChanged(account);
706 }
707 }
708 if (account.getStatus() == Account.State.ONLINE) {
709 synchronized (mLowPingTimeoutMode) {
710 long lastReceived = account.getXmppConnection().getLastPacketReceived();
711 long lastSent = account.getXmppConnection().getLastPingSent();
712 long pingInterval = isUiAction ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
713 long msToNextPing = (Math.max(lastReceived, lastSent) + pingInterval) - SystemClock.elapsedRealtime();
714 int pingTimeout = mLowPingTimeoutMode.contains(account.getJid().asBareJid()) ? Config.LOW_PING_TIMEOUT * 1000 : Config.PING_TIMEOUT * 1000;
715 long pingTimeoutIn = (lastSent + pingTimeout) - SystemClock.elapsedRealtime();
716 if (lastSent > lastReceived) {
717 if (pingTimeoutIn < 0) {
718 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ping timeout");
719 this.reconnectAccount(account, true, interactive);
720 } else {
721 int secs = (int) (pingTimeoutIn / 1000);
722 this.scheduleWakeUpCall(secs, account.getUuid().hashCode());
723 }
724 } else {
725 pingCandidates.add(account);
726 if (isAccountPushed) {
727 pingNow = true;
728 if (mLowPingTimeoutMode.add(account.getJid().asBareJid())) {
729 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": entering low ping timeout mode");
730 }
731 } else if (msToNextPing <= 0) {
732 pingNow = true;
733 } else {
734 this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
735 if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
736 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": leaving low ping timeout mode");
737 }
738 }
739 }
740 }
741 } else if (account.getStatus() == Account.State.OFFLINE) {
742 reconnectAccount(account, true, interactive);
743 } else if (account.getStatus() == Account.State.CONNECTING) {
744 long secondsSinceLastConnect = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000;
745 long secondsSinceLastDisco = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastDiscoStarted()) / 1000;
746 long discoTimeout = Config.CONNECT_DISCO_TIMEOUT - secondsSinceLastDisco;
747 long timeout = Config.CONNECT_TIMEOUT - secondsSinceLastConnect;
748 if (timeout < 0) {
749 Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting (secondsSinceLast=" + secondsSinceLastConnect + ")");
750 account.getXmppConnection().resetAttemptCount(false);
751 reconnectAccount(account, true, interactive);
752 } else if (discoTimeout < 0) {
753 account.getXmppConnection().sendDiscoTimeout();
754 scheduleWakeUpCall((int) Math.min(timeout, discoTimeout), account.getUuid().hashCode());
755 } else {
756 scheduleWakeUpCall((int) Math.min(timeout, discoTimeout), account.getUuid().hashCode());
757 }
758 } else {
759 if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
760 reconnectAccount(account, true, interactive);
761 }
762 }
763 }
764 }
765 return pingNow;
766 }
767
768 public boolean isDataSaverDisabled() {
769 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
770 ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
771 return !connectivityManager.isActiveNetworkMetered()
772 || connectivityManager.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
773 } else {
774 return true;
775 }
776 }
777
778 private void directReply(Conversation conversation, String body, final boolean dismissAfterReply) {
779 Message message = new Message(conversation, body, conversation.getNextEncryption());
780 message.markUnread();
781 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
782 getPgpEngine().encrypt(message, new UiCallback<Message>() {
783 @Override
784 public void success(Message message) {
785 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
786 sendMessage(message);
787 if (dismissAfterReply) {
788 markRead(message.getConversation(), true);
789 } else {
790 mNotificationService.pushFromDirectReply(message);
791 }
792 }
793
794 @Override
795 public void error(int errorCode, Message object) {
796
797 }
798
799 @Override
800 public void userInputRequried(PendingIntent pi, Message object) {
801
802 }
803 });
804 } else {
805 sendMessage(message);
806 if (dismissAfterReply) {
807 markRead(conversation, true);
808 } else {
809 mNotificationService.pushFromDirectReply(message);
810 }
811 }
812 }
813
814 private boolean dndOnSilentMode() {
815 return getBooleanPreference(SettingsActivity.DND_ON_SILENT_MODE, R.bool.dnd_on_silent_mode);
816 }
817
818 private boolean manuallyChangePresence() {
819 return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
820 }
821
822 private boolean treatVibrateAsSilent() {
823 return getBooleanPreference(SettingsActivity.TREAT_VIBRATE_AS_SILENT, R.bool.treat_vibrate_as_silent);
824 }
825
826 private boolean awayWhenScreenOff() {
827 return getBooleanPreference(SettingsActivity.AWAY_WHEN_SCREEN_IS_OFF, R.bool.away_when_screen_off);
828 }
829
830 private String getCompressPicturesPreference() {
831 return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression));
832 }
833
834 private Presence.Status getTargetPresence() {
835 if (dndOnSilentMode() && isPhoneSilenced()) {
836 return Presence.Status.DND;
837 } else if (awayWhenScreenOff() && !isInteractive()) {
838 return Presence.Status.AWAY;
839 } else {
840 return Presence.Status.ONLINE;
841 }
842 }
843
844 @SuppressLint("NewApi")
845 @SuppressWarnings("deprecation")
846 public boolean isInteractive() {
847 final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
848
849 final boolean isScreenOn;
850 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
851 isScreenOn = pm.isScreenOn();
852 } else {
853 isScreenOn = pm.isInteractive();
854 }
855 return isScreenOn;
856 }
857
858 private boolean isPhoneSilenced() {
859 AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
860 try {
861 if (treatVibrateAsSilent()) {
862 return audioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL;
863 } else {
864 return audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT;
865 }
866 } catch (Throwable throwable) {
867 Log.d(Config.LOGTAG, "platform bug in isPhoneSilenced (" + throwable.getMessage() + ")");
868 return false;
869 }
870 }
871
872 private void resetAllAttemptCounts(boolean reallyAll, boolean retryImmediately) {
873 Log.d(Config.LOGTAG, "resetting all attempt counts");
874 for (Account account : accounts) {
875 if (account.hasErrorStatus() || reallyAll) {
876 final XmppConnection connection = account.getXmppConnection();
877 if (connection != null) {
878 connection.resetAttemptCount(retryImmediately);
879 }
880 }
881 if (account.setShowErrorNotification(true)) {
882 databaseBackend.updateAccount(account);
883 }
884 }
885 mNotificationService.updateErrorNotification();
886 }
887
888 private void dismissErrorNotifications() {
889 for (final Account account : this.accounts) {
890 if (account.hasErrorStatus()) {
891 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": dismissing error notification");
892 if (account.setShowErrorNotification(false)) {
893 databaseBackend.updateAccount(account);
894 }
895 }
896 }
897 }
898
899 private void expireOldMessages() {
900 expireOldMessages(false);
901 }
902
903 public void expireOldMessages(final boolean resetHasMessagesLeftOnServer) {
904 mLastExpiryRun.set(SystemClock.elapsedRealtime());
905 mDatabaseWriterExecutor.execute(() -> {
906 long timestamp = getAutomaticMessageDeletionDate();
907 if (timestamp > 0) {
908 databaseBackend.expireOldMessages(timestamp);
909 synchronized (XmppConnectionService.this.conversations) {
910 for (Conversation conversation : XmppConnectionService.this.conversations) {
911 conversation.expireOldMessages(timestamp);
912 if (resetHasMessagesLeftOnServer) {
913 conversation.messagesLoaded.set(true);
914 conversation.setHasMessagesLeftOnServer(true);
915 }
916 }
917 }
918 updateConversationUi();
919 }
920 });
921 }
922
923 public boolean hasInternetConnection() {
924 final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
925 try {
926 final NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
927 return activeNetwork != null && activeNetwork.isConnected();
928 } catch (RuntimeException e) {
929 Log.d(Config.LOGTAG, "unable to check for internet connection", e);
930 return true; //if internet connection can not be checked it is probably best to just try
931 }
932 }
933
934 @SuppressLint("TrulyRandom")
935 @Override
936 public void onCreate() {
937 OmemoSetting.load(this);
938 ExceptionHelper.init(getApplicationContext());
939 PRNGFixes.apply();
940 Resolver.init(this);
941 this.mRandom = new SecureRandom();
942 updateMemorizingTrustmanager();
943 final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
944 final int cacheSize = maxMemory / 8;
945 this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
946 @Override
947 protected int sizeOf(final String key, final Bitmap bitmap) {
948 return bitmap.getByteCount() / 1024;
949 }
950 };
951
952 Log.d(Config.LOGTAG, "initializing database...");
953 this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
954 Log.d(Config.LOGTAG, "restoring accounts...");
955 this.accounts = databaseBackend.getAccounts();
956 final SharedPreferences.Editor editor = getPreferences().edit();
957 if (this.accounts.size() == 0 && Arrays.asList("Sony", "Sony Ericsson").contains(Build.MANUFACTURER)) {
958 editor.putBoolean(SettingsActivity.KEEP_FOREGROUND_SERVICE, true);
959 Log.d(Config.LOGTAG, Build.MANUFACTURER + " is on blacklist. enabling foreground service");
960 }
961 editor.putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts()).apply();
962 editor.apply();
963
964 restoreFromDatabase();
965
966 getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
967 new Thread(fileObserver::startWatching).start();
968 if (Config.supportOpenPgp()) {
969 this.pgpServiceConnection = new OpenPgpServiceConnection(this, "org.sufficientlysecure.keychain", new OpenPgpServiceConnection.OnBound() {
970 @Override
971 public void onBound(IOpenPgpService2 service) {
972 for (Account account : accounts) {
973 final PgpDecryptionService pgp = account.getPgpDecryptionService();
974 if (pgp != null) {
975 pgp.continueDecryption(true);
976 }
977 }
978 }
979
980 @Override
981 public void onError(Exception e) {
982 }
983 });
984 this.pgpServiceConnection.bindToService();
985 }
986
987 this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
988 this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "XmppConnectionService");
989
990 toggleForegroundService();
991 updateUnreadCountBadge();
992 toggleScreenEventReceiver();
993 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
994 scheduleNextIdlePing();
995 }
996 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
997 registerReceiver(this.mEventReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
998 }
999 }
1000
1001 @Override
1002 public void onTrimMemory(int level) {
1003 super.onTrimMemory(level);
1004 if (level >= TRIM_MEMORY_COMPLETE) {
1005 Log.d(Config.LOGTAG, "clear cache due to low memory");
1006 getBitmapCache().evictAll();
1007 }
1008 }
1009
1010 @Override
1011 public void onDestroy() {
1012 try {
1013 unregisterReceiver(this.mEventReceiver);
1014 } catch (IllegalArgumentException e) {
1015 //ignored
1016 }
1017 fileObserver.stopWatching();
1018 super.onDestroy();
1019 }
1020
1021 public void toggleScreenEventReceiver() {
1022 if (awayWhenScreenOff() && !manuallyChangePresence()) {
1023 final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
1024 filter.addAction(Intent.ACTION_SCREEN_OFF);
1025 registerReceiver(this.mEventReceiver, filter);
1026 } else {
1027 try {
1028 unregisterReceiver(this.mEventReceiver);
1029 } catch (IllegalArgumentException e) {
1030 //ignored
1031 }
1032 }
1033 }
1034
1035 public void toggleForegroundService() {
1036 if (mForceForegroundService.get() || (keepForegroundService() && hasEnabledAccounts())) {
1037 startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
1038 Log.d(Config.LOGTAG, "started foreground service");
1039 } else {
1040 stopForeground(true);
1041 Log.d(Config.LOGTAG, "stopped foreground service");
1042 }
1043 }
1044
1045 public boolean keepForegroundService() {
1046 return getBooleanPreference(SettingsActivity.KEEP_FOREGROUND_SERVICE, R.bool.enable_foreground_service);
1047 }
1048
1049 @Override
1050 public void onTaskRemoved(final Intent rootIntent) {
1051 super.onTaskRemoved(rootIntent);
1052 if (keepForegroundService() || mForceForegroundService.get()) {
1053 Log.d(Config.LOGTAG, "ignoring onTaskRemoved because foreground service is activated");
1054 } else {
1055 this.logoutAndSave(false);
1056 }
1057 }
1058
1059 private void logoutAndSave(boolean stop) {
1060 int activeAccounts = 0;
1061 for (final Account account : accounts) {
1062 if (account.getStatus() != Account.State.DISABLED) {
1063 databaseBackend.writeRoster(account.getRoster());
1064 activeAccounts++;
1065 }
1066 if (account.getXmppConnection() != null) {
1067 new Thread(() -> disconnect(account, false)).start();
1068 }
1069 }
1070 if (stop || activeAccounts == 0) {
1071 Log.d(Config.LOGTAG, "good bye");
1072 stopSelf();
1073 }
1074 }
1075
1076 public void scheduleWakeUpCall(int seconds, int requestCode) {
1077 final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
1078 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1079 Intent intent = new Intent(this, EventReceiver.class);
1080 intent.setAction("ping");
1081 PendingIntent pendingIntent = PendingIntent.getBroadcast(this, requestCode, intent, 0);
1082 try {
1083 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1084 } catch (RuntimeException e) {
1085 Log.e(Config.LOGTAG, "unable to schedule alarm for ping", e);
1086 }
1087 }
1088
1089 @TargetApi(Build.VERSION_CODES.M)
1090 private void scheduleNextIdlePing() {
1091 final long timeToWake = SystemClock.elapsedRealtime() + (Config.IDLE_PING_INTERVAL * 1000);
1092 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1093 Intent intent = new Intent(this, EventReceiver.class);
1094 intent.setAction(ACTION_IDLE_PING);
1095 PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
1096 try {
1097 alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1098 } catch (RuntimeException e) {
1099 Log.d(Config.LOGTAG, "unable to schedule alarm for idle ping", e);
1100 }
1101 }
1102
1103 public XmppConnection createConnection(final Account account) {
1104 final XmppConnection connection = new XmppConnection(account, this);
1105 connection.setOnMessagePacketReceivedListener(this.mMessageParser);
1106 connection.setOnStatusChangedListener(this.statusListener);
1107 connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
1108 connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
1109 connection.setOnJinglePacketReceivedListener(this.jingleListener);
1110 connection.setOnBindListener(this.mOnBindListener);
1111 connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
1112 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
1113 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
1114 AxolotlService axolotlService = account.getAxolotlService();
1115 if (axolotlService != null) {
1116 connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
1117 }
1118 return connection;
1119 }
1120
1121 public void sendChatState(Conversation conversation) {
1122 if (sendChatStates()) {
1123 MessagePacket packet = mMessageGenerator.generateChatState(conversation);
1124 sendMessagePacket(conversation.getAccount(), packet);
1125 }
1126 }
1127
1128 private void sendFileMessage(final Message message, final boolean delay) {
1129 Log.d(Config.LOGTAG, "send file message");
1130 final Account account = message.getConversation().getAccount();
1131 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1132 || message.getConversation().getMode() == Conversation.MODE_MULTI) {
1133 mHttpConnectionManager.createNewUploadConnection(message, delay);
1134 } else {
1135 mJingleConnectionManager.createNewConnection(message);
1136 }
1137 }
1138
1139 public void sendMessage(final Message message) {
1140 sendMessage(message, false, false);
1141 }
1142
1143 private void sendMessage(final Message message, final boolean resend, final boolean delay) {
1144 final Account account = message.getConversation().getAccount();
1145 if (account.setShowErrorNotification(true)) {
1146 databaseBackend.updateAccount(account);
1147 mNotificationService.updateErrorNotification();
1148 }
1149 final Conversation conversation = message.getConversation();
1150 account.deactivateGracePeriod();
1151 MessagePacket packet = null;
1152 final boolean addToConversation = (conversation.getMode() != Conversation.MODE_MULTI
1153 || !Patches.BAD_MUC_REFLECTION.contains(account.getServerIdentity()))
1154 && !message.edited();
1155 boolean saveInDb = addToConversation;
1156 message.setStatus(Message.STATUS_WAITING);
1157
1158 if (account.isOnlineAndConnected()) {
1159 switch (message.getEncryption()) {
1160 case Message.ENCRYPTION_NONE:
1161 if (message.needsUploading()) {
1162 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1163 || conversation.getMode() == Conversation.MODE_MULTI
1164 || message.fixCounterpart()) {
1165 this.sendFileMessage(message, delay);
1166 } else {
1167 break;
1168 }
1169 } else {
1170 packet = mMessageGenerator.generateChat(message);
1171 }
1172 break;
1173 case Message.ENCRYPTION_PGP:
1174 case Message.ENCRYPTION_DECRYPTED:
1175 if (message.needsUploading()) {
1176 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1177 || conversation.getMode() == Conversation.MODE_MULTI
1178 || message.fixCounterpart()) {
1179 this.sendFileMessage(message, delay);
1180 } else {
1181 break;
1182 }
1183 } else {
1184 packet = mMessageGenerator.generatePgpChat(message);
1185 }
1186 break;
1187 case Message.ENCRYPTION_AXOLOTL:
1188 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1189 if (message.needsUploading()) {
1190 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1191 || conversation.getMode() == Conversation.MODE_MULTI
1192 || message.fixCounterpart()) {
1193 this.sendFileMessage(message, delay);
1194 } else {
1195 break;
1196 }
1197 } else {
1198 XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
1199 if (axolotlMessage == null) {
1200 account.getAxolotlService().preparePayloadMessage(message, delay);
1201 } else {
1202 packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
1203 }
1204 }
1205 break;
1206
1207 }
1208 if (packet != null) {
1209 if (account.getXmppConnection().getFeatures().sm()
1210 || (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1211 message.setStatus(Message.STATUS_UNSEND);
1212 } else {
1213 message.setStatus(Message.STATUS_SEND);
1214 }
1215 }
1216 } else {
1217 switch (message.getEncryption()) {
1218 case Message.ENCRYPTION_DECRYPTED:
1219 if (!message.needsUploading()) {
1220 String pgpBody = message.getEncryptedBody();
1221 String decryptedBody = message.getBody();
1222 message.setBody(pgpBody); //TODO might throw NPE
1223 message.setEncryption(Message.ENCRYPTION_PGP);
1224 if (message.edited()) {
1225 message.setBody(decryptedBody);
1226 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1227 databaseBackend.updateMessage(message, message.getEditedId());
1228 updateConversationUi();
1229 return;
1230 } else {
1231 databaseBackend.createMessage(message);
1232 saveInDb = false;
1233 message.setBody(decryptedBody);
1234 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1235 }
1236 }
1237 break;
1238 case Message.ENCRYPTION_AXOLOTL:
1239 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1240 break;
1241 }
1242 }
1243
1244
1245 boolean mucMessage = conversation.getMode() == Conversation.MODE_MULTI && message.getType() != Message.TYPE_PRIVATE;
1246 if (mucMessage) {
1247 message.setCounterpart(conversation.getMucOptions().getSelf().getFullJid());
1248 }
1249
1250 if (resend) {
1251 if (packet != null && addToConversation) {
1252 if (account.getXmppConnection().getFeatures().sm() || mucMessage) {
1253 markMessage(message, Message.STATUS_UNSEND);
1254 } else {
1255 markMessage(message, Message.STATUS_SEND);
1256 }
1257 }
1258 } else {
1259 if (addToConversation) {
1260 conversation.add(message);
1261 }
1262 if (saveInDb) {
1263 databaseBackend.createMessage(message);
1264 } else if (message.edited()) {
1265 databaseBackend.updateMessage(message, message.getEditedId());
1266 }
1267 updateConversationUi();
1268 }
1269 if (packet != null) {
1270 if (delay) {
1271 mMessageGenerator.addDelay(packet, message.getTimeSent());
1272 }
1273 if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1274 if (this.sendChatStates()) {
1275 packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
1276 }
1277 }
1278 sendMessagePacket(account, packet);
1279 }
1280 }
1281
1282 private void sendUnsentMessages(final Conversation conversation) {
1283 conversation.findWaitingMessages(new Conversation.OnMessageFound() {
1284
1285 @Override
1286 public void onMessageFound(Message message) {
1287 resendMessage(message, true);
1288 }
1289 });
1290 }
1291
1292 public void resendMessage(final Message message, final boolean delay) {
1293 sendMessage(message, true, delay);
1294 }
1295
1296 public void fetchRosterFromServer(final Account account) {
1297 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1298 if (!"".equals(account.getRosterVersion())) {
1299 Log.d(Config.LOGTAG, account.getJid().asBareJid()
1300 + ": fetching roster version " + account.getRosterVersion());
1301 } else {
1302 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching roster");
1303 }
1304 iqPacket.query(Namespace.ROSTER).setAttribute("ver", account.getRosterVersion());
1305 sendIqPacket(account, iqPacket, mIqParser);
1306 }
1307
1308 public void fetchBookmarks(final Account account) {
1309 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1310 final Element query = iqPacket.query("jabber:iq:private");
1311 query.addChild("storage", "storage:bookmarks");
1312 final OnIqPacketReceived callback = new OnIqPacketReceived() {
1313
1314 @Override
1315 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1316 if (packet.getType() == IqPacket.TYPE.RESULT) {
1317 final Element query = packet.query();
1318 final HashMap<Jid, Bookmark> bookmarks = new HashMap<>();
1319 final Element storage = query.findChild("storage", "storage:bookmarks");
1320 final boolean autojoin = respectAutojoin();
1321 if (storage != null) {
1322 for (final Element item : storage.getChildren()) {
1323 if (item.getName().equals("conference")) {
1324 final Bookmark bookmark = Bookmark.parse(item, account);
1325 Bookmark old = bookmarks.put(bookmark.getJid(), bookmark);
1326 if (old != null && old.getBookmarkName() != null && bookmark.getBookmarkName() == null) {
1327 bookmark.setBookmarkName(old.getBookmarkName());
1328 }
1329 Conversation conversation = find(bookmark);
1330 if (conversation != null) {
1331 bookmark.setConversation(conversation);
1332 } else if (bookmark.autojoin() && bookmark.getJid() != null && autojoin) {
1333 conversation = findOrCreateConversation(account, bookmark.getJid(), true, true, false);
1334 bookmark.setConversation(conversation);
1335 }
1336 }
1337 }
1338 }
1339 account.setBookmarks(new CopyOnWriteArrayList<>(bookmarks.values()));
1340 } else {
1341 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not fetch bookmarks");
1342 }
1343 }
1344 };
1345 sendIqPacket(account, iqPacket, callback);
1346 }
1347
1348 public void pushBookmarks(Account account) {
1349 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks");
1350 IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1351 Element query = iqPacket.query("jabber:iq:private");
1352 Element storage = query.addChild("storage", "storage:bookmarks");
1353 for (Bookmark bookmark : account.getBookmarks()) {
1354 storage.addChild(bookmark);
1355 }
1356 sendIqPacket(account, iqPacket, mDefaultIqHandler);
1357 }
1358
1359 private void restoreFromDatabase() {
1360 synchronized (this.conversations) {
1361 final Map<String, Account> accountLookupTable = new Hashtable<>();
1362 for (Account account : this.accounts) {
1363 accountLookupTable.put(account.getUuid(), account);
1364 }
1365 Log.d(Config.LOGTAG, "restoring conversations...");
1366 final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
1367 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1368 for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
1369 Conversation conversation = iterator.next();
1370 Account account = accountLookupTable.get(conversation.getAccountUuid());
1371 if (account != null) {
1372 conversation.setAccount(account);
1373 } else {
1374 Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
1375 iterator.remove();
1376 }
1377 }
1378 long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
1379 Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
1380 Runnable runnable = () -> {
1381 long deletionDate = getAutomaticMessageDeletionDate();
1382 mLastExpiryRun.set(SystemClock.elapsedRealtime());
1383 if (deletionDate > 0) {
1384 Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
1385 databaseBackend.expireOldMessages(deletionDate);
1386 }
1387 Log.d(Config.LOGTAG, "restoring roster...");
1388 for (Account account : accounts) {
1389 databaseBackend.readRoster(account.getRoster());
1390 account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1391 }
1392 getBitmapCache().evictAll();
1393 loadPhoneContacts();
1394 Log.d(Config.LOGTAG, "restoring messages...");
1395 final long startMessageRestore = SystemClock.elapsedRealtime();
1396 final Conversation quickLoad = QuickLoader.get(this.conversations);
1397 if (quickLoad != null) {
1398 restoreMessages(quickLoad);
1399 updateConversationUi();
1400 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1401 Log.d(Config.LOGTAG,"quickly restored "+quickLoad.getName()+" after " + diffMessageRestore + "ms");
1402 }
1403 for (Conversation conversation : this.conversations) {
1404 if (quickLoad != conversation) {
1405 restoreMessages(conversation);
1406 }
1407 }
1408 mNotificationService.finishBacklog(false);
1409 restoredFromDatabaseLatch.countDown();
1410 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1411 Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
1412 updateConversationUi();
1413 };
1414 mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
1415 }
1416 }
1417
1418 private void restoreMessages(Conversation conversation) {
1419 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1420 checkDeletedFiles(conversation);
1421 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
1422 conversation.findUnreadMessages(message -> mNotificationService.pushFromBacklog(message));
1423 }
1424
1425 public void loadPhoneContacts() {
1426 mContactMergerExecutor.execute(() -> PhoneHelper.loadPhoneContacts(XmppConnectionService.this, new OnPhoneContactsLoadedListener() {
1427 @Override
1428 public void onPhoneContactsLoaded(List<Bundle> phoneContacts) {
1429 Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1430 for (Account account : accounts) {
1431 List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
1432 for (Bundle phoneContact : phoneContacts) {
1433 Jid jid;
1434 try {
1435 jid = Jid.of(phoneContact.getString("jid"));
1436 } catch (final IllegalArgumentException e) {
1437 continue;
1438 }
1439 final Contact contact = account.getRoster().getContact(jid);
1440 String systemAccount = phoneContact.getInt("phoneid")
1441 + "#"
1442 + phoneContact.getString("lookup");
1443 contact.setSystemAccount(systemAccount);
1444 boolean needsCacheClean = contact.setPhotoUri(phoneContact.getString("photouri"));
1445 needsCacheClean |= contact.setSystemName(phoneContact.getString("displayname"));
1446 if (needsCacheClean) {
1447 getAvatarService().clear(contact);
1448 }
1449 withSystemAccounts.remove(contact);
1450 }
1451 for (Contact contact : withSystemAccounts) {
1452 contact.setSystemAccount(null);
1453 boolean needsCacheClean = contact.setPhotoUri(null);
1454 needsCacheClean |= contact.setSystemName(null);
1455 if (needsCacheClean) {
1456 getAvatarService().clear(contact);
1457 }
1458 }
1459 }
1460 Log.d(Config.LOGTAG, "finished merging phone contacts");
1461 mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
1462 updateAccountUi();
1463 }
1464 }));
1465 }
1466
1467
1468 public void syncRoster(final Account account) {
1469 mRosterSyncTaskManager.execute(account, () -> databaseBackend.writeRoster(account.getRoster()));
1470 }
1471
1472 public List<Conversation> getConversations() {
1473 return this.conversations;
1474 }
1475
1476 private void checkDeletedFiles(Conversation conversation) {
1477 conversation.findMessagesWithFiles(message -> {
1478 if (!getFileBackend().isFileAvailable(message)) {
1479 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1480 final int s = message.getStatus();
1481 if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1482 markMessage(message, Message.STATUS_SEND_FAILED);
1483 }
1484 }
1485 });
1486 }
1487
1488 private void markFileDeleted(final String path) {
1489 Log.d(Config.LOGTAG, "deleted file " + path);
1490 for (Conversation conversation : getConversations()) {
1491 conversation.findMessagesWithFiles(message -> {
1492 DownloadableFile file = fileBackend.getFile(message);
1493 if (file.getAbsolutePath().equals(path)) {
1494 if (!file.exists()) {
1495 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1496 final int s = message.getStatus();
1497 if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1498 markMessage(message, Message.STATUS_SEND_FAILED);
1499 } else {
1500 updateConversationUi();
1501 }
1502 } else {
1503 Log.d(Config.LOGTAG, "found matching message for file " + path + " but file still exists");
1504 }
1505 }
1506 });
1507 }
1508 }
1509
1510 public void populateWithOrderedConversations(final List<Conversation> list) {
1511 populateWithOrderedConversations(list, true);
1512 }
1513
1514 public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1515 list.clear();
1516 if (includeNoFileUpload) {
1517 list.addAll(getConversations());
1518 } else {
1519 for (Conversation conversation : getConversations()) {
1520 if (conversation.getMode() == Conversation.MODE_SINGLE
1521 || conversation.getAccount().httpUploadAvailable()) {
1522 list.add(conversation);
1523 }
1524 }
1525 }
1526 try {
1527 Collections.sort(list);
1528 } catch (IllegalArgumentException e) {
1529 //ignore
1530 }
1531 }
1532
1533 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1534 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
1535 return;
1536 } else if (timestamp == 0) {
1537 return;
1538 }
1539 Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1540 final Runnable runnable = () -> {
1541 final Account account = conversation.getAccount();
1542 List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
1543 if (messages.size() > 0) {
1544 conversation.addAll(0, messages);
1545 checkDeletedFiles(conversation);
1546 callback.onMoreMessagesLoaded(messages.size(), conversation);
1547 } else if (conversation.hasMessagesLeftOnServer()
1548 && account.isOnlineAndConnected()
1549 && conversation.getLastClearHistory().getTimestamp() == 0) {
1550 final boolean mamAvailable;
1551 if (conversation.getMode() == Conversation.MODE_SINGLE) {
1552 mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
1553 } else {
1554 mamAvailable = conversation.getMucOptions().mamSupport();
1555 }
1556 if (mamAvailable) {
1557 MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
1558 if (query != null) {
1559 query.setCallback(callback);
1560 callback.informUser(R.string.fetching_history_from_server);
1561 } else {
1562 callback.informUser(R.string.not_fetching_history_retention_period);
1563 }
1564
1565 }
1566 }
1567 };
1568 mDatabaseReaderExecutor.execute(runnable);
1569 }
1570
1571 public List<Account> getAccounts() {
1572 return this.accounts;
1573 }
1574
1575 public List<Conversation> findAllConferencesWith(Contact contact) {
1576 ArrayList<Conversation> results = new ArrayList<>();
1577 for (Conversation conversation : conversations) {
1578 if (conversation.getMode() == Conversation.MODE_MULTI
1579 && conversation.getMucOptions().isContactInRoom(contact)) {
1580 results.add(conversation);
1581 }
1582 }
1583 return results;
1584 }
1585
1586 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1587 for (final Conversation conversation : haystack) {
1588 if (conversation.getContact() == contact) {
1589 return conversation;
1590 }
1591 }
1592 return null;
1593 }
1594
1595 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1596 if (jid == null) {
1597 return null;
1598 }
1599 for (final Conversation conversation : haystack) {
1600 if ((account == null || conversation.getAccount() == account)
1601 && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
1602 return conversation;
1603 }
1604 }
1605 return null;
1606 }
1607
1608 public boolean isConversationsListEmpty(final Conversation ignore) {
1609 synchronized (this.conversations) {
1610 final int size = this.conversations.size();
1611 if (size == 0) {
1612 return true;
1613 } else if (size == 1) {
1614 return this.conversations.get(0) == ignore;
1615 } else {
1616 return false;
1617 }
1618 }
1619 }
1620
1621 public boolean isConversationStillOpen(final Conversation conversation) {
1622 synchronized (this.conversations) {
1623 for (Conversation current : this.conversations) {
1624 if (current == conversation) {
1625 return true;
1626 }
1627 }
1628 }
1629 return false;
1630 }
1631
1632 public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
1633 return this.findOrCreateConversation(account, jid, muc, false, async);
1634 }
1635
1636 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
1637 return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
1638 }
1639
1640 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
1641 synchronized (this.conversations) {
1642 Conversation conversation = find(account, jid);
1643 if (conversation != null) {
1644 return conversation;
1645 }
1646 conversation = databaseBackend.findConversation(account, jid);
1647 final boolean loadMessagesFromDb;
1648 if (conversation != null) {
1649 conversation.setStatus(Conversation.STATUS_AVAILABLE);
1650 conversation.setAccount(account);
1651 if (muc) {
1652 conversation.setMode(Conversation.MODE_MULTI);
1653 conversation.setContactJid(jid);
1654 } else {
1655 conversation.setMode(Conversation.MODE_SINGLE);
1656 conversation.setContactJid(jid.asBareJid());
1657 }
1658 databaseBackend.updateConversation(conversation);
1659 loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
1660 } else {
1661 String conversationName;
1662 Contact contact = account.getRoster().getContact(jid);
1663 if (contact != null) {
1664 conversationName = contact.getDisplayName();
1665 } else {
1666 conversationName = jid.getLocal();
1667 }
1668 if (muc) {
1669 conversation = new Conversation(conversationName, account, jid,
1670 Conversation.MODE_MULTI);
1671 } else {
1672 conversation = new Conversation(conversationName, account, jid.asBareJid(),
1673 Conversation.MODE_SINGLE);
1674 }
1675 this.databaseBackend.createConversation(conversation);
1676 loadMessagesFromDb = false;
1677 }
1678 final Conversation c = conversation;
1679 final Runnable runnable = () -> {
1680 if (loadMessagesFromDb) {
1681 c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
1682 updateConversationUi();
1683 c.messagesLoaded.set(true);
1684 }
1685 if (account.getXmppConnection() != null
1686 && !c.getContact().isBlocked()
1687 && account.getXmppConnection().getFeatures().mam()
1688 && !muc) {
1689 if (query == null) {
1690 mMessageArchiveService.query(c);
1691 } else {
1692 if (query.getConversation() == null) {
1693 mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
1694 }
1695 }
1696 }
1697 checkDeletedFiles(c);
1698 if (joinAfterCreate) {
1699 joinMuc(c);
1700 }
1701 };
1702 if (async) {
1703 mDatabaseReaderExecutor.execute(runnable);
1704 } else {
1705 runnable.run();
1706 }
1707 this.conversations.add(conversation);
1708 updateConversationUi();
1709 return conversation;
1710 }
1711 }
1712
1713 public void archiveConversation(Conversation conversation) {
1714 getNotificationService().clear(conversation);
1715 conversation.setStatus(Conversation.STATUS_ARCHIVED);
1716 conversation.setNextMessage(null);
1717 synchronized (this.conversations) {
1718 getMessageArchiveService().kill(conversation);
1719 if (conversation.getMode() == Conversation.MODE_MULTI) {
1720 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1721 Bookmark bookmark = conversation.getBookmark();
1722 if (bookmark != null && bookmark.autojoin() && respectAutojoin()) {
1723 bookmark.setAutojoin(false);
1724 pushBookmarks(bookmark.getAccount());
1725 }
1726 }
1727 leaveMuc(conversation);
1728 } else {
1729 if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1730 Log.d(Config.LOGTAG, "Canceling presence request from " + conversation.getJid().toString());
1731 sendPresencePacket(
1732 conversation.getAccount(),
1733 mPresenceGenerator.stopPresenceUpdatesTo(conversation.getContact())
1734 );
1735 }
1736 }
1737 updateConversation(conversation);
1738 this.conversations.remove(conversation);
1739 updateConversationUi();
1740 }
1741 }
1742
1743 public void createAccount(final Account account) {
1744 account.initAccountServices(this);
1745 databaseBackend.createAccount(account);
1746 this.accounts.add(account);
1747 this.reconnectAccountInBackground(account);
1748 updateAccountUi();
1749 syncEnabledAccountSetting();
1750 toggleForegroundService();
1751 }
1752
1753 private void syncEnabledAccountSetting() {
1754 getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts()).apply();
1755 }
1756
1757 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1758 new Thread(() -> {
1759 try {
1760 final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
1761 final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
1762 if (cert == null) {
1763 callback.informUser(R.string.unable_to_parse_certificate);
1764 return;
1765 }
1766 Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
1767 if (info == null) {
1768 callback.informUser(R.string.certificate_does_not_contain_jid);
1769 return;
1770 }
1771 if (findAccountByJid(info.first) == null) {
1772 Account account = new Account(info.first, "");
1773 account.setPrivateKeyAlias(alias);
1774 account.setOption(Account.OPTION_DISABLED, true);
1775 account.setDisplayName(info.second);
1776 createAccount(account);
1777 callback.onAccountCreated(account);
1778 if (Config.X509_VERIFICATION) {
1779 try {
1780 getMemorizingTrustManager().getNonInteractive(account.getJid().getDomain()).checkClientTrusted(chain, "RSA");
1781 } catch (CertificateException e) {
1782 callback.informUser(R.string.certificate_chain_is_not_trusted);
1783 }
1784 }
1785 } else {
1786 callback.informUser(R.string.account_already_exists);
1787 }
1788 } catch (Exception e) {
1789 e.printStackTrace();
1790 callback.informUser(R.string.unable_to_parse_certificate);
1791 }
1792 }).start();
1793
1794 }
1795
1796 public void updateKeyInAccount(final Account account, final String alias) {
1797 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
1798 try {
1799 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1800 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
1801 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1802 if (info == null) {
1803 showErrorToastInUi(R.string.certificate_does_not_contain_jid);
1804 return;
1805 }
1806 if (account.getJid().asBareJid().equals(info.first)) {
1807 account.setPrivateKeyAlias(alias);
1808 account.setDisplayName(info.second);
1809 databaseBackend.updateAccount(account);
1810 if (Config.X509_VERIFICATION) {
1811 try {
1812 getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1813 } catch (CertificateException e) {
1814 showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1815 }
1816 account.getAxolotlService().regenerateKeys(true);
1817 }
1818 } else {
1819 showErrorToastInUi(R.string.jid_does_not_match_certificate);
1820 }
1821 } catch (Exception e) {
1822 e.printStackTrace();
1823 }
1824 }
1825
1826 public boolean updateAccount(final Account account) {
1827 if (databaseBackend.updateAccount(account)) {
1828 account.setShowErrorNotification(true);
1829 this.statusListener.onStatusChanged(account);
1830 databaseBackend.updateAccount(account);
1831 reconnectAccountInBackground(account);
1832 updateAccountUi();
1833 getNotificationService().updateErrorNotification();
1834 toggleForegroundService();
1835 syncEnabledAccountSetting();
1836 return true;
1837 } else {
1838 return false;
1839 }
1840 }
1841
1842 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1843 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1844 sendIqPacket(account, iq, (a, packet) -> {
1845 if (packet.getType() == IqPacket.TYPE.RESULT) {
1846 a.setPassword(newPassword);
1847 a.setOption(Account.OPTION_MAGIC_CREATE, false);
1848 databaseBackend.updateAccount(a);
1849 callback.onPasswordChangeSucceeded();
1850 } else {
1851 callback.onPasswordChangeFailed();
1852 }
1853 });
1854 }
1855
1856 public void deleteAccount(final Account account) {
1857 synchronized (this.conversations) {
1858 for (final Conversation conversation : conversations) {
1859 if (conversation.getAccount() == account) {
1860 if (conversation.getMode() == Conversation.MODE_MULTI) {
1861 leaveMuc(conversation);
1862 }
1863 conversations.remove(conversation);
1864 }
1865 }
1866 if (account.getXmppConnection() != null) {
1867 new Thread(() -> disconnect(account, true)).start();
1868 }
1869 final Runnable runnable = () -> {
1870 if (!databaseBackend.deleteAccount(account)) {
1871 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
1872 }
1873 };
1874 mDatabaseWriterExecutor.execute(runnable);
1875 this.accounts.remove(account);
1876 this.mRosterSyncTaskManager.clear(account);
1877 updateAccountUi();
1878 getNotificationService().updateErrorNotification();
1879 syncEnabledAccountSetting();
1880 }
1881 }
1882
1883 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1884 synchronized (this) {
1885 this.mLastActivity = System.currentTimeMillis();
1886 if (checkListeners()) {
1887 switchToForeground();
1888 }
1889 this.mOnConversationUpdate = listener;
1890 this.mNotificationService.setIsInForeground(true);
1891 if (this.convChangedListenerCount < 2) {
1892 this.convChangedListenerCount++;
1893 }
1894 }
1895 }
1896
1897 public void removeOnConversationListChangedListener() {
1898 synchronized (this) {
1899 this.convChangedListenerCount--;
1900 if (this.convChangedListenerCount <= 0) {
1901 this.convChangedListenerCount = 0;
1902 this.mOnConversationUpdate = null;
1903 this.mNotificationService.setIsInForeground(false);
1904 if (checkListeners()) {
1905 switchToBackground();
1906 }
1907 }
1908 }
1909 }
1910
1911 public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1912 synchronized (this) {
1913 if (checkListeners()) {
1914 switchToForeground();
1915 }
1916 this.mOnShowErrorToast = onShowErrorToast;
1917 if (this.showErrorToastListenerCount < 2) {
1918 this.showErrorToastListenerCount++;
1919 }
1920 }
1921 this.mOnShowErrorToast = onShowErrorToast;
1922 }
1923
1924 public void removeOnShowErrorToastListener() {
1925 synchronized (this) {
1926 this.showErrorToastListenerCount--;
1927 if (this.showErrorToastListenerCount <= 0) {
1928 this.showErrorToastListenerCount = 0;
1929 this.mOnShowErrorToast = null;
1930 if (checkListeners()) {
1931 switchToBackground();
1932 }
1933 }
1934 }
1935 }
1936
1937 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1938 synchronized (this) {
1939 if (checkListeners()) {
1940 switchToForeground();
1941 }
1942 this.mOnAccountUpdate = listener;
1943 if (this.accountChangedListenerCount < 2) {
1944 this.accountChangedListenerCount++;
1945 }
1946 }
1947 }
1948
1949 public void removeOnAccountListChangedListener() {
1950 synchronized (this) {
1951 this.accountChangedListenerCount--;
1952 if (this.accountChangedListenerCount <= 0) {
1953 this.mOnAccountUpdate = null;
1954 this.accountChangedListenerCount = 0;
1955 if (checkListeners()) {
1956 switchToBackground();
1957 }
1958 }
1959 }
1960 }
1961
1962 public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
1963 synchronized (this) {
1964 if (checkListeners()) {
1965 switchToForeground();
1966 }
1967 this.mOnCaptchaRequested = listener;
1968 if (this.captchaRequestedListenerCount < 2) {
1969 this.captchaRequestedListenerCount++;
1970 }
1971 }
1972 }
1973
1974 public void removeOnCaptchaRequestedListener() {
1975 synchronized (this) {
1976 this.captchaRequestedListenerCount--;
1977 if (this.captchaRequestedListenerCount <= 0) {
1978 this.mOnCaptchaRequested = null;
1979 this.captchaRequestedListenerCount = 0;
1980 if (checkListeners()) {
1981 switchToBackground();
1982 }
1983 }
1984 }
1985 }
1986
1987 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1988 synchronized (this) {
1989 if (checkListeners()) {
1990 switchToForeground();
1991 }
1992 this.mOnRosterUpdate = listener;
1993 if (this.rosterChangedListenerCount < 2) {
1994 this.rosterChangedListenerCount++;
1995 }
1996 }
1997 }
1998
1999 public void removeOnRosterUpdateListener() {
2000 synchronized (this) {
2001 this.rosterChangedListenerCount--;
2002 if (this.rosterChangedListenerCount <= 0) {
2003 this.rosterChangedListenerCount = 0;
2004 this.mOnRosterUpdate = null;
2005 if (checkListeners()) {
2006 switchToBackground();
2007 }
2008 }
2009 }
2010 }
2011
2012 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2013 synchronized (this) {
2014 if (checkListeners()) {
2015 switchToForeground();
2016 }
2017 this.mOnUpdateBlocklist = listener;
2018 if (this.updateBlocklistListenerCount < 2) {
2019 this.updateBlocklistListenerCount++;
2020 }
2021 }
2022 }
2023
2024 public void removeOnUpdateBlocklistListener() {
2025 synchronized (this) {
2026 this.updateBlocklistListenerCount--;
2027 if (this.updateBlocklistListenerCount <= 0) {
2028 this.updateBlocklistListenerCount = 0;
2029 this.mOnUpdateBlocklist = null;
2030 if (checkListeners()) {
2031 switchToBackground();
2032 }
2033 }
2034 }
2035 }
2036
2037 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2038 synchronized (this) {
2039 if (checkListeners()) {
2040 switchToForeground();
2041 }
2042 this.mOnKeyStatusUpdated = listener;
2043 if (this.keyStatusUpdatedListenerCount < 2) {
2044 this.keyStatusUpdatedListenerCount++;
2045 }
2046 }
2047 }
2048
2049 public void removeOnNewKeysAvailableListener() {
2050 synchronized (this) {
2051 this.keyStatusUpdatedListenerCount--;
2052 if (this.keyStatusUpdatedListenerCount <= 0) {
2053 this.keyStatusUpdatedListenerCount = 0;
2054 this.mOnKeyStatusUpdated = null;
2055 if (checkListeners()) {
2056 switchToBackground();
2057 }
2058 }
2059 }
2060 }
2061
2062 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2063 synchronized (this) {
2064 if (checkListeners()) {
2065 switchToForeground();
2066 }
2067 this.mOnMucRosterUpdate = listener;
2068 if (this.mucRosterChangedListenerCount < 2) {
2069 this.mucRosterChangedListenerCount++;
2070 }
2071 }
2072 }
2073
2074 public void removeOnMucRosterUpdateListener() {
2075 synchronized (this) {
2076 this.mucRosterChangedListenerCount--;
2077 if (this.mucRosterChangedListenerCount <= 0) {
2078 this.mucRosterChangedListenerCount = 0;
2079 this.mOnMucRosterUpdate = null;
2080 if (checkListeners()) {
2081 switchToBackground();
2082 }
2083 }
2084 }
2085 }
2086
2087 public boolean checkListeners() {
2088 return (this.mOnAccountUpdate == null
2089 && this.mOnConversationUpdate == null
2090 && this.mOnRosterUpdate == null
2091 && this.mOnCaptchaRequested == null
2092 && this.mOnUpdateBlocklist == null
2093 && this.mOnShowErrorToast == null
2094 && this.mOnKeyStatusUpdated == null);
2095 }
2096
2097 private void switchToForeground() {
2098 final boolean broadcastLastActivity = broadcastLastActivity();
2099 for (Conversation conversation : getConversations()) {
2100 if (conversation.getMode() == Conversation.MODE_MULTI) {
2101 conversation.getMucOptions().resetChatState();
2102 } else {
2103 conversation.setIncomingChatState(Config.DEFAULT_CHATSTATE);
2104 }
2105 }
2106 for (Account account : getAccounts()) {
2107 if (account.getStatus() == Account.State.ONLINE) {
2108 account.deactivateGracePeriod();
2109 final XmppConnection connection = account.getXmppConnection();
2110 if (connection != null) {
2111 if (connection.getFeatures().csi()) {
2112 connection.sendActive();
2113 }
2114 if (broadcastLastActivity) {
2115 sendPresence(account, false); //send new presence but don't include idle because we are not
2116 }
2117 }
2118 }
2119 }
2120 Log.d(Config.LOGTAG, "app switched into foreground");
2121 }
2122
2123 private void switchToBackground() {
2124 final boolean broadcastLastActivity = broadcastLastActivity();
2125 for (Account account : getAccounts()) {
2126 if (account.getStatus() == Account.State.ONLINE) {
2127 XmppConnection connection = account.getXmppConnection();
2128 if (connection != null) {
2129 if (broadcastLastActivity) {
2130 sendPresence(account, true);
2131 }
2132 if (connection.getFeatures().csi()) {
2133 connection.sendInactive();
2134 }
2135 }
2136 }
2137 }
2138 this.mNotificationService.setIsInForeground(false);
2139 Log.d(Config.LOGTAG, "app switched into background");
2140 }
2141
2142 private void connectMultiModeConversations(Account account) {
2143 List<Conversation> conversations = getConversations();
2144 for (Conversation conversation : conversations) {
2145 if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2146 joinMuc(conversation);
2147 }
2148 }
2149 }
2150
2151 public void joinMuc(Conversation conversation) {
2152 joinMuc(conversation, null, false);
2153 }
2154
2155 public void joinMuc(Conversation conversation, boolean followedInvite) {
2156 joinMuc(conversation, null, followedInvite);
2157 }
2158
2159 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2160 joinMuc(conversation, onConferenceJoined, false);
2161 }
2162
2163 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2164 Account account = conversation.getAccount();
2165 account.pendingConferenceJoins.remove(conversation);
2166 account.pendingConferenceLeaves.remove(conversation);
2167 if (account.getStatus() == Account.State.ONLINE) {
2168 sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
2169 conversation.resetMucOptions();
2170 if (onConferenceJoined != null) {
2171 conversation.getMucOptions().flagNoAutoPushConfiguration();
2172 }
2173 conversation.setHasMessagesLeftOnServer(false);
2174 fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2175
2176 private void join(Conversation conversation) {
2177 Account account = conversation.getAccount();
2178 final MucOptions mucOptions = conversation.getMucOptions();
2179 final Jid joinJid = mucOptions.getSelf().getFullJid();
2180 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
2181 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
2182 packet.setTo(joinJid);
2183 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2184 if (conversation.getMucOptions().getPassword() != null) {
2185 x.addChild("password").setContent(mucOptions.getPassword());
2186 }
2187
2188 if (mucOptions.mamSupport()) {
2189 // Use MAM instead of the limited muc history to get history
2190 x.addChild("history").setAttribute("maxchars", "0");
2191 } else {
2192 // Fallback to muc history
2193 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
2194 }
2195 sendPresencePacket(account, packet);
2196 if (onConferenceJoined != null) {
2197 onConferenceJoined.onConferenceJoined(conversation);
2198 }
2199 if (!joinJid.equals(conversation.getJid())) {
2200 conversation.setContactJid(joinJid);
2201 databaseBackend.updateConversation(conversation);
2202 }
2203
2204 if (mucOptions.mamSupport()) {
2205 getMessageArchiveService().catchupMUC(conversation);
2206 }
2207 if (mucOptions.isPrivateAndNonAnonymous()) {
2208 fetchConferenceMembers(conversation);
2209 if (followedInvite && conversation.getBookmark() == null) {
2210 saveConversationAsBookmark(conversation, null);
2211 }
2212 }
2213 sendUnsentMessages(conversation);
2214 }
2215
2216 @Override
2217 public void onConferenceConfigurationFetched(Conversation conversation) {
2218 join(conversation);
2219 }
2220
2221 @Override
2222 public void onFetchFailed(final Conversation conversation, Element error) {
2223 if (error != null && "remote-server-not-found".equals(error.getName())) {
2224 conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2225 updateConversationUi();
2226 } else {
2227 join(conversation);
2228 fetchConferenceConfiguration(conversation);
2229 }
2230 }
2231 });
2232 updateConversationUi();
2233 } else {
2234 account.pendingConferenceJoins.add(conversation);
2235 conversation.resetMucOptions();
2236 conversation.setHasMessagesLeftOnServer(false);
2237 updateConversationUi();
2238 }
2239 }
2240
2241 private void fetchConferenceMembers(final Conversation conversation) {
2242 final Account account = conversation.getAccount();
2243 final AxolotlService axolotlService = account.getAxolotlService();
2244 final String[] affiliations = {"member", "admin", "owner"};
2245 OnIqPacketReceived callback = new OnIqPacketReceived() {
2246
2247 private int i = 0;
2248 private boolean success = true;
2249
2250 @Override
2251 public void onIqPacketReceived(Account account, IqPacket packet) {
2252
2253 Element query = packet.query("http://jabber.org/protocol/muc#admin");
2254 if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2255 for (Element child : query.getChildren()) {
2256 if ("item".equals(child.getName())) {
2257 MucOptions.User user = AbstractParser.parseItem(conversation, child);
2258 if (!user.realJidMatchesAccount()) {
2259 boolean isNew = conversation.getMucOptions().updateUser(user);
2260 Contact contact = user.getContact();
2261 if (isNew
2262 && user.getRealJid() != null
2263 && (contact == null || !contact.mutualPresenceSubscription())
2264 && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
2265 axolotlService.fetchDeviceIds(user.getRealJid());
2266 }
2267 }
2268 }
2269 }
2270 } else {
2271 success = false;
2272 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
2273 }
2274 ++i;
2275 if (i >= affiliations.length) {
2276 List<Jid> members = conversation.getMucOptions().getMembers();
2277 if (success) {
2278 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
2279 boolean changed = false;
2280 for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
2281 Jid jid = iterator.next();
2282 if (!members.contains(jid)) {
2283 iterator.remove();
2284 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
2285 changed = true;
2286 }
2287 }
2288 if (changed) {
2289 conversation.setAcceptedCryptoTargets(cryptoTargets);
2290 updateConversation(conversation);
2291 }
2292 }
2293 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": retrieved members for " + conversation.getJid().asBareJid() + ": " + conversation.getMucOptions().getMembers());
2294 getAvatarService().clear(conversation);
2295 updateMucRosterUi();
2296 updateConversationUi();
2297 }
2298 }
2299 };
2300 for (String affiliation : affiliations) {
2301 sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2302 }
2303 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
2304 }
2305
2306 public void providePasswordForMuc(Conversation conversation, String password) {
2307 if (conversation.getMode() == Conversation.MODE_MULTI) {
2308 conversation.getMucOptions().setPassword(password);
2309 if (conversation.getBookmark() != null) {
2310 if (respectAutojoin()) {
2311 conversation.getBookmark().setAutojoin(true);
2312 }
2313 pushBookmarks(conversation.getAccount());
2314 }
2315 updateConversation(conversation);
2316 joinMuc(conversation);
2317 }
2318 }
2319
2320 private boolean hasEnabledAccounts() {
2321 for (Account account : this.accounts) {
2322 if (account.isEnabled()) {
2323 return true;
2324 }
2325 }
2326 return false;
2327 }
2328
2329 public void persistSelfNick(MucOptions.User self) {
2330 final Conversation conversation = self.getConversation();
2331 Jid full = self.getFullJid();
2332 if (!full.equals(conversation.getJid())) {
2333 Log.d(Config.LOGTAG, "nick changed. updating");
2334 conversation.setContactJid(full);
2335 databaseBackend.updateConversation(conversation);
2336 }
2337
2338 Bookmark bookmark = conversation.getBookmark();
2339 if (bookmark != null && !full.getResource().equals(bookmark.getNick())) {
2340 bookmark.setNick(full.getResource());
2341 pushBookmarks(bookmark.getAccount());
2342 }
2343 }
2344
2345 public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2346 final MucOptions options = conversation.getMucOptions();
2347 final Jid joinJid = options.createJoinJid(nick);
2348 if (joinJid == null) {
2349 return false;
2350 }
2351 if (options.online()) {
2352 Account account = conversation.getAccount();
2353 options.setOnRenameListener(new OnRenameListener() {
2354
2355 @Override
2356 public void onSuccess() {
2357 callback.success(conversation);
2358 }
2359
2360 @Override
2361 public void onFailure() {
2362 callback.error(R.string.nick_in_use, conversation);
2363 }
2364 });
2365
2366 PresencePacket packet = new PresencePacket();
2367 packet.setTo(joinJid);
2368 packet.setFrom(conversation.getAccount().getJid());
2369
2370 String sig = account.getPgpSignature();
2371 if (sig != null) {
2372 packet.addChild("status").setContent("online");
2373 packet.addChild("x", "jabber:x:signed").setContent(sig);
2374 }
2375 sendPresencePacket(account, packet);
2376 } else {
2377 conversation.setContactJid(joinJid);
2378 databaseBackend.updateConversation(conversation);
2379 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2380 Bookmark bookmark = conversation.getBookmark();
2381 if (bookmark != null) {
2382 bookmark.setNick(nick);
2383 pushBookmarks(bookmark.getAccount());
2384 }
2385 joinMuc(conversation);
2386 }
2387 }
2388 return true;
2389 }
2390
2391 public void leaveMuc(Conversation conversation) {
2392 leaveMuc(conversation, false);
2393 }
2394
2395 private void leaveMuc(Conversation conversation, boolean now) {
2396 Account account = conversation.getAccount();
2397 account.pendingConferenceJoins.remove(conversation);
2398 account.pendingConferenceLeaves.remove(conversation);
2399 if (account.getStatus() == Account.State.ONLINE || now) {
2400 sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
2401 conversation.getMucOptions().setOffline();
2402 Bookmark bookmark = conversation.getBookmark();
2403 if (bookmark != null) {
2404 bookmark.setConversation(null);
2405 }
2406 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
2407 } else {
2408 account.pendingConferenceLeaves.add(conversation);
2409 }
2410 }
2411
2412 public String findConferenceServer(final Account account) {
2413 String server;
2414 if (account.getXmppConnection() != null) {
2415 server = account.getXmppConnection().getMucServer();
2416 if (server != null) {
2417 return server;
2418 }
2419 }
2420 for (Account other : getAccounts()) {
2421 if (other != account && other.getXmppConnection() != null) {
2422 server = other.getXmppConnection().getMucServer();
2423 if (server != null) {
2424 return server;
2425 }
2426 }
2427 }
2428 return null;
2429 }
2430
2431 public boolean createAdhocConference(final Account account,
2432 final String subject,
2433 final Iterable<Jid> jids,
2434 final UiCallback<Conversation> callback) {
2435 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2436 if (account.getStatus() == Account.State.ONLINE) {
2437 try {
2438 String server = findConferenceServer(account);
2439 if (server == null) {
2440 if (callback != null) {
2441 callback.error(R.string.no_conference_server_found, null);
2442 }
2443 return false;
2444 }
2445 final Jid jid = Jid.of(new BigInteger(64, getRNG()).toString(Character.MAX_RADIX), server, null);
2446 final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
2447 joinMuc(conversation, new OnConferenceJoined() {
2448 @Override
2449 public void onConferenceJoined(final Conversation conversation) {
2450 pushConferenceConfiguration(conversation, IqGenerator.defaultRoomConfiguration(), new OnConfigurationPushed() {
2451 @Override
2452 public void onPushSucceeded() {
2453 if (subject != null && !subject.trim().isEmpty()) {
2454 pushSubjectToConference(conversation, subject.trim());
2455 }
2456 for (Jid invite : jids) {
2457 invite(conversation, invite);
2458 }
2459 if (account.countPresences() > 1) {
2460 directInvite(conversation, account.getJid().asBareJid());
2461 }
2462 saveConversationAsBookmark(conversation, subject);
2463 if (callback != null) {
2464 callback.success(conversation);
2465 }
2466 }
2467
2468 @Override
2469 public void onPushFailed() {
2470 archiveConversation(conversation);
2471 if (callback != null) {
2472 callback.error(R.string.conference_creation_failed, conversation);
2473 }
2474 }
2475 });
2476 }
2477 });
2478 return true;
2479 } catch (IllegalArgumentException e) {
2480 if (callback != null) {
2481 callback.error(R.string.conference_creation_failed, null);
2482 }
2483 return false;
2484 }
2485 } else {
2486 if (callback != null) {
2487 callback.error(R.string.not_connected_try_again, null);
2488 }
2489 return false;
2490 }
2491 }
2492
2493 public void fetchConferenceConfiguration(final Conversation conversation) {
2494 fetchConferenceConfiguration(conversation, null);
2495 }
2496
2497 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2498 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2499 request.setTo(conversation.getJid().asBareJid());
2500 request.query("http://jabber.org/protocol/disco#info");
2501 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2502 @Override
2503 public void onIqPacketReceived(Account account, IqPacket packet) {
2504 Element query = packet.findChild("query", "http://jabber.org/protocol/disco#info");
2505 if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2506 ArrayList<String> features = new ArrayList<>();
2507 for (Element child : query.getChildren()) {
2508 if (child != null && child.getName().equals("feature")) {
2509 String var = child.getAttribute("var");
2510 if (var != null) {
2511 features.add(var);
2512 }
2513 }
2514 }
2515 Element form = query.findChild("x", Namespace.DATA);
2516 Data data = form == null ? null : Data.parse(form);
2517 if (conversation.getMucOptions().updateConfiguration(features, data)) {
2518 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
2519 updateConversation(conversation);
2520 }
2521 if (callback != null) {
2522 callback.onConferenceConfigurationFetched(conversation);
2523 }
2524 updateConversationUi();
2525 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
2526 if (callback != null) {
2527 callback.onFetchFailed(conversation, packet.getError());
2528 }
2529 }
2530 }
2531 });
2532 }
2533
2534 public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
2535 pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
2536 }
2537
2538 public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
2539 sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
2540 @Override
2541 public void onIqPacketReceived(Account account, IqPacket packet) {
2542 if (packet.getType() == IqPacket.TYPE.RESULT) {
2543 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
2544 Element configuration = pubsub == null ? null : pubsub.findChild("configure");
2545 Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
2546 if (x != null) {
2547 Data data = Data.parse(x);
2548 data.submit(options);
2549 sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
2550 @Override
2551 public void onIqPacketReceived(Account account, IqPacket packet) {
2552 if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
2553 callback.onPushSucceeded();
2554 } else {
2555 Log.d(Config.LOGTAG, packet.toString());
2556 }
2557 }
2558 });
2559 } else if (callback != null) {
2560 callback.onPushFailed();
2561 }
2562 } else if (callback != null) {
2563 callback.onPushFailed();
2564 }
2565 }
2566 });
2567 }
2568
2569 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
2570 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2571 request.setTo(conversation.getJid().asBareJid());
2572 request.query("http://jabber.org/protocol/muc#owner");
2573 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2574 @Override
2575 public void onIqPacketReceived(Account account, IqPacket packet) {
2576 if (packet.getType() == IqPacket.TYPE.RESULT) {
2577 Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
2578 data.submit(options);
2579 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2580 set.setTo(conversation.getJid().asBareJid());
2581 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2582 sendIqPacket(account, set, new OnIqPacketReceived() {
2583 @Override
2584 public void onIqPacketReceived(Account account, IqPacket packet) {
2585 if (callback != null) {
2586 if (packet.getType() == IqPacket.TYPE.RESULT) {
2587 callback.onPushSucceeded();
2588 } else {
2589 callback.onPushFailed();
2590 }
2591 }
2592 }
2593 });
2594 } else {
2595 if (callback != null) {
2596 callback.onPushFailed();
2597 }
2598 }
2599 }
2600 });
2601 }
2602
2603 public void pushSubjectToConference(final Conversation conference, final String subject) {
2604 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2605 this.sendMessagePacket(conference.getAccount(), packet);
2606 final MucOptions mucOptions = conference.getMucOptions();
2607 final MucOptions.User self = mucOptions.getSelf();
2608 if (self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2609 Bundle options = new Bundle();
2610 options.putString("muc#roomconfig_persistentroom", "1");
2611 options.putString("muc#roomconfig_roomname", subject);
2612 this.pushConferenceConfiguration(conference, options, null);
2613 }
2614 }
2615
2616 public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2617 final Jid jid = user.asBareJid();
2618 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2619 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2620 @Override
2621 public void onIqPacketReceived(Account account, IqPacket packet) {
2622 if (packet.getType() == IqPacket.TYPE.RESULT) {
2623 conference.getMucOptions().changeAffiliation(jid, affiliation);
2624 getAvatarService().clear(conference);
2625 callback.onAffiliationChangedSuccessful(jid);
2626 } else {
2627 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2628 }
2629 }
2630 });
2631 }
2632
2633 public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2634 List<Jid> jids = new ArrayList<>();
2635 for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2636 if (user.getAffiliation() == before && user.getRealJid() != null) {
2637 jids.add(user.getRealJid());
2638 }
2639 }
2640 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2641 sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2642 }
2643
2644 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2645 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2646 Log.d(Config.LOGTAG, request.toString());
2647 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2648 @Override
2649 public void onIqPacketReceived(Account account, IqPacket packet) {
2650 Log.d(Config.LOGTAG, packet.toString());
2651 if (packet.getType() == IqPacket.TYPE.RESULT) {
2652 callback.onRoleChangedSuccessful(nick);
2653 } else {
2654 callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2655 }
2656 }
2657 });
2658 }
2659
2660 private void disconnect(Account account, boolean force) {
2661 if ((account.getStatus() == Account.State.ONLINE)
2662 || (account.getStatus() == Account.State.DISABLED)) {
2663 final XmppConnection connection = account.getXmppConnection();
2664 if (!force) {
2665 List<Conversation> conversations = getConversations();
2666 for (Conversation conversation : conversations) {
2667 if (conversation.getAccount() == account) {
2668 if (conversation.getMode() == Conversation.MODE_MULTI) {
2669 leaveMuc(conversation, true);
2670 }
2671 }
2672 }
2673 sendOfflinePresence(account);
2674 }
2675 connection.disconnect(force);
2676 }
2677 }
2678
2679 @Override
2680 public IBinder onBind(Intent intent) {
2681 return mBinder;
2682 }
2683
2684 public void updateMessage(Message message) {
2685 databaseBackend.updateMessage(message);
2686 updateConversationUi();
2687 }
2688
2689 public void updateMessage(Message message, String uuid) {
2690 databaseBackend.updateMessage(message, uuid);
2691 updateConversationUi();
2692 }
2693
2694 protected void syncDirtyContacts(Account account) {
2695 for (Contact contact : account.getRoster().getContacts()) {
2696 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2697 pushContactToServer(contact);
2698 }
2699 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2700 deleteContactOnServer(contact);
2701 }
2702 }
2703 }
2704
2705 public void createContact(Contact contact, boolean autoGrant) {
2706 if (autoGrant) {
2707 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2708 contact.setOption(Contact.Options.ASKING);
2709 }
2710 pushContactToServer(contact);
2711 }
2712
2713 public void pushContactToServer(final Contact contact) {
2714 contact.resetOption(Contact.Options.DIRTY_DELETE);
2715 contact.setOption(Contact.Options.DIRTY_PUSH);
2716 final Account account = contact.getAccount();
2717 if (account.getStatus() == Account.State.ONLINE) {
2718 final boolean ask = contact.getOption(Contact.Options.ASKING);
2719 final boolean sendUpdates = contact
2720 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2721 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2722 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2723 iq.query(Namespace.ROSTER).addChild(contact.asElement());
2724 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2725 if (sendUpdates) {
2726 sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
2727 }
2728 if (ask) {
2729 sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2730 }
2731 } else {
2732 syncRoster(contact.getAccount());
2733 }
2734 }
2735
2736 public void publishAvatar(final Account account, final Uri image, final UiCallback<Avatar> callback) {
2737 new Thread(() -> {
2738 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2739 final int size = Config.AVATAR_SIZE;
2740 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2741 if (avatar != null) {
2742 if (!getFileBackend().save(avatar)) {
2743 callback.error(R.string.error_saving_avatar, avatar);
2744 return;
2745 }
2746 publishAvatar(account, avatar, callback);
2747 } else {
2748 callback.error(R.string.error_publish_avatar_converting, null);
2749 }
2750 }).start();
2751
2752 }
2753
2754 public void publishAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2755 IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2756 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2757
2758 @Override
2759 public void onIqPacketReceived(Account account, IqPacket result) {
2760 if (result.getType() == IqPacket.TYPE.RESULT) {
2761 final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar);
2762 sendIqPacket(account, packet, new OnIqPacketReceived() {
2763 @Override
2764 public void onIqPacketReceived(Account account, IqPacket result) {
2765 if (result.getType() == IqPacket.TYPE.RESULT) {
2766 if (account.setAvatar(avatar.getFilename())) {
2767 getAvatarService().clear(account);
2768 databaseBackend.updateAccount(account);
2769 }
2770 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
2771 if (callback != null) {
2772 callback.success(avatar);
2773 }
2774 } else {
2775 if (callback != null) {
2776 callback.error(R.string.error_publish_avatar_server_reject, avatar);
2777 }
2778 }
2779 }
2780 });
2781 } else {
2782 Element error = result.findChild("error");
2783 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
2784 if (callback != null) {
2785 callback.error(R.string.error_publish_avatar_server_reject, avatar);
2786 }
2787 }
2788 }
2789 });
2790 }
2791
2792 public void republishAvatarIfNeeded(Account account) {
2793 if (account.getAxolotlService().isPepBroken()) {
2794 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
2795 return;
2796 }
2797 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2798 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2799
2800 private Avatar parseAvatar(IqPacket packet) {
2801 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2802 if (pubsub != null) {
2803 Element items = pubsub.findChild("items");
2804 if (items != null) {
2805 return Avatar.parseMetadata(items);
2806 }
2807 }
2808 return null;
2809 }
2810
2811 private boolean errorIsItemNotFound(IqPacket packet) {
2812 Element error = packet.findChild("error");
2813 return packet.getType() == IqPacket.TYPE.ERROR
2814 && error != null
2815 && error.hasChild("item-not-found");
2816 }
2817
2818 @Override
2819 public void onIqPacketReceived(Account account, IqPacket packet) {
2820 if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2821 Avatar serverAvatar = parseAvatar(packet);
2822 if (serverAvatar == null && account.getAvatar() != null) {
2823 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2824 if (avatar != null) {
2825 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
2826 publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2827 } else {
2828 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
2829 }
2830 }
2831 }
2832 }
2833 });
2834 }
2835
2836 public void fetchAvatar(Account account, Avatar avatar) {
2837 fetchAvatar(account, avatar, null);
2838 }
2839
2840 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2841 final String KEY = generateFetchKey(account, avatar);
2842 synchronized (this.mInProgressAvatarFetches) {
2843 if (!this.mInProgressAvatarFetches.contains(KEY)) {
2844 switch (avatar.origin) {
2845 case PEP:
2846 this.mInProgressAvatarFetches.add(KEY);
2847 fetchAvatarPep(account, avatar, callback);
2848 break;
2849 case VCARD:
2850 this.mInProgressAvatarFetches.add(KEY);
2851 fetchAvatarVcard(account, avatar, callback);
2852 break;
2853 }
2854 }
2855 }
2856 }
2857
2858 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2859 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2860 sendIqPacket(account, packet, new OnIqPacketReceived() {
2861
2862 @Override
2863 public void onIqPacketReceived(Account account, IqPacket result) {
2864 synchronized (mInProgressAvatarFetches) {
2865 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2866 }
2867 final String ERROR = account.getJid().asBareJid()
2868 + ": fetching avatar for " + avatar.owner + " failed ";
2869 if (result.getType() == IqPacket.TYPE.RESULT) {
2870 avatar.image = mIqParser.avatarData(result);
2871 if (avatar.image != null) {
2872 if (getFileBackend().save(avatar)) {
2873 if (account.getJid().asBareJid().equals(avatar.owner)) {
2874 if (account.setAvatar(avatar.getFilename())) {
2875 databaseBackend.updateAccount(account);
2876 }
2877 getAvatarService().clear(account);
2878 updateConversationUi();
2879 updateAccountUi();
2880 } else {
2881 Contact contact = account.getRoster()
2882 .getContact(avatar.owner);
2883 contact.setAvatar(avatar);
2884 getAvatarService().clear(contact);
2885 updateConversationUi();
2886 updateRosterUi();
2887 }
2888 if (callback != null) {
2889 callback.success(avatar);
2890 }
2891 Log.d(Config.LOGTAG, account.getJid().asBareJid()
2892 + ": successfully fetched pep avatar for " + avatar.owner);
2893 return;
2894 }
2895 } else {
2896
2897 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2898 }
2899 } else {
2900 Element error = result.findChild("error");
2901 if (error == null) {
2902 Log.d(Config.LOGTAG, ERROR + "(server error)");
2903 } else {
2904 Log.d(Config.LOGTAG, ERROR + error.toString());
2905 }
2906 }
2907 if (callback != null) {
2908 callback.error(0, null);
2909 }
2910
2911 }
2912 });
2913 }
2914
2915 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2916 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2917 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2918 @Override
2919 public void onIqPacketReceived(Account account, IqPacket packet) {
2920 synchronized (mInProgressAvatarFetches) {
2921 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2922 }
2923 if (packet.getType() == IqPacket.TYPE.RESULT) {
2924 Element vCard = packet.findChild("vCard", "vcard-temp");
2925 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2926 String image = photo != null ? photo.findChildContent("BINVAL") : null;
2927 if (image != null) {
2928 avatar.image = image;
2929 if (getFileBackend().save(avatar)) {
2930 Log.d(Config.LOGTAG, account.getJid().asBareJid()
2931 + ": successfully fetched vCard avatar for " + avatar.owner);
2932 if (avatar.owner.isBareJid()) {
2933 if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
2934 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
2935 account.setAvatar(avatar.getFilename());
2936 databaseBackend.updateAccount(account);
2937 getAvatarService().clear(account);
2938 updateAccountUi();
2939 } else {
2940 Contact contact = account.getRoster().getContact(avatar.owner);
2941 contact.setAvatar(avatar);
2942 getAvatarService().clear(contact);
2943 updateRosterUi();
2944 }
2945 updateConversationUi();
2946 } else {
2947 Conversation conversation = find(account, avatar.owner.asBareJid());
2948 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
2949 MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
2950 if (user != null) {
2951 if (user.setAvatar(avatar)) {
2952 getAvatarService().clear(user);
2953 updateConversationUi();
2954 updateMucRosterUi();
2955 }
2956 }
2957 }
2958 }
2959 }
2960 }
2961 }
2962 }
2963 });
2964 }
2965
2966 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2967 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2968 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2969
2970 @Override
2971 public void onIqPacketReceived(Account account, IqPacket packet) {
2972 if (packet.getType() == IqPacket.TYPE.RESULT) {
2973 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2974 if (pubsub != null) {
2975 Element items = pubsub.findChild("items");
2976 if (items != null) {
2977 Avatar avatar = Avatar.parseMetadata(items);
2978 if (avatar != null) {
2979 avatar.owner = account.getJid().asBareJid();
2980 if (fileBackend.isAvatarCached(avatar)) {
2981 if (account.setAvatar(avatar.getFilename())) {
2982 databaseBackend.updateAccount(account);
2983 }
2984 getAvatarService().clear(account);
2985 callback.success(avatar);
2986 } else {
2987 fetchAvatarPep(account, avatar, callback);
2988 }
2989 return;
2990 }
2991 }
2992 }
2993 }
2994 callback.error(0, null);
2995 }
2996 });
2997 }
2998
2999 public void deleteContactOnServer(Contact contact) {
3000 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
3001 contact.resetOption(Contact.Options.DIRTY_PUSH);
3002 contact.setOption(Contact.Options.DIRTY_DELETE);
3003 Account account = contact.getAccount();
3004 if (account.getStatus() == Account.State.ONLINE) {
3005 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3006 Element item = iq.query(Namespace.ROSTER).addChild("item");
3007 item.setAttribute("jid", contact.getJid().toString());
3008 item.setAttribute("subscription", "remove");
3009 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3010 }
3011 }
3012
3013 public void updateConversation(final Conversation conversation) {
3014 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
3015 }
3016
3017 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
3018 synchronized (account) {
3019 XmppConnection connection = account.getXmppConnection();
3020 if (connection == null) {
3021 connection = createConnection(account);
3022 account.setXmppConnection(connection);
3023 }
3024 boolean hasInternet = hasInternetConnection();
3025 if (account.isEnabled() && hasInternet) {
3026 if (!force) {
3027 disconnect(account, false);
3028 }
3029 Thread thread = new Thread(connection);
3030 connection.setInteractive(interactive);
3031 connection.prepareNewConnection();
3032 connection.interrupt();
3033 thread.start();
3034 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
3035 } else {
3036 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
3037 account.getRoster().clearPresences();
3038 connection.resetEverything();
3039 final AxolotlService axolotlService = account.getAxolotlService();
3040 if (axolotlService != null) {
3041 axolotlService.resetBrokenness();
3042 }
3043 if (!hasInternet) {
3044 account.setStatus(Account.State.NO_INTERNET);
3045 }
3046 }
3047 }
3048 }
3049
3050 public void reconnectAccountInBackground(final Account account) {
3051 new Thread(() -> reconnectAccount(account, false, true)).start();
3052 }
3053
3054 public void invite(Conversation conversation, Jid contact) {
3055 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
3056 MessagePacket packet = mMessageGenerator.invite(conversation, contact);
3057 sendMessagePacket(conversation.getAccount(), packet);
3058 }
3059
3060 public void directInvite(Conversation conversation, Jid jid) {
3061 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
3062 sendMessagePacket(conversation.getAccount(), packet);
3063 }
3064
3065 public void resetSendingToWaiting(Account account) {
3066 for (Conversation conversation : getConversations()) {
3067 if (conversation.getAccount() == account) {
3068 conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
3069
3070 @Override
3071 public void onMessageFound(Message message) {
3072 markMessage(message, Message.STATUS_WAITING);
3073 }
3074 });
3075 }
3076 }
3077 }
3078
3079 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
3080 return markMessage(account, recipient, uuid, status, null);
3081 }
3082
3083 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
3084 if (uuid == null) {
3085 return null;
3086 }
3087 for (Conversation conversation : getConversations()) {
3088 if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
3089 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
3090 if (message != null) {
3091 markMessage(message, status, errorMessage);
3092 }
3093 return message;
3094 }
3095 }
3096 return null;
3097 }
3098
3099 public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) {
3100 if (uuid == null) {
3101 return false;
3102 } else {
3103 Message message = conversation.findSentMessageWithUuid(uuid);
3104 if (message != null) {
3105 if (message.getServerMsgId() == null) {
3106 message.setServerMsgId(serverMessageId);
3107 }
3108 markMessage(message, status);
3109 return true;
3110 } else {
3111 return false;
3112 }
3113 }
3114 }
3115
3116 public void markMessage(Message message, int status) {
3117 markMessage(message, status, null);
3118 }
3119
3120
3121 public void markMessage(Message message, int status, String errorMessage) {
3122 final int c = message.getStatus();
3123 if (status == Message.STATUS_SEND_FAILED && (c == Message.STATUS_SEND_RECEIVED || c == Message.STATUS_SEND_DISPLAYED)) {
3124 return;
3125 }
3126 if (status == Message.STATUS_SEND_RECEIVED && c == Message.STATUS_SEND_DISPLAYED) {
3127 return;
3128 }
3129 message.setErrorMessage(errorMessage);
3130 message.setStatus(status);
3131 databaseBackend.updateMessage(message);
3132 updateConversationUi();
3133 }
3134
3135 private SharedPreferences getPreferences() {
3136 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
3137 }
3138
3139 public long getAutomaticMessageDeletionDate() {
3140 final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
3141 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
3142 }
3143
3144 public long getLongPreference(String name, @IntegerRes int res) {
3145 long defaultValue = getResources().getInteger(res);
3146 try {
3147 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
3148 } catch (NumberFormatException e) {
3149 return defaultValue;
3150 }
3151 }
3152
3153 public boolean getBooleanPreference(String name, @BoolRes int res) {
3154 return getPreferences().getBoolean(name, getResources().getBoolean(res));
3155 }
3156
3157 public boolean confirmMessages() {
3158 return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
3159 }
3160
3161 public boolean allowMessageCorrection() {
3162 return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
3163 }
3164
3165 public boolean sendChatStates() {
3166 return getBooleanPreference("chat_states", R.bool.chat_states);
3167 }
3168
3169 private boolean respectAutojoin() {
3170 return getBooleanPreference("autojoin", R.bool.autojoin);
3171 }
3172
3173 public boolean indicateReceived() {
3174 return getBooleanPreference("indicate_received", R.bool.indicate_received);
3175 }
3176
3177 public boolean useTorToConnect() {
3178 return Config.FORCE_ORBOT || getBooleanPreference("use_tor", R.bool.use_tor);
3179 }
3180
3181 public boolean showExtendedConnectionOptions() {
3182 return getBooleanPreference("show_connection_options", R.bool.show_connection_options);
3183 }
3184
3185 public boolean broadcastLastActivity() {
3186 return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
3187 }
3188
3189 public int unreadCount() {
3190 int count = 0;
3191 for (Conversation conversation : getConversations()) {
3192 count += conversation.unreadCount();
3193 }
3194 return count;
3195 }
3196
3197
3198 public void showErrorToastInUi(int resId) {
3199 if (mOnShowErrorToast != null) {
3200 mOnShowErrorToast.onShowErrorToast(resId);
3201 }
3202 }
3203
3204 public void updateConversationUi() {
3205 if (mOnConversationUpdate != null) {
3206 mOnConversationUpdate.onConversationUpdate();
3207 }
3208 }
3209
3210 public void updateAccountUi() {
3211 if (mOnAccountUpdate != null) {
3212 mOnAccountUpdate.onAccountUpdate();
3213 }
3214 }
3215
3216 public void updateRosterUi() {
3217 if (mOnRosterUpdate != null) {
3218 mOnRosterUpdate.onRosterUpdate();
3219 }
3220 }
3221
3222 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3223 if (mOnCaptchaRequested != null) {
3224 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3225 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3226 (int) (captcha.getHeight() * metrics.scaledDensity), false);
3227
3228 mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
3229 return true;
3230 }
3231 return false;
3232 }
3233
3234 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3235 if (mOnUpdateBlocklist != null) {
3236 mOnUpdateBlocklist.OnUpdateBlocklist(status);
3237 }
3238 }
3239
3240 public void updateMucRosterUi() {
3241 if (mOnMucRosterUpdate != null) {
3242 mOnMucRosterUpdate.onMucRosterUpdate();
3243 }
3244 }
3245
3246 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3247 if (mOnKeyStatusUpdated != null) {
3248 mOnKeyStatusUpdated.onKeyStatusUpdated(report);
3249 }
3250 }
3251
3252 public Account findAccountByJid(final Jid accountJid) {
3253 for (Account account : this.accounts) {
3254 if (account.getJid().asBareJid().equals(accountJid.asBareJid())) {
3255 return account;
3256 }
3257 }
3258 return null;
3259 }
3260
3261 public Conversation findConversationByUuid(String uuid) {
3262 for (Conversation conversation : getConversations()) {
3263 if (conversation.getUuid().equals(uuid)) {
3264 return conversation;
3265 }
3266 }
3267 return null;
3268 }
3269
3270 public boolean markRead(final Conversation conversation, boolean dismiss) {
3271 return markRead(conversation, null, dismiss).size() > 0;
3272 }
3273
3274 public void markRead(final Conversation conversation) {
3275 markRead(conversation, null, true);
3276 }
3277
3278 public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
3279 if (dismiss) {
3280 mNotificationService.clear(conversation);
3281 }
3282 final List<Message> readMessages = conversation.markRead(upToUuid);
3283 if (readMessages.size() > 0) {
3284 Runnable runnable = () -> {
3285 for (Message message : readMessages) {
3286 databaseBackend.updateMessage(message);
3287 }
3288 };
3289 mDatabaseWriterExecutor.execute(runnable);
3290 updateUnreadCountBadge();
3291 return readMessages;
3292 } else {
3293 return readMessages;
3294 }
3295 }
3296
3297 public synchronized void updateUnreadCountBadge() {
3298 int count = unreadCount();
3299 if (unreadCount != count) {
3300 Log.d(Config.LOGTAG, "update unread count to " + count);
3301 if (count > 0) {
3302 ShortcutBadger.applyCount(getApplicationContext(), count);
3303 } else {
3304 ShortcutBadger.removeCount(getApplicationContext());
3305 }
3306 unreadCount = count;
3307 }
3308 }
3309
3310 public void sendReadMarker(final Conversation conversation, String upToUuid) {
3311 final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
3312 final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
3313 if (readMessages.size() > 0) {
3314 updateConversationUi();
3315 }
3316 final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
3317 if (confirmMessages()
3318 && markable != null
3319 && (markable.trusted() || isPrivateAndNonAnonymousMuc)
3320 && markable.getRemoteMsgId() != null) {
3321 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
3322 Account account = conversation.getAccount();
3323 final Jid to = markable.getCounterpart();
3324 final boolean groupChat = conversation.getMode() == Conversation.MODE_MULTI;
3325 MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId(), markable.getCounterpart(), groupChat);
3326 this.sendMessagePacket(conversation.getAccount(), packet);
3327 }
3328 }
3329
3330 public SecureRandom getRNG() {
3331 return this.mRandom;
3332 }
3333
3334 public MemorizingTrustManager getMemorizingTrustManager() {
3335 return this.mMemorizingTrustManager;
3336 }
3337
3338 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
3339 this.mMemorizingTrustManager = trustManager;
3340 }
3341
3342 public void updateMemorizingTrustmanager() {
3343 final MemorizingTrustManager tm;
3344 final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
3345 if (dontTrustSystemCAs) {
3346 tm = new MemorizingTrustManager(getApplicationContext(), null);
3347 } else {
3348 tm = new MemorizingTrustManager(getApplicationContext());
3349 }
3350 setMemorizingTrustManager(tm);
3351 }
3352
3353 public LruCache<String, Bitmap> getBitmapCache() {
3354 return this.mBitmapCache;
3355 }
3356
3357 public Collection<String> getKnownHosts() {
3358 final Set<String> hosts = new HashSet<>();
3359 for (final Account account : getAccounts()) {
3360 hosts.add(account.getServer());
3361 for (final Contact contact : account.getRoster().getContacts()) {
3362 if (contact.showInRoster()) {
3363 final String server = contact.getServer();
3364 if (server != null && !hosts.contains(server)) {
3365 hosts.add(server);
3366 }
3367 }
3368 }
3369 }
3370 if (Config.DOMAIN_LOCK != null) {
3371 hosts.add(Config.DOMAIN_LOCK);
3372 }
3373 if (Config.MAGIC_CREATE_DOMAIN != null) {
3374 hosts.add(Config.MAGIC_CREATE_DOMAIN);
3375 }
3376 return hosts;
3377 }
3378
3379 public Collection<String> getKnownConferenceHosts() {
3380 final Set<String> mucServers = new HashSet<>();
3381 for (final Account account : accounts) {
3382 if (account.getXmppConnection() != null) {
3383 mucServers.addAll(account.getXmppConnection().getMucServers());
3384 for (Bookmark bookmark : account.getBookmarks()) {
3385 final Jid jid = bookmark.getJid();
3386 final String s = jid == null ? null : jid.getDomain();
3387 if (s != null) {
3388 mucServers.add(s);
3389 }
3390 }
3391 }
3392 }
3393 return mucServers;
3394 }
3395
3396 public void sendMessagePacket(Account account, MessagePacket packet) {
3397 XmppConnection connection = account.getXmppConnection();
3398 if (connection != null) {
3399 connection.sendMessagePacket(packet);
3400 }
3401 }
3402
3403 public void sendPresencePacket(Account account, PresencePacket packet) {
3404 XmppConnection connection = account.getXmppConnection();
3405 if (connection != null) {
3406 connection.sendPresencePacket(packet);
3407 }
3408 }
3409
3410 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3411 final XmppConnection connection = account.getXmppConnection();
3412 if (connection != null) {
3413 IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3414 connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
3415 }
3416 }
3417
3418 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3419 final XmppConnection connection = account.getXmppConnection();
3420 if (connection != null) {
3421 connection.sendIqPacket(packet, callback);
3422 }
3423 }
3424
3425 public void sendPresence(final Account account) {
3426 sendPresence(account, checkListeners() && broadcastLastActivity());
3427 }
3428
3429 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3430 Presence.Status status;
3431 if (manuallyChangePresence()) {
3432 status = account.getPresenceStatus();
3433 } else {
3434 status = getTargetPresence();
3435 }
3436 PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
3437 String message = account.getPresenceStatusMessage();
3438 if (message != null && !message.isEmpty()) {
3439 packet.addChild(new Element("status").setContent(message));
3440 }
3441 if (mLastActivity > 0 && includeIdleTimestamp) {
3442 long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3443 packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
3444 }
3445 sendPresencePacket(account, packet);
3446 }
3447
3448 private void deactivateGracePeriod() {
3449 for (Account account : getAccounts()) {
3450 account.deactivateGracePeriod();
3451 }
3452 }
3453
3454 public void refreshAllPresences() {
3455 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3456 for (Account account : getAccounts()) {
3457 if (account.isEnabled()) {
3458 sendPresence(account, includeIdleTimestamp);
3459 }
3460 }
3461 }
3462
3463 private void refreshAllGcmTokens() {
3464 for (Account account : getAccounts()) {
3465 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3466 mPushManagementService.registerPushTokenOnServer(account);
3467 }
3468 }
3469 }
3470
3471 private void sendOfflinePresence(final Account account) {
3472 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
3473 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3474 }
3475
3476 public MessageGenerator getMessageGenerator() {
3477 return this.mMessageGenerator;
3478 }
3479
3480 public PresenceGenerator getPresenceGenerator() {
3481 return this.mPresenceGenerator;
3482 }
3483
3484 public IqGenerator getIqGenerator() {
3485 return this.mIqGenerator;
3486 }
3487
3488 public IqParser getIqParser() {
3489 return this.mIqParser;
3490 }
3491
3492 public JingleConnectionManager getJingleConnectionManager() {
3493 return this.mJingleConnectionManager;
3494 }
3495
3496 public MessageArchiveService getMessageArchiveService() {
3497 return this.mMessageArchiveService;
3498 }
3499
3500 public List<Contact> findContacts(Jid jid, String accountJid) {
3501 ArrayList<Contact> contacts = new ArrayList<>();
3502 for (Account account : getAccounts()) {
3503 if ((account.isEnabled() || accountJid != null)
3504 && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
3505 Contact contact = account.getRoster().getContactFromRoster(jid);
3506 if (contact != null) {
3507 contacts.add(contact);
3508 }
3509 }
3510 }
3511 return contacts;
3512 }
3513
3514 public Conversation findFirstMuc(Jid jid) {
3515 for (Conversation conversation : getConversations()) {
3516 if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
3517 return conversation;
3518 }
3519 }
3520 return null;
3521 }
3522
3523 public NotificationService getNotificationService() {
3524 return this.mNotificationService;
3525 }
3526
3527 public HttpConnectionManager getHttpConnectionManager() {
3528 return this.mHttpConnectionManager;
3529 }
3530
3531 public void resendFailedMessages(final Message message) {
3532 final Collection<Message> messages = new ArrayList<>();
3533 Message current = message;
3534 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3535 messages.add(current);
3536 if (current.mergeable(current.next())) {
3537 current = current.next();
3538 } else {
3539 break;
3540 }
3541 }
3542 for (final Message msg : messages) {
3543 msg.setTime(System.currentTimeMillis());
3544 markMessage(msg, Message.STATUS_WAITING);
3545 this.resendMessage(msg, false);
3546 }
3547 message.getConversation().sort();
3548 updateConversationUi();
3549 }
3550
3551 public void clearConversationHistory(final Conversation conversation) {
3552 final long clearDate;
3553 final String reference;
3554 if (conversation.countMessages() > 0) {
3555 Message latestMessage = conversation.getLatestMessage();
3556 clearDate = latestMessage.getTimeSent() + 1000;
3557 reference = latestMessage.getServerMsgId();
3558 } else {
3559 clearDate = System.currentTimeMillis();
3560 reference = null;
3561 }
3562 conversation.clearMessages();
3563 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3564 conversation.setLastClearHistory(clearDate, reference);
3565 Runnable runnable = () -> {
3566 databaseBackend.deleteMessagesInConversation(conversation);
3567 databaseBackend.updateConversation(conversation);
3568 };
3569 mDatabaseWriterExecutor.execute(runnable);
3570 }
3571
3572 public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
3573 if (blockable != null && blockable.getBlockedJid() != null) {
3574 final Jid jid = blockable.getBlockedJid();
3575 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), new OnIqPacketReceived() {
3576
3577 @Override
3578 public void onIqPacketReceived(final Account account, final IqPacket packet) {
3579 if (packet.getType() == IqPacket.TYPE.RESULT) {
3580 account.getBlocklist().add(jid);
3581 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3582 }
3583 }
3584 });
3585 if (removeBlockedConversations(blockable.getAccount(), jid)) {
3586 updateConversationUi();
3587 return true;
3588 } else {
3589 return false;
3590 }
3591 } else {
3592 return false;
3593 }
3594 }
3595
3596 public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
3597 boolean removed = false;
3598 synchronized (this.conversations) {
3599 boolean domainJid = blockedJid.getLocal() == null;
3600 for (Conversation conversation : this.conversations) {
3601 boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
3602 || blockedJid.equals(conversation.getJid().asBareJid());
3603 if (conversation.getAccount() == account
3604 && conversation.getMode() == Conversation.MODE_SINGLE
3605 && jidMatches) {
3606 this.conversations.remove(conversation);
3607 markRead(conversation);
3608 conversation.setStatus(Conversation.STATUS_ARCHIVED);
3609 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
3610 updateConversation(conversation);
3611 removed = true;
3612 }
3613 }
3614 }
3615 return removed;
3616 }
3617
3618 public void sendUnblockRequest(final Blockable blockable) {
3619 if (blockable != null && blockable.getJid() != null) {
3620 final Jid jid = blockable.getBlockedJid();
3621 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3622 @Override
3623 public void onIqPacketReceived(final Account account, final IqPacket packet) {
3624 if (packet.getType() == IqPacket.TYPE.RESULT) {
3625 account.getBlocklist().remove(jid);
3626 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3627 }
3628 }
3629 });
3630 }
3631 }
3632
3633 public void publishDisplayName(Account account) {
3634 String displayName = account.getDisplayName();
3635 if (displayName != null && !displayName.isEmpty()) {
3636 IqPacket publish = mIqGenerator.publishNick(displayName);
3637 sendIqPacket(account, publish, (account1, packet) -> {
3638 if (packet.getType() == IqPacket.TYPE.ERROR) {
3639 Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": could not publish nick");
3640 }
3641 });
3642 }
3643 }
3644
3645 public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
3646 ServiceDiscoveryResult result = discoCache.get(key);
3647 if (result != null) {
3648 return result;
3649 } else {
3650 result = databaseBackend.findDiscoveryResult(key.first, key.second);
3651 if (result != null) {
3652 discoCache.put(key, result);
3653 }
3654 return result;
3655 }
3656 }
3657
3658 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3659 final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
3660 ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3661 if (disco != null) {
3662 presence.setServiceDiscoveryResult(disco);
3663 } else {
3664 if (!account.inProgressDiscoFetches.contains(key)) {
3665 account.inProgressDiscoFetches.add(key);
3666 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3667 request.setTo(jid);
3668 request.query("http://jabber.org/protocol/disco#info");
3669 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
3670 sendIqPacket(account, request, (account1, discoPacket) -> {
3671 if (discoPacket.getType() == IqPacket.TYPE.RESULT) {
3672 ServiceDiscoveryResult disco1 = new ServiceDiscoveryResult(discoPacket);
3673 if (presence.getVer().equals(disco1.getVer())) {
3674 databaseBackend.insertDiscoveryResult(disco1);
3675 injectServiceDiscorveryResult(account1.getRoster(), presence.getHash(), presence.getVer(), disco1);
3676 } else {
3677 Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco1.getVer());
3678 }
3679 }
3680 account1.inProgressDiscoFetches.remove(key);
3681 });
3682 }
3683 }
3684 }
3685
3686 private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3687 for (Contact contact : roster.getContacts()) {
3688 for (Presence presence : contact.getPresences().getPresences().values()) {
3689 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3690 presence.setServiceDiscoveryResult(disco);
3691 }
3692 }
3693 }
3694 }
3695
3696 public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3697 final boolean legacy = account.getXmppConnection().getFeatures().mamLegacy();
3698 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3699 request.addChild("prefs", legacy ? Namespace.MAM_LEGACY : Namespace.MAM);
3700 sendIqPacket(account, request, (account1, packet) -> {
3701 Element prefs = packet.findChild("prefs", legacy ? Namespace.MAM_LEGACY : Namespace.MAM);
3702 if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3703 callback.onPreferencesFetched(prefs);
3704 } else {
3705 callback.onPreferencesFetchFailed();
3706 }
3707 });
3708 }
3709
3710 public PushManagementService getPushManagementService() {
3711 return mPushManagementService;
3712 }
3713
3714 public Account getPendingAccount() {
3715 Account pending = null;
3716 for (Account account : getAccounts()) {
3717 if (!account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY)) {
3718 pending = account;
3719 } else {
3720 return null;
3721 }
3722 }
3723 return pending;
3724 }
3725
3726 public void changeStatus(Account account, PresenceTemplate template, String signature) {
3727 if (!template.getStatusMessage().isEmpty()) {
3728 databaseBackend.insertPresenceTemplate(template);
3729 }
3730 account.setPgpSignature(signature);
3731 account.setPresenceStatus(template.getStatus());
3732 account.setPresenceStatusMessage(template.getStatusMessage());
3733 databaseBackend.updateAccount(account);
3734 sendPresence(account);
3735 }
3736
3737 public List<PresenceTemplate> getPresenceTemplates(Account account) {
3738 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3739 for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3740 if (!templates.contains(template)) {
3741 templates.add(0, template);
3742 }
3743 }
3744 return templates;
3745 }
3746
3747 public void saveConversationAsBookmark(Conversation conversation, String name) {
3748 Account account = conversation.getAccount();
3749 Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
3750 if (!conversation.getJid().isBareJid()) {
3751 bookmark.setNick(conversation.getJid().getResource());
3752 }
3753 if (name != null && !name.trim().isEmpty()) {
3754 bookmark.setBookmarkName(name.trim());
3755 }
3756 bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
3757 account.getBookmarks().add(bookmark);
3758 pushBookmarks(account);
3759 bookmark.setConversation(conversation);
3760 }
3761
3762 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
3763 boolean performedVerification = false;
3764 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
3765 for (XmppUri.Fingerprint fp : fingerprints) {
3766 if (fp.type == XmppUri.FingerprintType.OMEMO) {
3767 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
3768 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3769 if (fingerprintStatus != null) {
3770 if (!fingerprintStatus.isVerified()) {
3771 performedVerification = true;
3772 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
3773 }
3774 } else {
3775 axolotlService.preVerifyFingerprint(contact, fingerprint);
3776 }
3777 }
3778 }
3779 return performedVerification;
3780 }
3781
3782 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
3783 final AxolotlService axolotlService = account.getAxolotlService();
3784 boolean verifiedSomething = false;
3785 for (XmppUri.Fingerprint fp : fingerprints) {
3786 if (fp.type == XmppUri.FingerprintType.OMEMO) {
3787 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
3788 Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
3789 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3790 if (fingerprintStatus != null) {
3791 if (!fingerprintStatus.isVerified()) {
3792 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
3793 verifiedSomething = true;
3794 }
3795 } else {
3796 axolotlService.preVerifyFingerprint(account, fingerprint);
3797 verifiedSomething = true;
3798 }
3799 }
3800 }
3801 return verifiedSomething;
3802 }
3803
3804 public boolean blindTrustBeforeVerification() {
3805 return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
3806 }
3807
3808 public ShortcutService getShortcutService() {
3809 return mShortcutService;
3810 }
3811
3812 public void pushMamPreferences(Account account, Element prefs) {
3813 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3814 set.addChild(prefs);
3815 sendIqPacket(account, set, null);
3816 }
3817
3818 public interface OnMamPreferencesFetched {
3819 void onPreferencesFetched(Element prefs);
3820
3821 void onPreferencesFetchFailed();
3822 }
3823
3824 public interface OnAccountCreated {
3825 void onAccountCreated(Account account);
3826
3827 void informUser(int r);
3828 }
3829
3830 public interface OnMoreMessagesLoaded {
3831 void onMoreMessagesLoaded(int count, Conversation conversation);
3832
3833 void informUser(int r);
3834 }
3835
3836 public interface OnAccountPasswordChanged {
3837 void onPasswordChangeSucceeded();
3838
3839 void onPasswordChangeFailed();
3840 }
3841
3842 public interface OnAffiliationChanged {
3843 void onAffiliationChangedSuccessful(Jid jid);
3844
3845 void onAffiliationChangeFailed(Jid jid, int resId);
3846 }
3847
3848 public interface OnRoleChanged {
3849 void onRoleChangedSuccessful(String nick);
3850
3851 void onRoleChangeFailed(String nick, int resid);
3852 }
3853
3854 public interface OnConversationUpdate {
3855 void onConversationUpdate();
3856 }
3857
3858 public interface OnAccountUpdate {
3859 void onAccountUpdate();
3860 }
3861
3862 public interface OnCaptchaRequested {
3863 void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
3864 }
3865
3866 public interface OnRosterUpdate {
3867 void onRosterUpdate();
3868 }
3869
3870 public interface OnMucRosterUpdate {
3871 void onMucRosterUpdate();
3872 }
3873
3874 public interface OnConferenceConfigurationFetched {
3875 void onConferenceConfigurationFetched(Conversation conversation);
3876
3877 void onFetchFailed(Conversation conversation, Element error);
3878 }
3879
3880 public interface OnConferenceJoined {
3881 void onConferenceJoined(Conversation conversation);
3882 }
3883
3884 public interface OnConfigurationPushed {
3885 void onPushSucceeded();
3886
3887 void onPushFailed();
3888 }
3889
3890 public interface OnShowErrorToast {
3891 void onShowErrorToast(int resId);
3892 }
3893
3894 public class XmppConnectionBinder extends Binder {
3895 public XmppConnectionService getService() {
3896 return XmppConnectionService.this;
3897 }
3898 }
3899}