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