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 return size == 0 || size == 1 && this.conversations.get(0) == ignore;
1612 }
1613 }
1614
1615 public boolean isConversationStillOpen(final Conversation conversation) {
1616 synchronized (this.conversations) {
1617 for (Conversation current : this.conversations) {
1618 if (current == conversation) {
1619 return true;
1620 }
1621 }
1622 }
1623 return false;
1624 }
1625
1626 public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
1627 return this.findOrCreateConversation(account, jid, muc, false, async);
1628 }
1629
1630 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
1631 return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
1632 }
1633
1634 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
1635 synchronized (this.conversations) {
1636 Conversation conversation = find(account, jid);
1637 if (conversation != null) {
1638 return conversation;
1639 }
1640 conversation = databaseBackend.findConversation(account, jid);
1641 final boolean loadMessagesFromDb;
1642 if (conversation != null) {
1643 conversation.setStatus(Conversation.STATUS_AVAILABLE);
1644 conversation.setAccount(account);
1645 if (muc) {
1646 conversation.setMode(Conversation.MODE_MULTI);
1647 conversation.setContactJid(jid);
1648 } else {
1649 conversation.setMode(Conversation.MODE_SINGLE);
1650 conversation.setContactJid(jid.asBareJid());
1651 }
1652 databaseBackend.updateConversation(conversation);
1653 loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
1654 } else {
1655 String conversationName;
1656 Contact contact = account.getRoster().getContact(jid);
1657 if (contact != null) {
1658 conversationName = contact.getDisplayName();
1659 } else {
1660 conversationName = jid.getLocal();
1661 }
1662 if (muc) {
1663 conversation = new Conversation(conversationName, account, jid,
1664 Conversation.MODE_MULTI);
1665 } else {
1666 conversation = new Conversation(conversationName, account, jid.asBareJid(),
1667 Conversation.MODE_SINGLE);
1668 }
1669 this.databaseBackend.createConversation(conversation);
1670 loadMessagesFromDb = false;
1671 }
1672 final Conversation c = conversation;
1673 final Runnable runnable = () -> {
1674 if (loadMessagesFromDb) {
1675 c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
1676 updateConversationUi();
1677 c.messagesLoaded.set(true);
1678 }
1679 if (account.getXmppConnection() != null
1680 && !c.getContact().isBlocked()
1681 && account.getXmppConnection().getFeatures().mam()
1682 && !muc) {
1683 if (query == null) {
1684 mMessageArchiveService.query(c);
1685 } else {
1686 if (query.getConversation() == null) {
1687 mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
1688 }
1689 }
1690 }
1691 checkDeletedFiles(c);
1692 if (joinAfterCreate) {
1693 joinMuc(c);
1694 }
1695 };
1696 if (async) {
1697 mDatabaseReaderExecutor.execute(runnable);
1698 } else {
1699 runnable.run();
1700 }
1701 this.conversations.add(conversation);
1702 updateConversationUi();
1703 return conversation;
1704 }
1705 }
1706
1707 public void archiveConversation(Conversation conversation) {
1708 getNotificationService().clear(conversation);
1709 conversation.setStatus(Conversation.STATUS_ARCHIVED);
1710 conversation.setNextMessage(null);
1711 synchronized (this.conversations) {
1712 getMessageArchiveService().kill(conversation);
1713 if (conversation.getMode() == Conversation.MODE_MULTI) {
1714 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1715 Bookmark bookmark = conversation.getBookmark();
1716 if (bookmark != null && bookmark.autojoin() && respectAutojoin()) {
1717 bookmark.setAutojoin(false);
1718 pushBookmarks(bookmark.getAccount());
1719 }
1720 }
1721 leaveMuc(conversation);
1722 } else {
1723 if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1724 Log.d(Config.LOGTAG, "Canceling presence request from " + conversation.getJid().toString());
1725 sendPresencePacket(
1726 conversation.getAccount(),
1727 mPresenceGenerator.stopPresenceUpdatesTo(conversation.getContact())
1728 );
1729 }
1730 }
1731 updateConversation(conversation);
1732 this.conversations.remove(conversation);
1733 updateConversationUi();
1734 }
1735 }
1736
1737 public void createAccount(final Account account) {
1738 account.initAccountServices(this);
1739 databaseBackend.createAccount(account);
1740 this.accounts.add(account);
1741 this.reconnectAccountInBackground(account);
1742 updateAccountUi();
1743 syncEnabledAccountSetting();
1744 toggleForegroundService();
1745 }
1746
1747 private void syncEnabledAccountSetting() {
1748 getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts()).apply();
1749 }
1750
1751 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1752 new Thread(() -> {
1753 try {
1754 final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
1755 final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
1756 if (cert == null) {
1757 callback.informUser(R.string.unable_to_parse_certificate);
1758 return;
1759 }
1760 Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
1761 if (info == null) {
1762 callback.informUser(R.string.certificate_does_not_contain_jid);
1763 return;
1764 }
1765 if (findAccountByJid(info.first) == null) {
1766 Account account = new Account(info.first, "");
1767 account.setPrivateKeyAlias(alias);
1768 account.setOption(Account.OPTION_DISABLED, true);
1769 account.setDisplayName(info.second);
1770 createAccount(account);
1771 callback.onAccountCreated(account);
1772 if (Config.X509_VERIFICATION) {
1773 try {
1774 getMemorizingTrustManager().getNonInteractive(account.getJid().getDomain()).checkClientTrusted(chain, "RSA");
1775 } catch (CertificateException e) {
1776 callback.informUser(R.string.certificate_chain_is_not_trusted);
1777 }
1778 }
1779 } else {
1780 callback.informUser(R.string.account_already_exists);
1781 }
1782 } catch (Exception e) {
1783 e.printStackTrace();
1784 callback.informUser(R.string.unable_to_parse_certificate);
1785 }
1786 }).start();
1787
1788 }
1789
1790 public void updateKeyInAccount(final Account account, final String alias) {
1791 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
1792 try {
1793 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1794 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
1795 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1796 if (info == null) {
1797 showErrorToastInUi(R.string.certificate_does_not_contain_jid);
1798 return;
1799 }
1800 if (account.getJid().asBareJid().equals(info.first)) {
1801 account.setPrivateKeyAlias(alias);
1802 account.setDisplayName(info.second);
1803 databaseBackend.updateAccount(account);
1804 if (Config.X509_VERIFICATION) {
1805 try {
1806 getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1807 } catch (CertificateException e) {
1808 showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1809 }
1810 account.getAxolotlService().regenerateKeys(true);
1811 }
1812 } else {
1813 showErrorToastInUi(R.string.jid_does_not_match_certificate);
1814 }
1815 } catch (Exception e) {
1816 e.printStackTrace();
1817 }
1818 }
1819
1820 public boolean updateAccount(final Account account) {
1821 if (databaseBackend.updateAccount(account)) {
1822 account.setShowErrorNotification(true);
1823 this.statusListener.onStatusChanged(account);
1824 databaseBackend.updateAccount(account);
1825 reconnectAccountInBackground(account);
1826 updateAccountUi();
1827 getNotificationService().updateErrorNotification();
1828 toggleForegroundService();
1829 syncEnabledAccountSetting();
1830 return true;
1831 } else {
1832 return false;
1833 }
1834 }
1835
1836 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1837 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1838 sendIqPacket(account, iq, (a, packet) -> {
1839 if (packet.getType() == IqPacket.TYPE.RESULT) {
1840 a.setPassword(newPassword);
1841 a.setOption(Account.OPTION_MAGIC_CREATE, false);
1842 databaseBackend.updateAccount(a);
1843 callback.onPasswordChangeSucceeded();
1844 } else {
1845 callback.onPasswordChangeFailed();
1846 }
1847 });
1848 }
1849
1850 public void deleteAccount(final Account account) {
1851 synchronized (this.conversations) {
1852 for (final Conversation conversation : conversations) {
1853 if (conversation.getAccount() == account) {
1854 if (conversation.getMode() == Conversation.MODE_MULTI) {
1855 leaveMuc(conversation);
1856 }
1857 conversations.remove(conversation);
1858 }
1859 }
1860 if (account.getXmppConnection() != null) {
1861 new Thread(() -> disconnect(account, true)).start();
1862 }
1863 final Runnable runnable = () -> {
1864 if (!databaseBackend.deleteAccount(account)) {
1865 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
1866 }
1867 };
1868 mDatabaseWriterExecutor.execute(runnable);
1869 this.accounts.remove(account);
1870 this.mRosterSyncTaskManager.clear(account);
1871 updateAccountUi();
1872 getNotificationService().updateErrorNotification();
1873 syncEnabledAccountSetting();
1874 }
1875 }
1876
1877 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1878 synchronized (this) {
1879 this.mLastActivity = System.currentTimeMillis();
1880 if (checkListeners()) {
1881 switchToForeground();
1882 }
1883 this.mOnConversationUpdate = listener;
1884 this.mNotificationService.setIsInForeground(true);
1885 if (this.convChangedListenerCount < 2) {
1886 this.convChangedListenerCount++;
1887 }
1888 }
1889 }
1890
1891 public void removeOnConversationListChangedListener() {
1892 synchronized (this) {
1893 this.convChangedListenerCount--;
1894 if (this.convChangedListenerCount <= 0) {
1895 this.convChangedListenerCount = 0;
1896 this.mOnConversationUpdate = null;
1897 this.mNotificationService.setIsInForeground(false);
1898 if (checkListeners()) {
1899 switchToBackground();
1900 }
1901 }
1902 }
1903 }
1904
1905 public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1906 synchronized (this) {
1907 if (checkListeners()) {
1908 switchToForeground();
1909 }
1910 this.mOnShowErrorToast = onShowErrorToast;
1911 if (this.showErrorToastListenerCount < 2) {
1912 this.showErrorToastListenerCount++;
1913 }
1914 }
1915 this.mOnShowErrorToast = onShowErrorToast;
1916 }
1917
1918 public void removeOnShowErrorToastListener() {
1919 synchronized (this) {
1920 this.showErrorToastListenerCount--;
1921 if (this.showErrorToastListenerCount <= 0) {
1922 this.showErrorToastListenerCount = 0;
1923 this.mOnShowErrorToast = null;
1924 if (checkListeners()) {
1925 switchToBackground();
1926 }
1927 }
1928 }
1929 }
1930
1931 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1932 synchronized (this) {
1933 if (checkListeners()) {
1934 switchToForeground();
1935 }
1936 this.mOnAccountUpdate = listener;
1937 if (this.accountChangedListenerCount < 2) {
1938 this.accountChangedListenerCount++;
1939 }
1940 }
1941 }
1942
1943 public void removeOnAccountListChangedListener() {
1944 synchronized (this) {
1945 this.accountChangedListenerCount--;
1946 if (this.accountChangedListenerCount <= 0) {
1947 this.mOnAccountUpdate = null;
1948 this.accountChangedListenerCount = 0;
1949 if (checkListeners()) {
1950 switchToBackground();
1951 }
1952 }
1953 }
1954 }
1955
1956 public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
1957 synchronized (this) {
1958 if (checkListeners()) {
1959 switchToForeground();
1960 }
1961 this.mOnCaptchaRequested = listener;
1962 if (this.captchaRequestedListenerCount < 2) {
1963 this.captchaRequestedListenerCount++;
1964 }
1965 }
1966 }
1967
1968 public void removeOnCaptchaRequestedListener() {
1969 synchronized (this) {
1970 this.captchaRequestedListenerCount--;
1971 if (this.captchaRequestedListenerCount <= 0) {
1972 this.mOnCaptchaRequested = null;
1973 this.captchaRequestedListenerCount = 0;
1974 if (checkListeners()) {
1975 switchToBackground();
1976 }
1977 }
1978 }
1979 }
1980
1981 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1982 synchronized (this) {
1983 if (checkListeners()) {
1984 switchToForeground();
1985 }
1986 this.mOnRosterUpdate = listener;
1987 if (this.rosterChangedListenerCount < 2) {
1988 this.rosterChangedListenerCount++;
1989 }
1990 }
1991 }
1992
1993 public void removeOnRosterUpdateListener() {
1994 synchronized (this) {
1995 this.rosterChangedListenerCount--;
1996 if (this.rosterChangedListenerCount <= 0) {
1997 this.rosterChangedListenerCount = 0;
1998 this.mOnRosterUpdate = null;
1999 if (checkListeners()) {
2000 switchToBackground();
2001 }
2002 }
2003 }
2004 }
2005
2006 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2007 synchronized (this) {
2008 if (checkListeners()) {
2009 switchToForeground();
2010 }
2011 this.mOnUpdateBlocklist = listener;
2012 if (this.updateBlocklistListenerCount < 2) {
2013 this.updateBlocklistListenerCount++;
2014 }
2015 }
2016 }
2017
2018 public void removeOnUpdateBlocklistListener() {
2019 synchronized (this) {
2020 this.updateBlocklistListenerCount--;
2021 if (this.updateBlocklistListenerCount <= 0) {
2022 this.updateBlocklistListenerCount = 0;
2023 this.mOnUpdateBlocklist = null;
2024 if (checkListeners()) {
2025 switchToBackground();
2026 }
2027 }
2028 }
2029 }
2030
2031 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2032 synchronized (this) {
2033 if (checkListeners()) {
2034 switchToForeground();
2035 }
2036 this.mOnKeyStatusUpdated = listener;
2037 if (this.keyStatusUpdatedListenerCount < 2) {
2038 this.keyStatusUpdatedListenerCount++;
2039 }
2040 }
2041 }
2042
2043 public void removeOnNewKeysAvailableListener() {
2044 synchronized (this) {
2045 this.keyStatusUpdatedListenerCount--;
2046 if (this.keyStatusUpdatedListenerCount <= 0) {
2047 this.keyStatusUpdatedListenerCount = 0;
2048 this.mOnKeyStatusUpdated = null;
2049 if (checkListeners()) {
2050 switchToBackground();
2051 }
2052 }
2053 }
2054 }
2055
2056 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2057 synchronized (this) {
2058 if (checkListeners()) {
2059 switchToForeground();
2060 }
2061 this.mOnMucRosterUpdate = listener;
2062 if (this.mucRosterChangedListenerCount < 2) {
2063 this.mucRosterChangedListenerCount++;
2064 }
2065 }
2066 }
2067
2068 public void removeOnMucRosterUpdateListener() {
2069 synchronized (this) {
2070 this.mucRosterChangedListenerCount--;
2071 if (this.mucRosterChangedListenerCount <= 0) {
2072 this.mucRosterChangedListenerCount = 0;
2073 this.mOnMucRosterUpdate = null;
2074 if (checkListeners()) {
2075 switchToBackground();
2076 }
2077 }
2078 }
2079 }
2080
2081 public boolean checkListeners() {
2082 return (this.mOnAccountUpdate == null
2083 && this.mOnConversationUpdate == null
2084 && this.mOnRosterUpdate == null
2085 && this.mOnCaptchaRequested == null
2086 && this.mOnUpdateBlocklist == null
2087 && this.mOnShowErrorToast == null
2088 && this.mOnKeyStatusUpdated == null);
2089 }
2090
2091 private void switchToForeground() {
2092 final boolean broadcastLastActivity = broadcastLastActivity();
2093 for (Conversation conversation : getConversations()) {
2094 if (conversation.getMode() == Conversation.MODE_MULTI) {
2095 conversation.getMucOptions().resetChatState();
2096 } else {
2097 conversation.setIncomingChatState(Config.DEFAULT_CHATSTATE);
2098 }
2099 }
2100 for (Account account : getAccounts()) {
2101 if (account.getStatus() == Account.State.ONLINE) {
2102 account.deactivateGracePeriod();
2103 final XmppConnection connection = account.getXmppConnection();
2104 if (connection != null) {
2105 if (connection.getFeatures().csi()) {
2106 connection.sendActive();
2107 }
2108 if (broadcastLastActivity) {
2109 sendPresence(account, false); //send new presence but don't include idle because we are not
2110 }
2111 }
2112 }
2113 }
2114 Log.d(Config.LOGTAG, "app switched into foreground");
2115 }
2116
2117 private void switchToBackground() {
2118 final boolean broadcastLastActivity = broadcastLastActivity();
2119 for (Account account : getAccounts()) {
2120 if (account.getStatus() == Account.State.ONLINE) {
2121 XmppConnection connection = account.getXmppConnection();
2122 if (connection != null) {
2123 if (broadcastLastActivity) {
2124 sendPresence(account, true);
2125 }
2126 if (connection.getFeatures().csi()) {
2127 connection.sendInactive();
2128 }
2129 }
2130 }
2131 }
2132 this.mNotificationService.setIsInForeground(false);
2133 Log.d(Config.LOGTAG, "app switched into background");
2134 }
2135
2136 private void connectMultiModeConversations(Account account) {
2137 List<Conversation> conversations = getConversations();
2138 for (Conversation conversation : conversations) {
2139 if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2140 joinMuc(conversation);
2141 }
2142 }
2143 }
2144
2145 public void joinMuc(Conversation conversation) {
2146 joinMuc(conversation, null, false);
2147 }
2148
2149 public void joinMuc(Conversation conversation, boolean followedInvite) {
2150 joinMuc(conversation, null, followedInvite);
2151 }
2152
2153 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2154 joinMuc(conversation, onConferenceJoined, false);
2155 }
2156
2157 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2158 Account account = conversation.getAccount();
2159 account.pendingConferenceJoins.remove(conversation);
2160 account.pendingConferenceLeaves.remove(conversation);
2161 if (account.getStatus() == Account.State.ONLINE) {
2162 sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
2163 conversation.resetMucOptions();
2164 if (onConferenceJoined != null) {
2165 conversation.getMucOptions().flagNoAutoPushConfiguration();
2166 }
2167 conversation.setHasMessagesLeftOnServer(false);
2168 fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2169
2170 private void join(Conversation conversation) {
2171 Account account = conversation.getAccount();
2172 final MucOptions mucOptions = conversation.getMucOptions();
2173 final Jid joinJid = mucOptions.getSelf().getFullJid();
2174 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
2175 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
2176 packet.setTo(joinJid);
2177 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2178 if (conversation.getMucOptions().getPassword() != null) {
2179 x.addChild("password").setContent(mucOptions.getPassword());
2180 }
2181
2182 if (mucOptions.mamSupport()) {
2183 // Use MAM instead of the limited muc history to get history
2184 x.addChild("history").setAttribute("maxchars", "0");
2185 } else {
2186 // Fallback to muc history
2187 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
2188 }
2189 sendPresencePacket(account, packet);
2190 if (onConferenceJoined != null) {
2191 onConferenceJoined.onConferenceJoined(conversation);
2192 }
2193 if (!joinJid.equals(conversation.getJid())) {
2194 conversation.setContactJid(joinJid);
2195 databaseBackend.updateConversation(conversation);
2196 }
2197
2198 if (mucOptions.mamSupport()) {
2199 getMessageArchiveService().catchupMUC(conversation);
2200 }
2201 if (mucOptions.isPrivateAndNonAnonymous()) {
2202 fetchConferenceMembers(conversation);
2203 if (followedInvite && conversation.getBookmark() == null) {
2204 saveConversationAsBookmark(conversation, null);
2205 }
2206 }
2207 sendUnsentMessages(conversation);
2208 }
2209
2210 @Override
2211 public void onConferenceConfigurationFetched(Conversation conversation) {
2212 join(conversation);
2213 }
2214
2215 @Override
2216 public void onFetchFailed(final Conversation conversation, Element error) {
2217 if (error != null && "remote-server-not-found".equals(error.getName())) {
2218 conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2219 updateConversationUi();
2220 } else {
2221 join(conversation);
2222 fetchConferenceConfiguration(conversation);
2223 }
2224 }
2225 });
2226 updateConversationUi();
2227 } else {
2228 account.pendingConferenceJoins.add(conversation);
2229 conversation.resetMucOptions();
2230 conversation.setHasMessagesLeftOnServer(false);
2231 updateConversationUi();
2232 }
2233 }
2234
2235 private void fetchConferenceMembers(final Conversation conversation) {
2236 final Account account = conversation.getAccount();
2237 final AxolotlService axolotlService = account.getAxolotlService();
2238 final String[] affiliations = {"member", "admin", "owner"};
2239 OnIqPacketReceived callback = new OnIqPacketReceived() {
2240
2241 private int i = 0;
2242 private boolean success = true;
2243
2244 @Override
2245 public void onIqPacketReceived(Account account, IqPacket packet) {
2246
2247 Element query = packet.query("http://jabber.org/protocol/muc#admin");
2248 if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2249 for (Element child : query.getChildren()) {
2250 if ("item".equals(child.getName())) {
2251 MucOptions.User user = AbstractParser.parseItem(conversation, child);
2252 if (!user.realJidMatchesAccount()) {
2253 boolean isNew = conversation.getMucOptions().updateUser(user);
2254 Contact contact = user.getContact();
2255 if (isNew
2256 && user.getRealJid() != null
2257 && (contact == null || !contact.mutualPresenceSubscription())
2258 && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
2259 axolotlService.fetchDeviceIds(user.getRealJid());
2260 }
2261 }
2262 }
2263 }
2264 } else {
2265 success = false;
2266 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
2267 }
2268 ++i;
2269 if (i >= affiliations.length) {
2270 List<Jid> members = conversation.getMucOptions().getMembers();
2271 if (success) {
2272 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
2273 boolean changed = false;
2274 for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
2275 Jid jid = iterator.next();
2276 if (!members.contains(jid)) {
2277 iterator.remove();
2278 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
2279 changed = true;
2280 }
2281 }
2282 if (changed) {
2283 conversation.setAcceptedCryptoTargets(cryptoTargets);
2284 updateConversation(conversation);
2285 }
2286 }
2287 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": retrieved members for " + conversation.getJid().asBareJid() + ": " + conversation.getMucOptions().getMembers());
2288 getAvatarService().clear(conversation);
2289 updateMucRosterUi();
2290 updateConversationUi();
2291 }
2292 }
2293 };
2294 for (String affiliation : affiliations) {
2295 sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2296 }
2297 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
2298 }
2299
2300 public void providePasswordForMuc(Conversation conversation, String password) {
2301 if (conversation.getMode() == Conversation.MODE_MULTI) {
2302 conversation.getMucOptions().setPassword(password);
2303 if (conversation.getBookmark() != null) {
2304 if (respectAutojoin()) {
2305 conversation.getBookmark().setAutojoin(true);
2306 }
2307 pushBookmarks(conversation.getAccount());
2308 }
2309 updateConversation(conversation);
2310 joinMuc(conversation);
2311 }
2312 }
2313
2314 private boolean hasEnabledAccounts() {
2315 for (Account account : this.accounts) {
2316 if (account.isEnabled()) {
2317 return true;
2318 }
2319 }
2320 return false;
2321 }
2322
2323 public void persistSelfNick(MucOptions.User self) {
2324 final Conversation conversation = self.getConversation();
2325 Jid full = self.getFullJid();
2326 if (!full.equals(conversation.getJid())) {
2327 Log.d(Config.LOGTAG, "nick changed. updating");
2328 conversation.setContactJid(full);
2329 databaseBackend.updateConversation(conversation);
2330 }
2331
2332 Bookmark bookmark = conversation.getBookmark();
2333 if (bookmark != null && !full.getResource().equals(bookmark.getNick())) {
2334 bookmark.setNick(full.getResource());
2335 pushBookmarks(bookmark.getAccount());
2336 }
2337 }
2338
2339 public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2340 final MucOptions options = conversation.getMucOptions();
2341 final Jid joinJid = options.createJoinJid(nick);
2342 if (joinJid == null) {
2343 return false;
2344 }
2345 if (options.online()) {
2346 Account account = conversation.getAccount();
2347 options.setOnRenameListener(new OnRenameListener() {
2348
2349 @Override
2350 public void onSuccess() {
2351 callback.success(conversation);
2352 }
2353
2354 @Override
2355 public void onFailure() {
2356 callback.error(R.string.nick_in_use, conversation);
2357 }
2358 });
2359
2360 PresencePacket packet = new PresencePacket();
2361 packet.setTo(joinJid);
2362 packet.setFrom(conversation.getAccount().getJid());
2363
2364 String sig = account.getPgpSignature();
2365 if (sig != null) {
2366 packet.addChild("status").setContent("online");
2367 packet.addChild("x", "jabber:x:signed").setContent(sig);
2368 }
2369 sendPresencePacket(account, packet);
2370 } else {
2371 conversation.setContactJid(joinJid);
2372 databaseBackend.updateConversation(conversation);
2373 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2374 Bookmark bookmark = conversation.getBookmark();
2375 if (bookmark != null) {
2376 bookmark.setNick(nick);
2377 pushBookmarks(bookmark.getAccount());
2378 }
2379 joinMuc(conversation);
2380 }
2381 }
2382 return true;
2383 }
2384
2385 public void leaveMuc(Conversation conversation) {
2386 leaveMuc(conversation, false);
2387 }
2388
2389 private void leaveMuc(Conversation conversation, boolean now) {
2390 Account account = conversation.getAccount();
2391 account.pendingConferenceJoins.remove(conversation);
2392 account.pendingConferenceLeaves.remove(conversation);
2393 if (account.getStatus() == Account.State.ONLINE || now) {
2394 sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
2395 conversation.getMucOptions().setOffline();
2396 Bookmark bookmark = conversation.getBookmark();
2397 if (bookmark != null) {
2398 bookmark.setConversation(null);
2399 }
2400 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
2401 } else {
2402 account.pendingConferenceLeaves.add(conversation);
2403 }
2404 }
2405
2406 public String findConferenceServer(final Account account) {
2407 String server;
2408 if (account.getXmppConnection() != null) {
2409 server = account.getXmppConnection().getMucServer();
2410 if (server != null) {
2411 return server;
2412 }
2413 }
2414 for (Account other : getAccounts()) {
2415 if (other != account && other.getXmppConnection() != null) {
2416 server = other.getXmppConnection().getMucServer();
2417 if (server != null) {
2418 return server;
2419 }
2420 }
2421 }
2422 return null;
2423 }
2424
2425 public boolean createAdhocConference(final Account account,
2426 final String subject,
2427 final Iterable<Jid> jids,
2428 final UiCallback<Conversation> callback) {
2429 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2430 if (account.getStatus() == Account.State.ONLINE) {
2431 try {
2432 String server = findConferenceServer(account);
2433 if (server == null) {
2434 if (callback != null) {
2435 callback.error(R.string.no_conference_server_found, null);
2436 }
2437 return false;
2438 }
2439 final Jid jid = Jid.of(new BigInteger(64, getRNG()).toString(Character.MAX_RADIX), server, null);
2440 final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
2441 joinMuc(conversation, new OnConferenceJoined() {
2442 @Override
2443 public void onConferenceJoined(final Conversation conversation) {
2444 pushConferenceConfiguration(conversation, IqGenerator.defaultRoomConfiguration(), new OnConfigurationPushed() {
2445 @Override
2446 public void onPushSucceeded() {
2447 if (subject != null && !subject.trim().isEmpty()) {
2448 pushSubjectToConference(conversation, subject.trim());
2449 }
2450 for (Jid invite : jids) {
2451 invite(conversation, invite);
2452 }
2453 if (account.countPresences() > 1) {
2454 directInvite(conversation, account.getJid().asBareJid());
2455 }
2456 saveConversationAsBookmark(conversation, subject);
2457 if (callback != null) {
2458 callback.success(conversation);
2459 }
2460 }
2461
2462 @Override
2463 public void onPushFailed() {
2464 archiveConversation(conversation);
2465 if (callback != null) {
2466 callback.error(R.string.conference_creation_failed, conversation);
2467 }
2468 }
2469 });
2470 }
2471 });
2472 return true;
2473 } catch (IllegalArgumentException e) {
2474 if (callback != null) {
2475 callback.error(R.string.conference_creation_failed, null);
2476 }
2477 return false;
2478 }
2479 } else {
2480 if (callback != null) {
2481 callback.error(R.string.not_connected_try_again, null);
2482 }
2483 return false;
2484 }
2485 }
2486
2487 public void fetchConferenceConfiguration(final Conversation conversation) {
2488 fetchConferenceConfiguration(conversation, null);
2489 }
2490
2491 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2492 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2493 request.setTo(conversation.getJid().asBareJid());
2494 request.query("http://jabber.org/protocol/disco#info");
2495 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2496 @Override
2497 public void onIqPacketReceived(Account account, IqPacket packet) {
2498 Element query = packet.findChild("query", "http://jabber.org/protocol/disco#info");
2499 if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2500 ArrayList<String> features = new ArrayList<>();
2501 for (Element child : query.getChildren()) {
2502 if (child != null && child.getName().equals("feature")) {
2503 String var = child.getAttribute("var");
2504 if (var != null) {
2505 features.add(var);
2506 }
2507 }
2508 }
2509 Element form = query.findChild("x", Namespace.DATA);
2510 Data data = form == null ? null : Data.parse(form);
2511 if (conversation.getMucOptions().updateConfiguration(features, data)) {
2512 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
2513 updateConversation(conversation);
2514 }
2515 if (callback != null) {
2516 callback.onConferenceConfigurationFetched(conversation);
2517 }
2518 updateConversationUi();
2519 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
2520 if (callback != null) {
2521 callback.onFetchFailed(conversation, packet.getError());
2522 }
2523 }
2524 }
2525 });
2526 }
2527
2528 public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
2529 pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
2530 }
2531
2532 public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
2533 sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
2534 @Override
2535 public void onIqPacketReceived(Account account, IqPacket packet) {
2536 if (packet.getType() == IqPacket.TYPE.RESULT) {
2537 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
2538 Element configuration = pubsub == null ? null : pubsub.findChild("configure");
2539 Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
2540 if (x != null) {
2541 Data data = Data.parse(x);
2542 data.submit(options);
2543 sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
2544 @Override
2545 public void onIqPacketReceived(Account account, IqPacket packet) {
2546 if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
2547 callback.onPushSucceeded();
2548 } else {
2549 Log.d(Config.LOGTAG, packet.toString());
2550 }
2551 }
2552 });
2553 } else if (callback != null) {
2554 callback.onPushFailed();
2555 }
2556 } else if (callback != null) {
2557 callback.onPushFailed();
2558 }
2559 }
2560 });
2561 }
2562
2563 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
2564 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2565 request.setTo(conversation.getJid().asBareJid());
2566 request.query("http://jabber.org/protocol/muc#owner");
2567 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2568 @Override
2569 public void onIqPacketReceived(Account account, IqPacket packet) {
2570 if (packet.getType() == IqPacket.TYPE.RESULT) {
2571 Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
2572 data.submit(options);
2573 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2574 set.setTo(conversation.getJid().asBareJid());
2575 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2576 sendIqPacket(account, set, new OnIqPacketReceived() {
2577 @Override
2578 public void onIqPacketReceived(Account account, IqPacket packet) {
2579 if (callback != null) {
2580 if (packet.getType() == IqPacket.TYPE.RESULT) {
2581 callback.onPushSucceeded();
2582 } else {
2583 callback.onPushFailed();
2584 }
2585 }
2586 }
2587 });
2588 } else {
2589 if (callback != null) {
2590 callback.onPushFailed();
2591 }
2592 }
2593 }
2594 });
2595 }
2596
2597 public void pushSubjectToConference(final Conversation conference, final String subject) {
2598 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2599 this.sendMessagePacket(conference.getAccount(), packet);
2600 final MucOptions mucOptions = conference.getMucOptions();
2601 final MucOptions.User self = mucOptions.getSelf();
2602 if (self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2603 Bundle options = new Bundle();
2604 options.putString("muc#roomconfig_persistentroom", "1");
2605 options.putString("muc#roomconfig_roomname", subject);
2606 this.pushConferenceConfiguration(conference, options, null);
2607 }
2608 }
2609
2610 public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2611 final Jid jid = user.asBareJid();
2612 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2613 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2614 @Override
2615 public void onIqPacketReceived(Account account, IqPacket packet) {
2616 if (packet.getType() == IqPacket.TYPE.RESULT) {
2617 conference.getMucOptions().changeAffiliation(jid, affiliation);
2618 getAvatarService().clear(conference);
2619 callback.onAffiliationChangedSuccessful(jid);
2620 } else {
2621 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2622 }
2623 }
2624 });
2625 }
2626
2627 public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2628 List<Jid> jids = new ArrayList<>();
2629 for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2630 if (user.getAffiliation() == before && user.getRealJid() != null) {
2631 jids.add(user.getRealJid());
2632 }
2633 }
2634 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2635 sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2636 }
2637
2638 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2639 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2640 Log.d(Config.LOGTAG, request.toString());
2641 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2642 @Override
2643 public void onIqPacketReceived(Account account, IqPacket packet) {
2644 Log.d(Config.LOGTAG, packet.toString());
2645 if (packet.getType() == IqPacket.TYPE.RESULT) {
2646 callback.onRoleChangedSuccessful(nick);
2647 } else {
2648 callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2649 }
2650 }
2651 });
2652 }
2653
2654 private void disconnect(Account account, boolean force) {
2655 if ((account.getStatus() == Account.State.ONLINE)
2656 || (account.getStatus() == Account.State.DISABLED)) {
2657 final XmppConnection connection = account.getXmppConnection();
2658 if (!force) {
2659 List<Conversation> conversations = getConversations();
2660 for (Conversation conversation : conversations) {
2661 if (conversation.getAccount() == account) {
2662 if (conversation.getMode() == Conversation.MODE_MULTI) {
2663 leaveMuc(conversation, true);
2664 }
2665 }
2666 }
2667 sendOfflinePresence(account);
2668 }
2669 connection.disconnect(force);
2670 }
2671 }
2672
2673 @Override
2674 public IBinder onBind(Intent intent) {
2675 return mBinder;
2676 }
2677
2678 public void updateMessage(Message message) {
2679 databaseBackend.updateMessage(message);
2680 updateConversationUi();
2681 }
2682
2683 public void updateMessage(Message message, String uuid) {
2684 databaseBackend.updateMessage(message, uuid);
2685 updateConversationUi();
2686 }
2687
2688 protected void syncDirtyContacts(Account account) {
2689 for (Contact contact : account.getRoster().getContacts()) {
2690 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2691 pushContactToServer(contact);
2692 }
2693 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2694 deleteContactOnServer(contact);
2695 }
2696 }
2697 }
2698
2699 public void createContact(Contact contact, boolean autoGrant) {
2700 if (autoGrant) {
2701 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2702 contact.setOption(Contact.Options.ASKING);
2703 }
2704 pushContactToServer(contact);
2705 }
2706
2707 public void pushContactToServer(final Contact contact) {
2708 contact.resetOption(Contact.Options.DIRTY_DELETE);
2709 contact.setOption(Contact.Options.DIRTY_PUSH);
2710 final Account account = contact.getAccount();
2711 if (account.getStatus() == Account.State.ONLINE) {
2712 final boolean ask = contact.getOption(Contact.Options.ASKING);
2713 final boolean sendUpdates = contact
2714 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2715 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2716 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2717 iq.query(Namespace.ROSTER).addChild(contact.asElement());
2718 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2719 if (sendUpdates) {
2720 sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
2721 }
2722 if (ask) {
2723 sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2724 }
2725 } else {
2726 syncRoster(contact.getAccount());
2727 }
2728 }
2729
2730 public void publishAvatar(final Account account, final Uri image, final UiCallback<Avatar> callback) {
2731 new Thread(() -> {
2732 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2733 final int size = Config.AVATAR_SIZE;
2734 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2735 if (avatar != null) {
2736 if (!getFileBackend().save(avatar)) {
2737 callback.error(R.string.error_saving_avatar, avatar);
2738 return;
2739 }
2740 publishAvatar(account, avatar, callback);
2741 } else {
2742 callback.error(R.string.error_publish_avatar_converting, null);
2743 }
2744 }).start();
2745
2746 }
2747
2748 public void publishAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2749 IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2750 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2751
2752 @Override
2753 public void onIqPacketReceived(Account account, IqPacket result) {
2754 if (result.getType() == IqPacket.TYPE.RESULT) {
2755 final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar);
2756 sendIqPacket(account, packet, new OnIqPacketReceived() {
2757 @Override
2758 public void onIqPacketReceived(Account account, IqPacket result) {
2759 if (result.getType() == IqPacket.TYPE.RESULT) {
2760 if (account.setAvatar(avatar.getFilename())) {
2761 getAvatarService().clear(account);
2762 databaseBackend.updateAccount(account);
2763 }
2764 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
2765 if (callback != null) {
2766 callback.success(avatar);
2767 }
2768 } else {
2769 if (callback != null) {
2770 callback.error(R.string.error_publish_avatar_server_reject, avatar);
2771 }
2772 }
2773 }
2774 });
2775 } else {
2776 Element error = result.findChild("error");
2777 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
2778 if (callback != null) {
2779 callback.error(R.string.error_publish_avatar_server_reject, avatar);
2780 }
2781 }
2782 }
2783 });
2784 }
2785
2786 public void republishAvatarIfNeeded(Account account) {
2787 if (account.getAxolotlService().isPepBroken()) {
2788 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
2789 return;
2790 }
2791 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2792 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2793
2794 private Avatar parseAvatar(IqPacket packet) {
2795 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2796 if (pubsub != null) {
2797 Element items = pubsub.findChild("items");
2798 if (items != null) {
2799 return Avatar.parseMetadata(items);
2800 }
2801 }
2802 return null;
2803 }
2804
2805 private boolean errorIsItemNotFound(IqPacket packet) {
2806 Element error = packet.findChild("error");
2807 return packet.getType() == IqPacket.TYPE.ERROR
2808 && error != null
2809 && error.hasChild("item-not-found");
2810 }
2811
2812 @Override
2813 public void onIqPacketReceived(Account account, IqPacket packet) {
2814 if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2815 Avatar serverAvatar = parseAvatar(packet);
2816 if (serverAvatar == null && account.getAvatar() != null) {
2817 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2818 if (avatar != null) {
2819 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
2820 publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2821 } else {
2822 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
2823 }
2824 }
2825 }
2826 }
2827 });
2828 }
2829
2830 public void fetchAvatar(Account account, Avatar avatar) {
2831 fetchAvatar(account, avatar, null);
2832 }
2833
2834 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2835 final String KEY = generateFetchKey(account, avatar);
2836 synchronized (this.mInProgressAvatarFetches) {
2837 if (!this.mInProgressAvatarFetches.contains(KEY)) {
2838 switch (avatar.origin) {
2839 case PEP:
2840 this.mInProgressAvatarFetches.add(KEY);
2841 fetchAvatarPep(account, avatar, callback);
2842 break;
2843 case VCARD:
2844 this.mInProgressAvatarFetches.add(KEY);
2845 fetchAvatarVcard(account, avatar, callback);
2846 break;
2847 }
2848 }
2849 }
2850 }
2851
2852 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2853 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2854 sendIqPacket(account, packet, new OnIqPacketReceived() {
2855
2856 @Override
2857 public void onIqPacketReceived(Account account, IqPacket result) {
2858 synchronized (mInProgressAvatarFetches) {
2859 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2860 }
2861 final String ERROR = account.getJid().asBareJid()
2862 + ": fetching avatar for " + avatar.owner + " failed ";
2863 if (result.getType() == IqPacket.TYPE.RESULT) {
2864 avatar.image = mIqParser.avatarData(result);
2865 if (avatar.image != null) {
2866 if (getFileBackend().save(avatar)) {
2867 if (account.getJid().asBareJid().equals(avatar.owner)) {
2868 if (account.setAvatar(avatar.getFilename())) {
2869 databaseBackend.updateAccount(account);
2870 }
2871 getAvatarService().clear(account);
2872 updateConversationUi();
2873 updateAccountUi();
2874 } else {
2875 Contact contact = account.getRoster()
2876 .getContact(avatar.owner);
2877 contact.setAvatar(avatar);
2878 getAvatarService().clear(contact);
2879 updateConversationUi();
2880 updateRosterUi();
2881 }
2882 if (callback != null) {
2883 callback.success(avatar);
2884 }
2885 Log.d(Config.LOGTAG, account.getJid().asBareJid()
2886 + ": successfully fetched pep avatar for " + avatar.owner);
2887 return;
2888 }
2889 } else {
2890
2891 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2892 }
2893 } else {
2894 Element error = result.findChild("error");
2895 if (error == null) {
2896 Log.d(Config.LOGTAG, ERROR + "(server error)");
2897 } else {
2898 Log.d(Config.LOGTAG, ERROR + error.toString());
2899 }
2900 }
2901 if (callback != null) {
2902 callback.error(0, null);
2903 }
2904
2905 }
2906 });
2907 }
2908
2909 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2910 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2911 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2912 @Override
2913 public void onIqPacketReceived(Account account, IqPacket packet) {
2914 synchronized (mInProgressAvatarFetches) {
2915 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2916 }
2917 if (packet.getType() == IqPacket.TYPE.RESULT) {
2918 Element vCard = packet.findChild("vCard", "vcard-temp");
2919 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2920 String image = photo != null ? photo.findChildContent("BINVAL") : null;
2921 if (image != null) {
2922 avatar.image = image;
2923 if (getFileBackend().save(avatar)) {
2924 Log.d(Config.LOGTAG, account.getJid().asBareJid()
2925 + ": successfully fetched vCard avatar for " + avatar.owner);
2926 if (avatar.owner.isBareJid()) {
2927 if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
2928 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
2929 account.setAvatar(avatar.getFilename());
2930 databaseBackend.updateAccount(account);
2931 getAvatarService().clear(account);
2932 updateAccountUi();
2933 } else {
2934 Contact contact = account.getRoster().getContact(avatar.owner);
2935 contact.setAvatar(avatar);
2936 getAvatarService().clear(contact);
2937 updateRosterUi();
2938 }
2939 updateConversationUi();
2940 } else {
2941 Conversation conversation = find(account, avatar.owner.asBareJid());
2942 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
2943 MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
2944 if (user != null) {
2945 if (user.setAvatar(avatar)) {
2946 getAvatarService().clear(user);
2947 updateConversationUi();
2948 updateMucRosterUi();
2949 }
2950 }
2951 }
2952 }
2953 }
2954 }
2955 }
2956 }
2957 });
2958 }
2959
2960 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2961 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2962 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2963
2964 @Override
2965 public void onIqPacketReceived(Account account, IqPacket packet) {
2966 if (packet.getType() == IqPacket.TYPE.RESULT) {
2967 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2968 if (pubsub != null) {
2969 Element items = pubsub.findChild("items");
2970 if (items != null) {
2971 Avatar avatar = Avatar.parseMetadata(items);
2972 if (avatar != null) {
2973 avatar.owner = account.getJid().asBareJid();
2974 if (fileBackend.isAvatarCached(avatar)) {
2975 if (account.setAvatar(avatar.getFilename())) {
2976 databaseBackend.updateAccount(account);
2977 }
2978 getAvatarService().clear(account);
2979 callback.success(avatar);
2980 } else {
2981 fetchAvatarPep(account, avatar, callback);
2982 }
2983 return;
2984 }
2985 }
2986 }
2987 }
2988 callback.error(0, null);
2989 }
2990 });
2991 }
2992
2993 public void deleteContactOnServer(Contact contact) {
2994 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2995 contact.resetOption(Contact.Options.DIRTY_PUSH);
2996 contact.setOption(Contact.Options.DIRTY_DELETE);
2997 Account account = contact.getAccount();
2998 if (account.getStatus() == Account.State.ONLINE) {
2999 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3000 Element item = iq.query(Namespace.ROSTER).addChild("item");
3001 item.setAttribute("jid", contact.getJid().toString());
3002 item.setAttribute("subscription", "remove");
3003 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3004 }
3005 }
3006
3007 public void updateConversation(final Conversation conversation) {
3008 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
3009 }
3010
3011 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
3012 synchronized (account) {
3013 XmppConnection connection = account.getXmppConnection();
3014 if (connection == null) {
3015 connection = createConnection(account);
3016 account.setXmppConnection(connection);
3017 }
3018 boolean hasInternet = hasInternetConnection();
3019 if (account.isEnabled() && hasInternet) {
3020 if (!force) {
3021 disconnect(account, false);
3022 }
3023 Thread thread = new Thread(connection);
3024 connection.setInteractive(interactive);
3025 connection.prepareNewConnection();
3026 connection.interrupt();
3027 thread.start();
3028 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
3029 } else {
3030 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
3031 account.getRoster().clearPresences();
3032 connection.resetEverything();
3033 final AxolotlService axolotlService = account.getAxolotlService();
3034 if (axolotlService != null) {
3035 axolotlService.resetBrokenness();
3036 }
3037 if (!hasInternet) {
3038 account.setStatus(Account.State.NO_INTERNET);
3039 }
3040 }
3041 }
3042 }
3043
3044 public void reconnectAccountInBackground(final Account account) {
3045 new Thread(() -> reconnectAccount(account, false, true)).start();
3046 }
3047
3048 public void invite(Conversation conversation, Jid contact) {
3049 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
3050 MessagePacket packet = mMessageGenerator.invite(conversation, contact);
3051 sendMessagePacket(conversation.getAccount(), packet);
3052 }
3053
3054 public void directInvite(Conversation conversation, Jid jid) {
3055 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
3056 sendMessagePacket(conversation.getAccount(), packet);
3057 }
3058
3059 public void resetSendingToWaiting(Account account) {
3060 for (Conversation conversation : getConversations()) {
3061 if (conversation.getAccount() == account) {
3062 conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
3063
3064 @Override
3065 public void onMessageFound(Message message) {
3066 markMessage(message, Message.STATUS_WAITING);
3067 }
3068 });
3069 }
3070 }
3071 }
3072
3073 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
3074 return markMessage(account, recipient, uuid, status, null);
3075 }
3076
3077 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
3078 if (uuid == null) {
3079 return null;
3080 }
3081 for (Conversation conversation : getConversations()) {
3082 if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
3083 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
3084 if (message != null) {
3085 markMessage(message, status, errorMessage);
3086 }
3087 return message;
3088 }
3089 }
3090 return null;
3091 }
3092
3093 public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) {
3094 if (uuid == null) {
3095 return false;
3096 } else {
3097 Message message = conversation.findSentMessageWithUuid(uuid);
3098 if (message != null) {
3099 if (message.getServerMsgId() == null) {
3100 message.setServerMsgId(serverMessageId);
3101 }
3102 markMessage(message, status);
3103 return true;
3104 } else {
3105 return false;
3106 }
3107 }
3108 }
3109
3110 public void markMessage(Message message, int status) {
3111 markMessage(message, status, null);
3112 }
3113
3114
3115 public void markMessage(Message message, int status, String errorMessage) {
3116 final int c = message.getStatus();
3117 if (status == Message.STATUS_SEND_FAILED && (c == Message.STATUS_SEND_RECEIVED || c == Message.STATUS_SEND_DISPLAYED)) {
3118 return;
3119 }
3120 if (status == Message.STATUS_SEND_RECEIVED && c == Message.STATUS_SEND_DISPLAYED) {
3121 return;
3122 }
3123 message.setErrorMessage(errorMessage);
3124 message.setStatus(status);
3125 databaseBackend.updateMessage(message);
3126 updateConversationUi();
3127 }
3128
3129 private SharedPreferences getPreferences() {
3130 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
3131 }
3132
3133 public long getAutomaticMessageDeletionDate() {
3134 final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
3135 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
3136 }
3137
3138 public long getLongPreference(String name, @IntegerRes int res) {
3139 long defaultValue = getResources().getInteger(res);
3140 try {
3141 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
3142 } catch (NumberFormatException e) {
3143 return defaultValue;
3144 }
3145 }
3146
3147 public boolean getBooleanPreference(String name, @BoolRes int res) {
3148 return getPreferences().getBoolean(name, getResources().getBoolean(res));
3149 }
3150
3151 public boolean confirmMessages() {
3152 return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
3153 }
3154
3155 public boolean allowMessageCorrection() {
3156 return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
3157 }
3158
3159 public boolean sendChatStates() {
3160 return getBooleanPreference("chat_states", R.bool.chat_states);
3161 }
3162
3163 private boolean respectAutojoin() {
3164 return getBooleanPreference("autojoin", R.bool.autojoin);
3165 }
3166
3167 public boolean indicateReceived() {
3168 return getBooleanPreference("indicate_received", R.bool.indicate_received);
3169 }
3170
3171 public boolean useTorToConnect() {
3172 return Config.FORCE_ORBOT || getBooleanPreference("use_tor", R.bool.use_tor);
3173 }
3174
3175 public boolean showExtendedConnectionOptions() {
3176 return getBooleanPreference("show_connection_options", R.bool.show_connection_options);
3177 }
3178
3179 public boolean broadcastLastActivity() {
3180 return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
3181 }
3182
3183 public int unreadCount() {
3184 int count = 0;
3185 for (Conversation conversation : getConversations()) {
3186 count += conversation.unreadCount();
3187 }
3188 return count;
3189 }
3190
3191
3192 public void showErrorToastInUi(int resId) {
3193 if (mOnShowErrorToast != null) {
3194 mOnShowErrorToast.onShowErrorToast(resId);
3195 }
3196 }
3197
3198 public void updateConversationUi() {
3199 if (mOnConversationUpdate != null) {
3200 mOnConversationUpdate.onConversationUpdate();
3201 }
3202 }
3203
3204 public void updateAccountUi() {
3205 if (mOnAccountUpdate != null) {
3206 mOnAccountUpdate.onAccountUpdate();
3207 }
3208 }
3209
3210 public void updateRosterUi() {
3211 if (mOnRosterUpdate != null) {
3212 mOnRosterUpdate.onRosterUpdate();
3213 }
3214 }
3215
3216 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3217 if (mOnCaptchaRequested != null) {
3218 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3219 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3220 (int) (captcha.getHeight() * metrics.scaledDensity), false);
3221
3222 mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
3223 return true;
3224 }
3225 return false;
3226 }
3227
3228 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3229 if (mOnUpdateBlocklist != null) {
3230 mOnUpdateBlocklist.OnUpdateBlocklist(status);
3231 }
3232 }
3233
3234 public void updateMucRosterUi() {
3235 if (mOnMucRosterUpdate != null) {
3236 mOnMucRosterUpdate.onMucRosterUpdate();
3237 }
3238 }
3239
3240 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3241 if (mOnKeyStatusUpdated != null) {
3242 mOnKeyStatusUpdated.onKeyStatusUpdated(report);
3243 }
3244 }
3245
3246 public Account findAccountByJid(final Jid accountJid) {
3247 for (Account account : this.accounts) {
3248 if (account.getJid().asBareJid().equals(accountJid.asBareJid())) {
3249 return account;
3250 }
3251 }
3252 return null;
3253 }
3254
3255 public Conversation findConversationByUuid(String uuid) {
3256 for (Conversation conversation : getConversations()) {
3257 if (conversation.getUuid().equals(uuid)) {
3258 return conversation;
3259 }
3260 }
3261 return null;
3262 }
3263
3264 public boolean markRead(final Conversation conversation, boolean dismiss) {
3265 return markRead(conversation, null, dismiss).size() > 0;
3266 }
3267
3268 public void markRead(final Conversation conversation) {
3269 markRead(conversation, null, true);
3270 }
3271
3272 public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
3273 if (dismiss) {
3274 mNotificationService.clear(conversation);
3275 }
3276 final List<Message> readMessages = conversation.markRead(upToUuid);
3277 if (readMessages.size() > 0) {
3278 Runnable runnable = () -> {
3279 for (Message message : readMessages) {
3280 databaseBackend.updateMessage(message);
3281 }
3282 };
3283 mDatabaseWriterExecutor.execute(runnable);
3284 updateUnreadCountBadge();
3285 return readMessages;
3286 } else {
3287 return readMessages;
3288 }
3289 }
3290
3291 public synchronized void updateUnreadCountBadge() {
3292 int count = unreadCount();
3293 if (unreadCount != count) {
3294 Log.d(Config.LOGTAG, "update unread count to " + count);
3295 if (count > 0) {
3296 ShortcutBadger.applyCount(getApplicationContext(), count);
3297 } else {
3298 ShortcutBadger.removeCount(getApplicationContext());
3299 }
3300 unreadCount = count;
3301 }
3302 }
3303
3304 public void sendReadMarker(final Conversation conversation, String upToUuid) {
3305 final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
3306 final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
3307 if (readMessages.size() > 0) {
3308 updateConversationUi();
3309 }
3310 final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
3311 if (confirmMessages()
3312 && markable != null
3313 && (markable.trusted() || isPrivateAndNonAnonymousMuc)
3314 && markable.getRemoteMsgId() != null) {
3315 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
3316 Account account = conversation.getAccount();
3317 final Jid to = markable.getCounterpart();
3318 final boolean groupChat = conversation.getMode() == Conversation.MODE_MULTI;
3319 MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId(), markable.getCounterpart(), groupChat);
3320 this.sendMessagePacket(conversation.getAccount(), packet);
3321 }
3322 }
3323
3324 public SecureRandom getRNG() {
3325 return this.mRandom;
3326 }
3327
3328 public MemorizingTrustManager getMemorizingTrustManager() {
3329 return this.mMemorizingTrustManager;
3330 }
3331
3332 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
3333 this.mMemorizingTrustManager = trustManager;
3334 }
3335
3336 public void updateMemorizingTrustmanager() {
3337 final MemorizingTrustManager tm;
3338 final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
3339 if (dontTrustSystemCAs) {
3340 tm = new MemorizingTrustManager(getApplicationContext(), null);
3341 } else {
3342 tm = new MemorizingTrustManager(getApplicationContext());
3343 }
3344 setMemorizingTrustManager(tm);
3345 }
3346
3347 public LruCache<String, Bitmap> getBitmapCache() {
3348 return this.mBitmapCache;
3349 }
3350
3351 public Collection<String> getKnownHosts() {
3352 final Set<String> hosts = new HashSet<>();
3353 for (final Account account : getAccounts()) {
3354 hosts.add(account.getServer());
3355 for (final Contact contact : account.getRoster().getContacts()) {
3356 if (contact.showInRoster()) {
3357 final String server = contact.getServer();
3358 if (server != null && !hosts.contains(server)) {
3359 hosts.add(server);
3360 }
3361 }
3362 }
3363 }
3364 if (Config.DOMAIN_LOCK != null) {
3365 hosts.add(Config.DOMAIN_LOCK);
3366 }
3367 if (Config.MAGIC_CREATE_DOMAIN != null) {
3368 hosts.add(Config.MAGIC_CREATE_DOMAIN);
3369 }
3370 return hosts;
3371 }
3372
3373 public Collection<String> getKnownConferenceHosts() {
3374 final Set<String> mucServers = new HashSet<>();
3375 for (final Account account : accounts) {
3376 if (account.getXmppConnection() != null) {
3377 mucServers.addAll(account.getXmppConnection().getMucServers());
3378 for (Bookmark bookmark : account.getBookmarks()) {
3379 final Jid jid = bookmark.getJid();
3380 final String s = jid == null ? null : jid.getDomain();
3381 if (s != null) {
3382 mucServers.add(s);
3383 }
3384 }
3385 }
3386 }
3387 return mucServers;
3388 }
3389
3390 public void sendMessagePacket(Account account, MessagePacket packet) {
3391 XmppConnection connection = account.getXmppConnection();
3392 if (connection != null) {
3393 connection.sendMessagePacket(packet);
3394 }
3395 }
3396
3397 public void sendPresencePacket(Account account, PresencePacket packet) {
3398 XmppConnection connection = account.getXmppConnection();
3399 if (connection != null) {
3400 connection.sendPresencePacket(packet);
3401 }
3402 }
3403
3404 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3405 final XmppConnection connection = account.getXmppConnection();
3406 if (connection != null) {
3407 IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3408 connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
3409 }
3410 }
3411
3412 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3413 final XmppConnection connection = account.getXmppConnection();
3414 if (connection != null) {
3415 connection.sendIqPacket(packet, callback);
3416 }
3417 }
3418
3419 public void sendPresence(final Account account) {
3420 sendPresence(account, checkListeners() && broadcastLastActivity());
3421 }
3422
3423 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3424 Presence.Status status;
3425 if (manuallyChangePresence()) {
3426 status = account.getPresenceStatus();
3427 } else {
3428 status = getTargetPresence();
3429 }
3430 PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
3431 String message = account.getPresenceStatusMessage();
3432 if (message != null && !message.isEmpty()) {
3433 packet.addChild(new Element("status").setContent(message));
3434 }
3435 if (mLastActivity > 0 && includeIdleTimestamp) {
3436 long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3437 packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
3438 }
3439 sendPresencePacket(account, packet);
3440 }
3441
3442 private void deactivateGracePeriod() {
3443 for (Account account : getAccounts()) {
3444 account.deactivateGracePeriod();
3445 }
3446 }
3447
3448 public void refreshAllPresences() {
3449 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3450 for (Account account : getAccounts()) {
3451 if (account.isEnabled()) {
3452 sendPresence(account, includeIdleTimestamp);
3453 }
3454 }
3455 }
3456
3457 private void refreshAllGcmTokens() {
3458 for (Account account : getAccounts()) {
3459 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3460 mPushManagementService.registerPushTokenOnServer(account);
3461 }
3462 }
3463 }
3464
3465 private void sendOfflinePresence(final Account account) {
3466 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
3467 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3468 }
3469
3470 public MessageGenerator getMessageGenerator() {
3471 return this.mMessageGenerator;
3472 }
3473
3474 public PresenceGenerator getPresenceGenerator() {
3475 return this.mPresenceGenerator;
3476 }
3477
3478 public IqGenerator getIqGenerator() {
3479 return this.mIqGenerator;
3480 }
3481
3482 public IqParser getIqParser() {
3483 return this.mIqParser;
3484 }
3485
3486 public JingleConnectionManager getJingleConnectionManager() {
3487 return this.mJingleConnectionManager;
3488 }
3489
3490 public MessageArchiveService getMessageArchiveService() {
3491 return this.mMessageArchiveService;
3492 }
3493
3494 public List<Contact> findContacts(Jid jid, String accountJid) {
3495 ArrayList<Contact> contacts = new ArrayList<>();
3496 for (Account account : getAccounts()) {
3497 if ((account.isEnabled() || accountJid != null)
3498 && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
3499 Contact contact = account.getRoster().getContactFromRoster(jid);
3500 if (contact != null) {
3501 contacts.add(contact);
3502 }
3503 }
3504 }
3505 return contacts;
3506 }
3507
3508 public Conversation findFirstMuc(Jid jid) {
3509 for (Conversation conversation : getConversations()) {
3510 if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
3511 return conversation;
3512 }
3513 }
3514 return null;
3515 }
3516
3517 public NotificationService getNotificationService() {
3518 return this.mNotificationService;
3519 }
3520
3521 public HttpConnectionManager getHttpConnectionManager() {
3522 return this.mHttpConnectionManager;
3523 }
3524
3525 public void resendFailedMessages(final Message message) {
3526 final Collection<Message> messages = new ArrayList<>();
3527 Message current = message;
3528 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3529 messages.add(current);
3530 if (current.mergeable(current.next())) {
3531 current = current.next();
3532 } else {
3533 break;
3534 }
3535 }
3536 for (final Message msg : messages) {
3537 msg.setTime(System.currentTimeMillis());
3538 markMessage(msg, Message.STATUS_WAITING);
3539 this.resendMessage(msg, false);
3540 }
3541 message.getConversation().sort();
3542 updateConversationUi();
3543 }
3544
3545 public void clearConversationHistory(final Conversation conversation) {
3546 final long clearDate;
3547 final String reference;
3548 if (conversation.countMessages() > 0) {
3549 Message latestMessage = conversation.getLatestMessage();
3550 clearDate = latestMessage.getTimeSent() + 1000;
3551 reference = latestMessage.getServerMsgId();
3552 } else {
3553 clearDate = System.currentTimeMillis();
3554 reference = null;
3555 }
3556 conversation.clearMessages();
3557 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3558 conversation.setLastClearHistory(clearDate, reference);
3559 Runnable runnable = () -> {
3560 databaseBackend.deleteMessagesInConversation(conversation);
3561 databaseBackend.updateConversation(conversation);
3562 };
3563 mDatabaseWriterExecutor.execute(runnable);
3564 }
3565
3566 public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
3567 if (blockable != null && blockable.getBlockedJid() != null) {
3568 final Jid jid = blockable.getBlockedJid();
3569 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), new OnIqPacketReceived() {
3570
3571 @Override
3572 public void onIqPacketReceived(final Account account, final IqPacket packet) {
3573 if (packet.getType() == IqPacket.TYPE.RESULT) {
3574 account.getBlocklist().add(jid);
3575 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3576 }
3577 }
3578 });
3579 if (removeBlockedConversations(blockable.getAccount(), jid)) {
3580 updateConversationUi();
3581 return true;
3582 } else {
3583 return false;
3584 }
3585 } else {
3586 return false;
3587 }
3588 }
3589
3590 public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
3591 boolean removed = false;
3592 synchronized (this.conversations) {
3593 boolean domainJid = blockedJid.getLocal() == null;
3594 for (Conversation conversation : this.conversations) {
3595 boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
3596 || blockedJid.equals(conversation.getJid().asBareJid());
3597 if (conversation.getAccount() == account
3598 && conversation.getMode() == Conversation.MODE_SINGLE
3599 && jidMatches) {
3600 this.conversations.remove(conversation);
3601 markRead(conversation);
3602 conversation.setStatus(Conversation.STATUS_ARCHIVED);
3603 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
3604 updateConversation(conversation);
3605 removed = true;
3606 }
3607 }
3608 }
3609 return removed;
3610 }
3611
3612 public void sendUnblockRequest(final Blockable blockable) {
3613 if (blockable != null && blockable.getJid() != null) {
3614 final Jid jid = blockable.getBlockedJid();
3615 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3616 @Override
3617 public void onIqPacketReceived(final Account account, final IqPacket packet) {
3618 if (packet.getType() == IqPacket.TYPE.RESULT) {
3619 account.getBlocklist().remove(jid);
3620 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3621 }
3622 }
3623 });
3624 }
3625 }
3626
3627 public void publishDisplayName(Account account) {
3628 String displayName = account.getDisplayName();
3629 if (displayName != null && !displayName.isEmpty()) {
3630 IqPacket publish = mIqGenerator.publishNick(displayName);
3631 sendIqPacket(account, publish, (account1, packet) -> {
3632 if (packet.getType() == IqPacket.TYPE.ERROR) {
3633 Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": could not publish nick");
3634 }
3635 });
3636 }
3637 }
3638
3639 public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
3640 ServiceDiscoveryResult result = discoCache.get(key);
3641 if (result != null) {
3642 return result;
3643 } else {
3644 result = databaseBackend.findDiscoveryResult(key.first, key.second);
3645 if (result != null) {
3646 discoCache.put(key, result);
3647 }
3648 return result;
3649 }
3650 }
3651
3652 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3653 final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
3654 ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3655 if (disco != null) {
3656 presence.setServiceDiscoveryResult(disco);
3657 } else {
3658 if (!account.inProgressDiscoFetches.contains(key)) {
3659 account.inProgressDiscoFetches.add(key);
3660 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3661 request.setTo(jid);
3662 request.query("http://jabber.org/protocol/disco#info");
3663 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
3664 sendIqPacket(account, request, (account1, discoPacket) -> {
3665 if (discoPacket.getType() == IqPacket.TYPE.RESULT) {
3666 ServiceDiscoveryResult disco1 = new ServiceDiscoveryResult(discoPacket);
3667 if (presence.getVer().equals(disco1.getVer())) {
3668 databaseBackend.insertDiscoveryResult(disco1);
3669 injectServiceDiscorveryResult(account1.getRoster(), presence.getHash(), presence.getVer(), disco1);
3670 } else {
3671 Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco1.getVer());
3672 }
3673 }
3674 account1.inProgressDiscoFetches.remove(key);
3675 });
3676 }
3677 }
3678 }
3679
3680 private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3681 for (Contact contact : roster.getContacts()) {
3682 for (Presence presence : contact.getPresences().getPresences().values()) {
3683 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3684 presence.setServiceDiscoveryResult(disco);
3685 }
3686 }
3687 }
3688 }
3689
3690 public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3691 final boolean legacy = account.getXmppConnection().getFeatures().mamLegacy();
3692 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3693 request.addChild("prefs", legacy ? Namespace.MAM_LEGACY : Namespace.MAM);
3694 sendIqPacket(account, request, (account1, packet) -> {
3695 Element prefs = packet.findChild("prefs", legacy ? Namespace.MAM_LEGACY : Namespace.MAM);
3696 if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3697 callback.onPreferencesFetched(prefs);
3698 } else {
3699 callback.onPreferencesFetchFailed();
3700 }
3701 });
3702 }
3703
3704 public PushManagementService getPushManagementService() {
3705 return mPushManagementService;
3706 }
3707
3708 public Account getPendingAccount() {
3709 Account pending = null;
3710 for (Account account : getAccounts()) {
3711 if (!account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY)) {
3712 pending = account;
3713 } else {
3714 return null;
3715 }
3716 }
3717 return pending;
3718 }
3719
3720 public void changeStatus(Account account, PresenceTemplate template, String signature) {
3721 if (!template.getStatusMessage().isEmpty()) {
3722 databaseBackend.insertPresenceTemplate(template);
3723 }
3724 account.setPgpSignature(signature);
3725 account.setPresenceStatus(template.getStatus());
3726 account.setPresenceStatusMessage(template.getStatusMessage());
3727 databaseBackend.updateAccount(account);
3728 sendPresence(account);
3729 }
3730
3731 public List<PresenceTemplate> getPresenceTemplates(Account account) {
3732 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3733 for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3734 if (!templates.contains(template)) {
3735 templates.add(0, template);
3736 }
3737 }
3738 return templates;
3739 }
3740
3741 public void saveConversationAsBookmark(Conversation conversation, String name) {
3742 Account account = conversation.getAccount();
3743 Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
3744 if (!conversation.getJid().isBareJid()) {
3745 bookmark.setNick(conversation.getJid().getResource());
3746 }
3747 if (name != null && !name.trim().isEmpty()) {
3748 bookmark.setBookmarkName(name.trim());
3749 }
3750 bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
3751 account.getBookmarks().add(bookmark);
3752 pushBookmarks(account);
3753 bookmark.setConversation(conversation);
3754 }
3755
3756 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
3757 boolean performedVerification = false;
3758 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
3759 for (XmppUri.Fingerprint fp : fingerprints) {
3760 if (fp.type == XmppUri.FingerprintType.OMEMO) {
3761 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
3762 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3763 if (fingerprintStatus != null) {
3764 if (!fingerprintStatus.isVerified()) {
3765 performedVerification = true;
3766 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
3767 }
3768 } else {
3769 axolotlService.preVerifyFingerprint(contact, fingerprint);
3770 }
3771 }
3772 }
3773 return performedVerification;
3774 }
3775
3776 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
3777 final AxolotlService axolotlService = account.getAxolotlService();
3778 boolean verifiedSomething = false;
3779 for (XmppUri.Fingerprint fp : fingerprints) {
3780 if (fp.type == XmppUri.FingerprintType.OMEMO) {
3781 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
3782 Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
3783 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3784 if (fingerprintStatus != null) {
3785 if (!fingerprintStatus.isVerified()) {
3786 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
3787 verifiedSomething = true;
3788 }
3789 } else {
3790 axolotlService.preVerifyFingerprint(account, fingerprint);
3791 verifiedSomething = true;
3792 }
3793 }
3794 }
3795 return verifiedSomething;
3796 }
3797
3798 public boolean blindTrustBeforeVerification() {
3799 return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
3800 }
3801
3802 public ShortcutService getShortcutService() {
3803 return mShortcutService;
3804 }
3805
3806 public void pushMamPreferences(Account account, Element prefs) {
3807 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3808 set.addChild(prefs);
3809 sendIqPacket(account, set, null);
3810 }
3811
3812 public interface OnMamPreferencesFetched {
3813 void onPreferencesFetched(Element prefs);
3814
3815 void onPreferencesFetchFailed();
3816 }
3817
3818 public interface OnAccountCreated {
3819 void onAccountCreated(Account account);
3820
3821 void informUser(int r);
3822 }
3823
3824 public interface OnMoreMessagesLoaded {
3825 void onMoreMessagesLoaded(int count, Conversation conversation);
3826
3827 void informUser(int r);
3828 }
3829
3830 public interface OnAccountPasswordChanged {
3831 void onPasswordChangeSucceeded();
3832
3833 void onPasswordChangeFailed();
3834 }
3835
3836 public interface OnAffiliationChanged {
3837 void onAffiliationChangedSuccessful(Jid jid);
3838
3839 void onAffiliationChangeFailed(Jid jid, int resId);
3840 }
3841
3842 public interface OnRoleChanged {
3843 void onRoleChangedSuccessful(String nick);
3844
3845 void onRoleChangeFailed(String nick, int resid);
3846 }
3847
3848 public interface OnConversationUpdate {
3849 void onConversationUpdate();
3850 }
3851
3852 public interface OnAccountUpdate {
3853 void onAccountUpdate();
3854 }
3855
3856 public interface OnCaptchaRequested {
3857 void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
3858 }
3859
3860 public interface OnRosterUpdate {
3861 void onRosterUpdate();
3862 }
3863
3864 public interface OnMucRosterUpdate {
3865 void onMucRosterUpdate();
3866 }
3867
3868 public interface OnConferenceConfigurationFetched {
3869 void onConferenceConfigurationFetched(Conversation conversation);
3870
3871 void onFetchFailed(Conversation conversation, Element error);
3872 }
3873
3874 public interface OnConferenceJoined {
3875 void onConferenceJoined(Conversation conversation);
3876 }
3877
3878 public interface OnConfigurationPushed {
3879 void onPushSucceeded();
3880
3881 void onPushFailed();
3882 }
3883
3884 public interface OnShowErrorToast {
3885 void onShowErrorToast(int resId);
3886 }
3887
3888 public class XmppConnectionBinder extends Binder {
3889 public XmppConnectionService getService() {
3890 return XmppConnectionService.this;
3891 }
3892 }
3893}