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