1package eu.siacs.conversations.services;
2
3import static eu.siacs.conversations.utils.Compatibility.s;
4
5import android.Manifest;
6import android.annotation.SuppressLint;
7import android.app.AlarmManager;
8import android.app.KeyguardManager;
9import android.app.Notification;
10import android.app.NotificationManager;
11import android.app.PendingIntent;
12import android.app.Service;
13import android.content.BroadcastReceiver;
14import android.content.ComponentName;
15import android.content.Context;
16import android.content.Intent;
17import android.content.IntentFilter;
18import android.content.SharedPreferences;
19import android.content.pm.PackageManager;
20import android.content.pm.ServiceInfo;
21import android.database.ContentObserver;
22import android.graphics.Bitmap;
23import android.media.AudioManager;
24import android.net.ConnectivityManager;
25import android.net.Network;
26import android.net.NetworkCapabilities;
27import android.net.NetworkInfo;
28import android.net.Uri;
29import android.os.Binder;
30import android.os.Build;
31import android.os.Bundle;
32import android.os.Environment;
33import android.os.IBinder;
34import android.os.Messenger;
35import android.os.PowerManager;
36import android.os.PowerManager.WakeLock;
37import android.os.SystemClock;
38import android.preference.PreferenceManager;
39import android.provider.ContactsContract;
40import android.security.KeyChain;
41import android.text.TextUtils;
42import android.util.DisplayMetrics;
43import android.util.Log;
44import android.util.LruCache;
45import android.util.Pair;
46import androidx.annotation.BoolRes;
47import androidx.annotation.IntegerRes;
48import androidx.annotation.NonNull;
49import androidx.annotation.Nullable;
50import androidx.core.app.RemoteInput;
51import androidx.core.content.ContextCompat;
52import com.google.common.base.Objects;
53import com.google.common.base.Optional;
54import com.google.common.base.Strings;
55import com.google.common.collect.Collections2;
56import com.google.common.collect.ImmutableMap;
57import com.google.common.collect.ImmutableSet;
58import com.google.common.collect.Iterables;
59import com.google.common.collect.Maps;
60import com.google.common.util.concurrent.FutureCallback;
61import com.google.common.util.concurrent.Futures;
62import com.google.common.util.concurrent.ListenableFuture;
63import com.google.common.util.concurrent.MoreExecutors;
64import eu.siacs.conversations.AppSettings;
65import eu.siacs.conversations.Config;
66import eu.siacs.conversations.R;
67import eu.siacs.conversations.android.JabberIdContact;
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.Message;
81import eu.siacs.conversations.entities.MucOptions;
82import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
83import eu.siacs.conversations.entities.PresenceTemplate;
84import eu.siacs.conversations.entities.Reaction;
85import eu.siacs.conversations.generator.AbstractGenerator;
86import eu.siacs.conversations.generator.IqGenerator;
87import eu.siacs.conversations.generator.MessageGenerator;
88import eu.siacs.conversations.generator.PresenceGenerator;
89import eu.siacs.conversations.http.HttpConnectionManager;
90import eu.siacs.conversations.http.ServiceOutageStatus;
91import eu.siacs.conversations.parser.AbstractParser;
92import eu.siacs.conversations.parser.IqParser;
93import eu.siacs.conversations.persistance.DatabaseBackend;
94import eu.siacs.conversations.persistance.FileBackend;
95import eu.siacs.conversations.persistance.UnifiedPushDatabase;
96import eu.siacs.conversations.receiver.SystemEventReceiver;
97import eu.siacs.conversations.ui.ChooseAccountForProfilePictureActivity;
98import eu.siacs.conversations.ui.ConversationsActivity;
99import eu.siacs.conversations.ui.RtpSessionActivity;
100import eu.siacs.conversations.ui.UiCallback;
101import eu.siacs.conversations.ui.interfaces.OnAvatarPublication;
102import eu.siacs.conversations.ui.interfaces.OnMediaLoaded;
103import eu.siacs.conversations.ui.interfaces.OnSearchResultsAvailable;
104import eu.siacs.conversations.utils.AccountUtils;
105import eu.siacs.conversations.utils.Compatibility;
106import eu.siacs.conversations.utils.ConversationsFileObserver;
107import eu.siacs.conversations.utils.CryptoHelper;
108import eu.siacs.conversations.utils.EasyOnboardingInvite;
109import eu.siacs.conversations.utils.Emoticons;
110import eu.siacs.conversations.utils.MimeUtils;
111import eu.siacs.conversations.utils.PhoneHelper;
112import eu.siacs.conversations.utils.QuickLoader;
113import eu.siacs.conversations.utils.ReplacingSerialSingleThreadExecutor;
114import eu.siacs.conversations.utils.Resolver;
115import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
116import eu.siacs.conversations.utils.StringUtils;
117import eu.siacs.conversations.utils.TorServiceUtils;
118import eu.siacs.conversations.utils.WakeLockHelper;
119import eu.siacs.conversations.utils.XmppUri;
120import eu.siacs.conversations.xml.Element;
121import eu.siacs.conversations.xml.LocalizedContent;
122import eu.siacs.conversations.xml.Namespace;
123import eu.siacs.conversations.xmpp.Jid;
124import eu.siacs.conversations.xmpp.OnContactStatusChanged;
125import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
126import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
127import eu.siacs.conversations.xmpp.XmppConnection;
128import eu.siacs.conversations.xmpp.chatstate.ChatState;
129import eu.siacs.conversations.xmpp.forms.Data;
130import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
131import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
132import eu.siacs.conversations.xmpp.jingle.Media;
133import eu.siacs.conversations.xmpp.jingle.RtpEndUserState;
134import eu.siacs.conversations.xmpp.mam.MamReference;
135import eu.siacs.conversations.xmpp.manager.AvatarManager;
136import eu.siacs.conversations.xmpp.manager.BlockingManager;
137import eu.siacs.conversations.xmpp.manager.BookmarkManager;
138import eu.siacs.conversations.xmpp.manager.DiscoManager;
139import eu.siacs.conversations.xmpp.manager.LegacyBookmarkManager;
140import eu.siacs.conversations.xmpp.manager.NickManager;
141import eu.siacs.conversations.xmpp.manager.PresenceManager;
142import eu.siacs.conversations.xmpp.manager.PrivateStorageManager;
143import eu.siacs.conversations.xmpp.manager.RosterManager;
144import eu.siacs.conversations.xmpp.pep.Avatar;
145import eu.siacs.conversations.xmpp.pep.PublishOptions;
146import im.conversations.android.xmpp.Entity;
147import im.conversations.android.xmpp.IqErrorException;
148import im.conversations.android.xmpp.model.avatar.Metadata;
149import im.conversations.android.xmpp.model.disco.info.InfoQuery;
150import im.conversations.android.xmpp.model.pubsub.PubSub;
151import im.conversations.android.xmpp.model.stanza.Iq;
152import im.conversations.android.xmpp.model.up.Push;
153import java.io.File;
154import java.security.Security;
155import java.security.cert.CertificateException;
156import java.security.cert.X509Certificate;
157import java.util.ArrayList;
158import java.util.Arrays;
159import java.util.Collection;
160import java.util.Collections;
161import java.util.HashSet;
162import java.util.Iterator;
163import java.util.List;
164import java.util.ListIterator;
165import java.util.Map;
166import java.util.Set;
167import java.util.WeakHashMap;
168import java.util.concurrent.CopyOnWriteArrayList;
169import java.util.concurrent.CountDownLatch;
170import java.util.concurrent.Executor;
171import java.util.concurrent.Executors;
172import java.util.concurrent.RejectedExecutionException;
173import java.util.concurrent.ScheduledExecutorService;
174import java.util.concurrent.TimeUnit;
175import java.util.concurrent.TimeoutException;
176import java.util.concurrent.atomic.AtomicBoolean;
177import java.util.concurrent.atomic.AtomicLong;
178import java.util.concurrent.atomic.AtomicReference;
179import java.util.function.Consumer;
180import me.leolin.shortcutbadger.ShortcutBadger;
181import okhttp3.HttpUrl;
182import org.conscrypt.Conscrypt;
183import org.jxmpp.stringprep.libidn.LibIdnXmppStringprep;
184import org.openintents.openpgp.IOpenPgpService2;
185import org.openintents.openpgp.util.OpenPgpApi;
186import org.openintents.openpgp.util.OpenPgpServiceConnection;
187
188public class XmppConnectionService extends Service {
189
190 public static final String ACTION_REPLY_TO_CONVERSATION = "reply_to_conversations";
191 public static final String ACTION_MARK_AS_READ = "mark_as_read";
192 public static final String ACTION_SNOOZE = "snooze";
193 public static final String ACTION_CLEAR_MESSAGE_NOTIFICATION = "clear_message_notification";
194 public static final String ACTION_CLEAR_MISSED_CALL_NOTIFICATION =
195 "clear_missed_call_notification";
196 public static final String ACTION_DISMISS_ERROR_NOTIFICATIONS = "dismiss_error";
197 public static final String ACTION_TRY_AGAIN = "try_again";
198
199 public static final String ACTION_TEMPORARILY_DISABLE = "temporarily_disable";
200 public static final String ACTION_PING = "ping";
201 public static final String ACTION_IDLE_PING = "idle_ping";
202 public static final String ACTION_INTERNAL_PING = "internal_ping";
203 public static final String ACTION_FCM_TOKEN_REFRESH = "fcm_token_refresh";
204 public static final String ACTION_FCM_MESSAGE_RECEIVED = "fcm_message_received";
205 public static final String ACTION_DISMISS_CALL = "dismiss_call";
206 public static final String ACTION_END_CALL = "end_call";
207 public static final String ACTION_PROVISION_ACCOUNT = "provision_account";
208 public static final String ACTION_CALL_INTEGRATION_SERVICE_STARTED =
209 "call_integration_service_started";
210 private static final String ACTION_POST_CONNECTIVITY_CHANGE =
211 "eu.siacs.conversations.POST_CONNECTIVITY_CHANGE";
212 public static final String ACTION_RENEW_UNIFIED_PUSH_ENDPOINTS =
213 "eu.siacs.conversations.UNIFIED_PUSH_RENEW";
214 public static final String ACTION_QUICK_LOG = "eu.siacs.conversations.QUICK_LOG";
215
216 private static final String SETTING_LAST_ACTIVITY_TS = "last_activity_timestamp";
217
218 public final CountDownLatch restoredFromDatabaseLatch = new CountDownLatch(1);
219 private static final Executor FILE_OBSERVER_EXECUTOR = Executors.newSingleThreadExecutor();
220 public static final Executor FILE_ATTACHMENT_EXECUTOR = Executors.newSingleThreadExecutor();
221
222 public final ScheduledExecutorService internalPingExecutor =
223 Executors.newSingleThreadScheduledExecutor();
224 private static final SerialSingleThreadExecutor VIDEO_COMPRESSION_EXECUTOR =
225 new SerialSingleThreadExecutor("VideoCompression");
226 private final SerialSingleThreadExecutor mDatabaseWriterExecutor =
227 new SerialSingleThreadExecutor("DatabaseWriter");
228 private final SerialSingleThreadExecutor mDatabaseReaderExecutor =
229 new SerialSingleThreadExecutor("DatabaseReader");
230 private final SerialSingleThreadExecutor mNotificationExecutor =
231 new SerialSingleThreadExecutor("NotificationExecutor");
232 private final IBinder mBinder = new XmppConnectionBinder();
233 private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
234 private final IqGenerator mIqGenerator = new IqGenerator(this);
235 private final Set<String> mInProgressAvatarFetches = new HashSet<>();
236 private final Set<String> mOmittedPepAvatarFetches = new HashSet<>();
237 public final HashSet<Jid> mLowPingTimeoutMode = new HashSet<>();
238 public DatabaseBackend databaseBackend;
239 private final ReplacingSerialSingleThreadExecutor mContactMergerExecutor =
240 new ReplacingSerialSingleThreadExecutor("ContactMerger");
241 private long mLastActivity = 0;
242
243 private final AppSettings appSettings = new AppSettings(this);
244 private final FileBackend fileBackend = new FileBackend(this);
245 private MemorizingTrustManager mMemorizingTrustManager;
246 private final NotificationService mNotificationService = new NotificationService(this);
247 private final UnifiedPushBroker unifiedPushBroker = new UnifiedPushBroker(this);
248 private final ChannelDiscoveryService mChannelDiscoveryService =
249 new ChannelDiscoveryService(this);
250 private final ShortcutService mShortcutService = new ShortcutService(this);
251 private final AtomicBoolean mInitialAddressbookSyncCompleted = new AtomicBoolean(false);
252 private final AtomicBoolean mOngoingVideoTranscoding = new AtomicBoolean(false);
253 private final AtomicBoolean mForceDuringOnCreate = new AtomicBoolean(false);
254 private final AtomicReference<OngoingCall> ongoingCall = new AtomicReference<>();
255 private final MessageGenerator mMessageGenerator = new MessageGenerator(this);
256 public OnContactStatusChanged onContactStatusChanged =
257 (contact, online) -> {
258 final var conversation = find(contact);
259 if (conversation == null) {
260 return;
261 }
262 if (online) {
263 if (contact.getPresences().size() == 1) {
264 sendUnsentMessages(conversation);
265 }
266 }
267 };
268 private final PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
269 private List<Account> accounts;
270 private final JingleConnectionManager mJingleConnectionManager =
271 new JingleConnectionManager(this);
272 private final HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(this);
273 private final AvatarService mAvatarService = new AvatarService(this);
274 private final MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
275 private final PushManagementService mPushManagementService = new PushManagementService(this);
276 private final QuickConversationsService mQuickConversationsService =
277 new QuickConversationsService(this);
278 private final ConversationsFileObserver fileObserver =
279 new ConversationsFileObserver(
280 Environment.getExternalStorageDirectory().getAbsolutePath()) {
281 @Override
282 public void onEvent(final int event, final File file) {
283 markFileDeleted(file);
284 }
285 };
286 private boolean destroyed = false;
287
288 private int unreadCount = -1;
289
290 // Ui callback listeners
291 private final Set<OnConversationUpdate> mOnConversationUpdates =
292 Collections.newSetFromMap(new WeakHashMap<OnConversationUpdate, Boolean>());
293 private final Set<OnShowErrorToast> mOnShowErrorToasts =
294 Collections.newSetFromMap(new WeakHashMap<OnShowErrorToast, Boolean>());
295 private final Set<OnAccountUpdate> mOnAccountUpdates =
296 Collections.newSetFromMap(new WeakHashMap<OnAccountUpdate, Boolean>());
297 private final Set<OnCaptchaRequested> mOnCaptchaRequested =
298 Collections.newSetFromMap(new WeakHashMap<OnCaptchaRequested, Boolean>());
299 private final Set<OnRosterUpdate> mOnRosterUpdates =
300 Collections.newSetFromMap(new WeakHashMap<OnRosterUpdate, Boolean>());
301 private final Set<OnUpdateBlocklist> mOnUpdateBlocklist =
302 Collections.newSetFromMap(new WeakHashMap<OnUpdateBlocklist, Boolean>());
303 private final Set<OnMucRosterUpdate> mOnMucRosterUpdate =
304 Collections.newSetFromMap(new WeakHashMap<OnMucRosterUpdate, Boolean>());
305 private final Set<OnKeyStatusUpdated> mOnKeyStatusUpdated =
306 Collections.newSetFromMap(new WeakHashMap<OnKeyStatusUpdated, Boolean>());
307 private final Set<OnJingleRtpConnectionUpdate> onJingleRtpConnectionUpdate =
308 Collections.newSetFromMap(new WeakHashMap<OnJingleRtpConnectionUpdate, Boolean>());
309
310 private final Object LISTENER_LOCK = new Object();
311
312 public final Set<String> FILENAMES_TO_IGNORE_DELETION = new HashSet<>();
313
314 private final AtomicLong mLastExpiryRun = new AtomicLong(0);
315
316 private OpenPgpServiceConnection pgpServiceConnection;
317 private PgpEngine mPgpEngine = null;
318 private WakeLock wakeLock;
319 private LruCache<String, Bitmap> mBitmapCache;
320 private final BroadcastReceiver mInternalEventReceiver = new InternalEventReceiver();
321 private final BroadcastReceiver mInternalRestrictedEventReceiver =
322 new RestrictedEventReceiver(List.of(TorServiceUtils.ACTION_STATUS));
323 private final BroadcastReceiver mInternalScreenEventReceiver = new InternalEventReceiver();
324
325 private static String generateFetchKey(Account account, final Avatar avatar) {
326 return account.getJid().asBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum;
327 }
328
329 public boolean isInLowPingTimeoutMode(Account account) {
330 synchronized (mLowPingTimeoutMode) {
331 return mLowPingTimeoutMode.contains(account.getJid().asBareJid());
332 }
333 }
334
335 public void startOngoingVideoTranscodingForegroundNotification() {
336 mOngoingVideoTranscoding.set(true);
337 toggleForegroundService();
338 }
339
340 public void stopOngoingVideoTranscodingForegroundNotification() {
341 mOngoingVideoTranscoding.set(false);
342 toggleForegroundService();
343 }
344
345 public boolean areMessagesInitialized() {
346 return this.restoredFromDatabaseLatch.getCount() == 0;
347 }
348
349 public PgpEngine getPgpEngine() {
350 if (!Config.supportOpenPgp()) {
351 return null;
352 } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
353 if (this.mPgpEngine == null) {
354 this.mPgpEngine =
355 new PgpEngine(
356 new OpenPgpApi(
357 getApplicationContext(), pgpServiceConnection.getService()),
358 this);
359 }
360 return mPgpEngine;
361 } else {
362 return null;
363 }
364 }
365
366 public OpenPgpApi getOpenPgpApi() {
367 if (!Config.supportOpenPgp()) {
368 return null;
369 } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
370 return new OpenPgpApi(this, pgpServiceConnection.getService());
371 } else {
372 return null;
373 }
374 }
375
376 public AppSettings getAppSettings() {
377 return this.appSettings;
378 }
379
380 public FileBackend getFileBackend() {
381 return this.fileBackend;
382 }
383
384 public AvatarService getAvatarService() {
385 return this.mAvatarService;
386 }
387
388 public void attachLocationToConversation(
389 final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
390 int encryption = conversation.getNextEncryption();
391 if (encryption == Message.ENCRYPTION_PGP) {
392 encryption = Message.ENCRYPTION_DECRYPTED;
393 }
394 Message message = new Message(conversation, uri.toString(), encryption);
395 Message.configurePrivateMessage(message);
396 if (encryption == Message.ENCRYPTION_DECRYPTED) {
397 getPgpEngine().encrypt(message, callback);
398 } else {
399 sendMessage(message);
400 callback.success(message);
401 }
402 }
403
404 public void attachFileToConversation(
405 final Conversation conversation,
406 final Uri uri,
407 final String type,
408 final UiCallback<Message> callback) {
409 final Message message;
410 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
411 message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
412 } else {
413 message = new Message(conversation, "", conversation.getNextEncryption());
414 }
415 if (!Message.configurePrivateFileMessage(message)) {
416 message.setCounterpart(conversation.getNextCounterpart());
417 message.setType(Message.TYPE_FILE);
418 }
419 Log.d(Config.LOGTAG, "attachFile: type=" + message.getType());
420 Log.d(Config.LOGTAG, "counterpart=" + message.getCounterpart());
421 final AttachFileToConversationRunnable runnable =
422 new AttachFileToConversationRunnable(this, uri, type, message, callback);
423 if (runnable.isVideoMessage()) {
424 VIDEO_COMPRESSION_EXECUTOR.execute(runnable);
425 } else {
426 FILE_ATTACHMENT_EXECUTOR.execute(runnable);
427 }
428 }
429
430 public void attachImageToConversation(
431 final Conversation conversation,
432 final Uri uri,
433 final String type,
434 final UiCallback<Message> callback) {
435 final String mimeType = MimeUtils.guessMimeTypeFromUriAndMime(this, uri, type);
436 final String compressPictures = getCompressPicturesPreference();
437
438 if ("never".equals(compressPictures)
439 || ("auto".equals(compressPictures) && getFileBackend().useImageAsIs(uri))
440 || (mimeType != null && mimeType.endsWith("/gif"))
441 || getFileBackend().unusualBounds(uri)) {
442 Log.d(
443 Config.LOGTAG,
444 conversation.getAccount().getJid().asBareJid()
445 + ": not compressing picture. sending as file");
446 attachFileToConversation(conversation, uri, mimeType, callback);
447 return;
448 }
449 final Message message;
450 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
451 message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
452 } else {
453 message = new Message(conversation, "", conversation.getNextEncryption());
454 }
455 if (!Message.configurePrivateFileMessage(message)) {
456 message.setCounterpart(conversation.getNextCounterpart());
457 message.setType(Message.TYPE_IMAGE);
458 }
459 Log.d(Config.LOGTAG, "attachImage: type=" + message.getType());
460 FILE_ATTACHMENT_EXECUTOR.execute(
461 () -> {
462 try {
463 getFileBackend().copyImageToPrivateStorage(message, uri);
464 } catch (FileBackend.ImageCompressionException e) {
465 Log.d(
466 Config.LOGTAG,
467 "unable to compress image. fall back to file transfer",
468 e);
469 attachFileToConversation(conversation, uri, mimeType, callback);
470 return;
471 } catch (final FileBackend.FileCopyException e) {
472 callback.error(e.getResId(), message);
473 return;
474 }
475 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
476 final PgpEngine pgpEngine = getPgpEngine();
477 if (pgpEngine != null) {
478 pgpEngine.encrypt(message, callback);
479 } else if (callback != null) {
480 callback.error(R.string.unable_to_connect_to_keychain, null);
481 }
482 } else {
483 sendMessage(message);
484 callback.success(message);
485 }
486 });
487 }
488
489 public Conversation find(Bookmark bookmark) {
490 return find(bookmark.getAccount(), bookmark.getJid());
491 }
492
493 public Conversation find(final Account account, final Jid jid) {
494 return find(getConversations(), account, jid);
495 }
496
497 public boolean isMuc(final Account account, final Jid jid) {
498 final Conversation c = find(account, jid);
499 return c != null && c.getMode() == Conversational.MODE_MULTI;
500 }
501
502 public void search(
503 final List<String> term,
504 final String uuid,
505 final OnSearchResultsAvailable onSearchResultsAvailable) {
506 MessageSearchTask.search(this, term, uuid, onSearchResultsAvailable);
507 }
508
509 @Override
510 public int onStartCommand(final Intent intent, int flags, int startId) {
511 final String action = Strings.nullToEmpty(intent == null ? null : intent.getAction());
512 final boolean needsForegroundService =
513 intent != null
514 && intent.getBooleanExtra(
515 SystemEventReceiver.EXTRA_NEEDS_FOREGROUND_SERVICE, false);
516 if (needsForegroundService) {
517 Log.d(
518 Config.LOGTAG,
519 "toggle forced foreground service after receiving event (action="
520 + action
521 + ")");
522 toggleForegroundService(true);
523 }
524 final String uuid = intent == null ? null : intent.getStringExtra("uuid");
525 switch (action) {
526 case QuickConversationsService.SMS_RETRIEVED_ACTION:
527 mQuickConversationsService.handleSmsReceived(intent);
528 break;
529 case ConnectivityManager.CONNECTIVITY_ACTION:
530 if (hasInternetConnection()) {
531 if (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL > 0) {
532 schedulePostConnectivityChange();
533 }
534 if (Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
535 resetAllAttemptCounts(true, false);
536 }
537 Resolver.clearCache();
538 }
539 break;
540 case Intent.ACTION_SHUTDOWN:
541 logoutAndSave(true);
542 return START_NOT_STICKY;
543 case ACTION_CLEAR_MESSAGE_NOTIFICATION:
544 mNotificationExecutor.execute(
545 () -> {
546 try {
547 final Conversation c = findConversationByUuid(uuid);
548 if (c != null) {
549 mNotificationService.clearMessages(c);
550 } else {
551 mNotificationService.clearMessages();
552 }
553 restoredFromDatabaseLatch.await();
554
555 } catch (InterruptedException e) {
556 Log.d(
557 Config.LOGTAG,
558 "unable to process clear message notification");
559 }
560 });
561 break;
562 case ACTION_CLEAR_MISSED_CALL_NOTIFICATION:
563 mNotificationExecutor.execute(
564 () -> {
565 try {
566 final Conversation c = findConversationByUuid(uuid);
567 if (c != null) {
568 mNotificationService.clearMissedCalls(c);
569 } else {
570 mNotificationService.clearMissedCalls();
571 }
572 restoredFromDatabaseLatch.await();
573
574 } catch (InterruptedException e) {
575 Log.d(
576 Config.LOGTAG,
577 "unable to process clear missed call notification");
578 }
579 });
580 break;
581 case ACTION_DISMISS_CALL:
582 {
583 if (intent == null) {
584 break;
585 }
586 final String sessionId =
587 intent.getStringExtra(RtpSessionActivity.EXTRA_SESSION_ID);
588 Log.d(
589 Config.LOGTAG,
590 "received intent to dismiss call with session id " + sessionId);
591 mJingleConnectionManager.rejectRtpSession(sessionId);
592 break;
593 }
594 case TorServiceUtils.ACTION_STATUS:
595 final String status =
596 intent == null ? null : intent.getStringExtra(TorServiceUtils.EXTRA_STATUS);
597 // TODO port and host are in 'extras' - but this may not be a reliable source?
598 if ("ON".equals(status)) {
599 handleOrbotStartedEvent();
600 return START_STICKY;
601 }
602 break;
603 case ACTION_END_CALL:
604 {
605 if (intent == null) {
606 break;
607 }
608 final String sessionId =
609 intent.getStringExtra(RtpSessionActivity.EXTRA_SESSION_ID);
610 Log.d(
611 Config.LOGTAG,
612 "received intent to end call with session id " + sessionId);
613 mJingleConnectionManager.endRtpSession(sessionId);
614 }
615 break;
616 case ACTION_PROVISION_ACCOUNT:
617 {
618 if (intent == null) {
619 break;
620 }
621 final String address = intent.getStringExtra("address");
622 final String password = intent.getStringExtra("password");
623 if (QuickConversationsService.isQuicksy()
624 || Strings.isNullOrEmpty(address)
625 || Strings.isNullOrEmpty(password)) {
626 break;
627 }
628 provisionAccount(address, password);
629 break;
630 }
631 case ACTION_DISMISS_ERROR_NOTIFICATIONS:
632 dismissErrorNotifications();
633 break;
634 case ACTION_TRY_AGAIN:
635 resetAllAttemptCounts(false, true);
636 break;
637 case ACTION_REPLY_TO_CONVERSATION:
638 final Bundle remoteInput =
639 intent == null ? null : RemoteInput.getResultsFromIntent(intent);
640 if (remoteInput == null) {
641 break;
642 }
643 final CharSequence body = remoteInput.getCharSequence("text_reply");
644 final boolean dismissNotification =
645 intent.getBooleanExtra("dismiss_notification", false);
646 final String lastMessageUuid = intent.getStringExtra("last_message_uuid");
647 if (body == null || body.length() <= 0) {
648 break;
649 }
650 mNotificationExecutor.execute(
651 () -> {
652 try {
653 restoredFromDatabaseLatch.await();
654 final Conversation c = findConversationByUuid(uuid);
655 if (c != null) {
656 directReply(
657 c,
658 body.toString(),
659 lastMessageUuid,
660 dismissNotification);
661 }
662 } catch (InterruptedException e) {
663 Log.d(Config.LOGTAG, "unable to process direct reply");
664 }
665 });
666 break;
667 case ACTION_MARK_AS_READ:
668 mNotificationExecutor.execute(
669 () -> {
670 final Conversation c = findConversationByUuid(uuid);
671 if (c == null) {
672 Log.d(
673 Config.LOGTAG,
674 "received mark read intent for unknown conversation ("
675 + uuid
676 + ")");
677 return;
678 }
679 try {
680 restoredFromDatabaseLatch.await();
681 sendReadMarker(c, null);
682 } catch (InterruptedException e) {
683 Log.d(
684 Config.LOGTAG,
685 "unable to process notification read marker for"
686 + " conversation "
687 + c.getName());
688 }
689 });
690 break;
691 case ACTION_SNOOZE:
692 mNotificationExecutor.execute(
693 () -> {
694 final Conversation c = findConversationByUuid(uuid);
695 if (c == null) {
696 Log.d(
697 Config.LOGTAG,
698 "received snooze intent for unknown conversation ("
699 + uuid
700 + ")");
701 return;
702 }
703 c.setMutedTill(System.currentTimeMillis() + 30 * 60 * 1000);
704 mNotificationService.clearMessages(c);
705 updateConversation(c);
706 });
707 case AudioManager.RINGER_MODE_CHANGED_ACTION:
708 case NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED:
709 if (dndOnSilentMode()) {
710 refreshAllPresences();
711 }
712 break;
713 case Intent.ACTION_SCREEN_ON:
714 deactivateGracePeriod();
715 case Intent.ACTION_USER_PRESENT:
716 case Intent.ACTION_SCREEN_OFF:
717 if (awayWhenScreenLocked()) {
718 refreshAllPresences();
719 }
720 break;
721 case ACTION_FCM_TOKEN_REFRESH:
722 refreshAllFcmTokens();
723 break;
724 case ACTION_RENEW_UNIFIED_PUSH_ENDPOINTS:
725 if (intent == null) {
726 break;
727 }
728 final String instance = intent.getStringExtra("instance");
729 final String application = intent.getStringExtra("application");
730 final Messenger messenger = intent.getParcelableExtra("messenger");
731 final UnifiedPushBroker.PushTargetMessenger pushTargetMessenger;
732 if (messenger != null && application != null && instance != null) {
733 pushTargetMessenger =
734 new UnifiedPushBroker.PushTargetMessenger(
735 new UnifiedPushDatabase.PushTarget(application, instance),
736 messenger);
737 Log.d(Config.LOGTAG, "found push target messenger");
738 } else {
739 pushTargetMessenger = null;
740 }
741 final Optional<UnifiedPushBroker.Transport> transport =
742 renewUnifiedPushEndpoints(pushTargetMessenger);
743 if (instance != null && transport.isPresent()) {
744 unifiedPushBroker.rebroadcastEndpoint(messenger, instance, transport.get());
745 }
746 break;
747 case ACTION_IDLE_PING:
748 scheduleNextIdlePing();
749 break;
750 case ACTION_FCM_MESSAGE_RECEIVED:
751 Log.d(Config.LOGTAG, "push message arrived in service. account");
752 break;
753 case ACTION_QUICK_LOG:
754 final String message = intent == null ? null : intent.getStringExtra("message");
755 if (message != null && Config.QUICK_LOG) {
756 quickLog(message);
757 }
758 break;
759 case Intent.ACTION_SEND:
760 final Uri uri = intent == null ? null : intent.getData();
761 if (uri != null) {
762 Log.d(Config.LOGTAG, "received uri permission for " + uri);
763 }
764 return START_STICKY;
765 case ACTION_TEMPORARILY_DISABLE:
766 toggleSoftDisabled(true);
767 if (checkListeners()) {
768 stopSelf();
769 }
770 return START_NOT_STICKY;
771 }
772 final var extras = intent == null ? null : intent.getExtras();
773 try {
774 internalPingExecutor.execute(() -> manageAccountConnectionStates(action, extras));
775 } catch (final RejectedExecutionException e) {
776 Log.e(Config.LOGTAG, "can not schedule connection states manager");
777 }
778 if (SystemClock.elapsedRealtime() - mLastExpiryRun.get() >= Config.EXPIRY_INTERVAL) {
779 expireOldMessages();
780 }
781 return START_STICKY;
782 }
783
784 private void quickLog(final String message) {
785 if (Strings.isNullOrEmpty(message)) {
786 return;
787 }
788 final Account account = AccountUtils.getFirstEnabled(this);
789 if (account == null) {
790 return;
791 }
792 final Conversation conversation =
793 findOrCreateConversation(account, Config.BUG_REPORTS, false, true);
794 final Message report = new Message(conversation, message, Message.ENCRYPTION_NONE);
795 report.setStatus(Message.STATUS_RECEIVED);
796 conversation.add(report);
797 databaseBackend.createMessage(report);
798 updateConversationUi();
799 }
800
801 public void manageAccountConnectionStatesInternal() {
802 manageAccountConnectionStates(ACTION_INTERNAL_PING, null);
803 }
804
805 private synchronized void manageAccountConnectionStates(
806 final String action, final Bundle extras) {
807 final String pushedAccountHash = extras == null ? null : extras.getString("account");
808 final boolean interactive = java.util.Objects.equals(ACTION_TRY_AGAIN, action);
809 WakeLockHelper.acquire(wakeLock);
810 boolean pingNow =
811 ConnectivityManager.CONNECTIVITY_ACTION.equals(action)
812 || (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL > 0
813 && ACTION_POST_CONNECTIVITY_CHANGE.equals(action));
814 final HashSet<Account> pingCandidates = new HashSet<>();
815 final String androidId = pushedAccountHash == null ? null : PhoneHelper.getAndroidId(this);
816 for (final Account account : accounts) {
817 final boolean pushWasMeantForThisAccount =
818 androidId != null
819 && CryptoHelper.getAccountFingerprint(account, androidId)
820 .equals(pushedAccountHash);
821 pingNow |=
822 processAccountState(
823 account,
824 interactive,
825 "ui".equals(action),
826 pushWasMeantForThisAccount,
827 pingCandidates);
828 }
829 if (pingNow) {
830 for (final Account account : pingCandidates) {
831 final var connection = account.getXmppConnection();
832 final boolean lowTimeout = isInLowPingTimeoutMode(account);
833 final var delta =
834 (SystemClock.elapsedRealtime() - connection.getLastPacketReceived())
835 / 1000L;
836 connection.sendPing();
837 Log.d(
838 Config.LOGTAG,
839 String.format(
840 "%s: send ping (action=%s,lowTimeout=%s,interval=%s)",
841 account.getJid().asBareJid(), action, lowTimeout, delta));
842 scheduleWakeUpCall(
843 lowTimeout ? Config.LOW_PING_TIMEOUT : Config.PING_TIMEOUT,
844 account.getUuid().hashCode());
845 }
846 }
847 WakeLockHelper.release(wakeLock);
848 }
849
850 private void handleOrbotStartedEvent() {
851 for (final Account account : accounts) {
852 if (account.getStatus() == Account.State.TOR_NOT_AVAILABLE) {
853 reconnectAccount(account, true, false);
854 }
855 }
856 }
857
858 private boolean processAccountState(
859 final Account account,
860 final boolean interactive,
861 final boolean isUiAction,
862 final boolean isAccountPushed,
863 final HashSet<Account> pingCandidates) {
864 final var connection = account.getXmppConnection();
865 if (!account.getStatus().isAttemptReconnect()) {
866 return false;
867 }
868 final var requestCode = account.getUuid().hashCode();
869 if (!hasInternetConnection()) {
870 connection.setStatusAndTriggerProcessor(Account.State.NO_INTERNET);
871 } else {
872 if (account.getStatus() == Account.State.NO_INTERNET) {
873 connection.setStatusAndTriggerProcessor(Account.State.OFFLINE);
874 }
875 if (account.getStatus() == Account.State.ONLINE) {
876 synchronized (mLowPingTimeoutMode) {
877 long lastReceived = account.getXmppConnection().getLastPacketReceived();
878 long lastSent = account.getXmppConnection().getLastPingSent();
879 long pingInterval =
880 isUiAction
881 ? Config.PING_MIN_INTERVAL * 1000
882 : Config.PING_MAX_INTERVAL * 1000;
883 long msToNextPing =
884 (Math.max(lastReceived, lastSent) + pingInterval)
885 - SystemClock.elapsedRealtime();
886 int pingTimeout =
887 mLowPingTimeoutMode.contains(account.getJid().asBareJid())
888 ? Config.LOW_PING_TIMEOUT * 1000
889 : Config.PING_TIMEOUT * 1000;
890 long pingTimeoutIn = (lastSent + pingTimeout) - SystemClock.elapsedRealtime();
891 if (lastSent > lastReceived) {
892 if (pingTimeoutIn < 0) {
893 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ping timeout");
894 this.reconnectAccount(account, true, interactive);
895 } else {
896 this.scheduleWakeUpCall(pingTimeoutIn, requestCode);
897 }
898 } else {
899 pingCandidates.add(account);
900 if (isAccountPushed) {
901 if (mLowPingTimeoutMode.add(account.getJid().asBareJid())) {
902 Log.d(
903 Config.LOGTAG,
904 account.getJid().asBareJid()
905 + ": entering low ping timeout mode");
906 }
907 return true;
908 } else if (msToNextPing <= 0) {
909 return true;
910 } else {
911 this.scheduleWakeUpCall(msToNextPing, requestCode);
912 if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
913 Log.d(
914 Config.LOGTAG,
915 account.getJid().asBareJid()
916 + ": leaving low ping timeout mode");
917 }
918 }
919 }
920 }
921 } else if (account.getStatus() == Account.State.OFFLINE) {
922 reconnectAccount(account, true, interactive);
923 } else if (account.getStatus() == Account.State.CONNECTING) {
924 final var connectionDuration = connection.getConnectionDuration();
925 final var discoDuration = connection.getDiscoDuration();
926 final var connectionTimeout = Config.CONNECT_TIMEOUT * 1000L - connectionDuration;
927 final var discoTimeout = Config.CONNECT_DISCO_TIMEOUT * 1000L - discoDuration;
928 if (connectionTimeout < 0) {
929 connection.triggerConnectionTimeout();
930 } else if (discoTimeout < 0) {
931 connection.sendDiscoTimeout();
932 scheduleWakeUpCall(discoTimeout, requestCode);
933 } else {
934 scheduleWakeUpCall(Math.min(connectionTimeout, discoTimeout), requestCode);
935 }
936 } else {
937 final boolean aggressive =
938 account.getStatus() == Account.State.SEE_OTHER_HOST
939 || hasJingleRtpConnection(account);
940 if (connection.getTimeToNextAttempt(aggressive) <= 0) {
941 reconnectAccount(account, true, interactive);
942 }
943 }
944 }
945 return false;
946 }
947
948 private void toggleSoftDisabled(final boolean softDisabled) {
949 for (final Account account : this.accounts) {
950 if (account.isEnabled()) {
951 if (account.setOption(Account.OPTION_SOFT_DISABLED, softDisabled)) {
952 updateAccount(account);
953 }
954 }
955 }
956 }
957
958 public void fetchServiceOutageStatus(final Account account) {
959 final var sosUrl = account.getKey(Account.KEY_SOS_URL);
960 if (Strings.isNullOrEmpty(sosUrl)) {
961 return;
962 }
963 final var url = HttpUrl.parse(sosUrl);
964 if (url == null) {
965 return;
966 }
967 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching service outage " + url);
968 Futures.addCallback(
969 ServiceOutageStatus.fetch(getApplicationContext(), url),
970 new FutureCallback<>() {
971 @Override
972 public void onSuccess(final ServiceOutageStatus sos) {
973 Log.d(Config.LOGTAG, "fetched " + sos);
974 account.setServiceOutageStatus(sos);
975 updateAccountUi();
976 }
977
978 @Override
979 public void onFailure(@NonNull Throwable throwable) {
980 Log.d(Config.LOGTAG, "error fetching sos", throwable);
981 }
982 },
983 MoreExecutors.directExecutor());
984 }
985
986 public boolean processUnifiedPushMessage(
987 final Account account, final Jid transport, final Push push) {
988 return unifiedPushBroker.processPushMessage(account, transport, push);
989 }
990
991 public void reinitializeMuclumbusService() {
992 mChannelDiscoveryService.initializeMuclumbusService();
993 }
994
995 public void discoverChannels(
996 String query,
997 ChannelDiscoveryService.Method method,
998 ChannelDiscoveryService.OnChannelSearchResultsFound onChannelSearchResultsFound) {
999 mChannelDiscoveryService.discover(
1000 Strings.nullToEmpty(query).trim(), method, onChannelSearchResultsFound);
1001 }
1002
1003 public boolean isDataSaverDisabled() {
1004 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
1005 return true;
1006 }
1007 final ConnectivityManager connectivityManager = getSystemService(ConnectivityManager.class);
1008 return !Compatibility.isActiveNetworkMetered(connectivityManager)
1009 || Compatibility.getRestrictBackgroundStatus(connectivityManager)
1010 == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
1011 }
1012
1013 private void directReply(
1014 final Conversation conversation,
1015 final String body,
1016 final String lastMessageUuid,
1017 final boolean dismissAfterReply) {
1018 final Message inReplyTo =
1019 lastMessageUuid == null ? null : conversation.findMessageWithUuid(lastMessageUuid);
1020 final Message message = new Message(conversation, body, conversation.getNextEncryption());
1021 if (inReplyTo != null && inReplyTo.isPrivateMessage()) {
1022 Message.configurePrivateMessage(message, inReplyTo.getCounterpart());
1023 }
1024 message.markUnread();
1025 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
1026 getPgpEngine()
1027 .encrypt(
1028 message,
1029 new UiCallback<Message>() {
1030 @Override
1031 public void success(Message message) {
1032 if (dismissAfterReply) {
1033 markRead((Conversation) message.getConversation(), true);
1034 } else {
1035 mNotificationService.pushFromDirectReply(message);
1036 }
1037 }
1038
1039 @Override
1040 public void error(int errorCode, Message object) {}
1041
1042 @Override
1043 public void userInputRequired(PendingIntent pi, Message object) {}
1044 });
1045 } else {
1046 sendMessage(message);
1047 if (dismissAfterReply) {
1048 markRead(conversation, true);
1049 } else {
1050 mNotificationService.pushFromDirectReply(message);
1051 }
1052 }
1053 }
1054
1055 private boolean dndOnSilentMode() {
1056 return getBooleanPreference(AppSettings.DND_ON_SILENT_MODE, R.bool.dnd_on_silent_mode);
1057 }
1058
1059 private boolean manuallyChangePresence() {
1060 return getBooleanPreference(
1061 AppSettings.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
1062 }
1063
1064 private boolean treatVibrateAsSilent() {
1065 return getBooleanPreference(
1066 AppSettings.TREAT_VIBRATE_AS_SILENT, R.bool.treat_vibrate_as_silent);
1067 }
1068
1069 private boolean awayWhenScreenLocked() {
1070 return getBooleanPreference(
1071 AppSettings.AWAY_WHEN_SCREEN_IS_OFF, R.bool.away_when_screen_off);
1072 }
1073
1074 private String getCompressPicturesPreference() {
1075 return getPreferences()
1076 .getString(
1077 "picture_compression",
1078 getResources().getString(R.string.picture_compression));
1079 }
1080
1081 private im.conversations.android.xmpp.model.stanza.Presence.Availability getTargetPresence() {
1082 if (dndOnSilentMode() && isPhoneSilenced()) {
1083 return im.conversations.android.xmpp.model.stanza.Presence.Availability.DND;
1084 } else if (awayWhenScreenLocked() && isScreenLocked()) {
1085 return im.conversations.android.xmpp.model.stanza.Presence.Availability.AWAY;
1086 } else {
1087 return im.conversations.android.xmpp.model.stanza.Presence.Availability.ONLINE;
1088 }
1089 }
1090
1091 public boolean isScreenLocked() {
1092 final KeyguardManager keyguardManager = getSystemService(KeyguardManager.class);
1093 final PowerManager powerManager = getSystemService(PowerManager.class);
1094 final boolean locked = keyguardManager != null && keyguardManager.isKeyguardLocked();
1095 final boolean interactive;
1096 try {
1097 interactive = powerManager != null && powerManager.isInteractive();
1098 } catch (final Exception e) {
1099 return false;
1100 }
1101 return locked || !interactive;
1102 }
1103
1104 private boolean isPhoneSilenced() {
1105 final NotificationManager notificationManager = getSystemService(NotificationManager.class);
1106 final int filter =
1107 notificationManager == null
1108 ? NotificationManager.INTERRUPTION_FILTER_UNKNOWN
1109 : notificationManager.getCurrentInterruptionFilter();
1110 final boolean notificationDnd = filter >= NotificationManager.INTERRUPTION_FILTER_PRIORITY;
1111 final AudioManager audioManager = getSystemService(AudioManager.class);
1112 final int ringerMode =
1113 audioManager == null
1114 ? AudioManager.RINGER_MODE_NORMAL
1115 : audioManager.getRingerMode();
1116 try {
1117 if (treatVibrateAsSilent()) {
1118 return notificationDnd || ringerMode != AudioManager.RINGER_MODE_NORMAL;
1119 } else {
1120 return notificationDnd || ringerMode == AudioManager.RINGER_MODE_SILENT;
1121 }
1122 } catch (final Throwable throwable) {
1123 Log.d(
1124 Config.LOGTAG,
1125 "platform bug in isPhoneSilenced (" + throwable.getMessage() + ")");
1126 return notificationDnd;
1127 }
1128 }
1129
1130 private void resetAllAttemptCounts(boolean reallyAll, boolean retryImmediately) {
1131 Log.d(Config.LOGTAG, "resetting all attempt counts");
1132 for (Account account : accounts) {
1133 if (account.hasErrorStatus() || reallyAll) {
1134 final XmppConnection connection = account.getXmppConnection();
1135 if (connection != null) {
1136 connection.resetAttemptCount(retryImmediately);
1137 }
1138 }
1139 if (account.setShowErrorNotification(true)) {
1140 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateAccount(account));
1141 }
1142 }
1143 mNotificationService.updateErrorNotification();
1144 }
1145
1146 private void dismissErrorNotifications() {
1147 for (final Account account : this.accounts) {
1148 if (account.hasErrorStatus()) {
1149 Log.d(
1150 Config.LOGTAG,
1151 account.getJid().asBareJid() + ": dismissing error notification");
1152 if (account.setShowErrorNotification(false)) {
1153 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateAccount(account));
1154 }
1155 }
1156 }
1157 }
1158
1159 private void expireOldMessages() {
1160 expireOldMessages(false);
1161 }
1162
1163 public void expireOldMessages(final boolean resetHasMessagesLeftOnServer) {
1164 mLastExpiryRun.set(SystemClock.elapsedRealtime());
1165 mDatabaseWriterExecutor.execute(
1166 () -> {
1167 long timestamp = getAutomaticMessageDeletionDate();
1168 if (timestamp > 0) {
1169 databaseBackend.expireOldMessages(timestamp);
1170 synchronized (XmppConnectionService.this.conversations) {
1171 for (Conversation conversation :
1172 XmppConnectionService.this.conversations) {
1173 conversation.expireOldMessages(timestamp);
1174 if (resetHasMessagesLeftOnServer) {
1175 conversation.messagesLoaded.set(true);
1176 conversation.setHasMessagesLeftOnServer(true);
1177 }
1178 }
1179 }
1180 updateConversationUi();
1181 }
1182 });
1183 }
1184
1185 public boolean hasInternetConnection() {
1186 final ConnectivityManager cm =
1187 ContextCompat.getSystemService(this, ConnectivityManager.class);
1188 if (cm == null) {
1189 return true; // if internet connection can not be checked it is probably best to just
1190 // try
1191 }
1192 try {
1193 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
1194 final Network activeNetwork = cm.getActiveNetwork();
1195 final NetworkCapabilities capabilities =
1196 activeNetwork == null ? null : cm.getNetworkCapabilities(activeNetwork);
1197 return capabilities != null
1198 && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1199 } else {
1200 final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
1201 return networkInfo != null
1202 && (networkInfo.isConnected()
1203 || networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET);
1204 }
1205 } catch (final RuntimeException e) {
1206 Log.d(Config.LOGTAG, "unable to check for internet connection", e);
1207 return true; // if internet connection can not be checked it is probably best to just
1208 // try
1209 }
1210 }
1211
1212 @SuppressLint("TrulyRandom")
1213 @Override
1214 public void onCreate() {
1215 LibIdnXmppStringprep.setup();
1216 if (Compatibility.twentySix()) {
1217 mNotificationService.initializeChannels();
1218 }
1219 mChannelDiscoveryService.initializeMuclumbusService();
1220 mForceDuringOnCreate.set(Compatibility.twentySix());
1221 toggleForegroundService();
1222 this.destroyed = false;
1223 OmemoSetting.load(this);
1224 try {
1225 Security.insertProviderAt(Conscrypt.newProvider(), 1);
1226 } catch (Throwable throwable) {
1227 Log.e(Config.LOGTAG, "unable to initialize security provider", throwable);
1228 }
1229 updateMemorizingTrustManager();
1230 final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
1231 final int cacheSize = maxMemory / 8;
1232 this.mBitmapCache =
1233 new LruCache<String, Bitmap>(cacheSize) {
1234 @Override
1235 protected int sizeOf(final String key, final Bitmap bitmap) {
1236 return bitmap.getByteCount() / 1024;
1237 }
1238 };
1239 if (mLastActivity == 0) {
1240 mLastActivity =
1241 getPreferences().getLong(SETTING_LAST_ACTIVITY_TS, System.currentTimeMillis());
1242 }
1243
1244 Log.d(Config.LOGTAG, "initializing database...");
1245 this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
1246 Log.d(Config.LOGTAG, "restoring accounts...");
1247 this.accounts = databaseBackend.getAccounts();
1248 for (final var account : this.accounts) {
1249 account.setXmppConnection(createConnection(account));
1250 }
1251 final SharedPreferences.Editor editor = getPreferences().edit();
1252 final boolean hasEnabledAccounts = hasEnabledAccounts();
1253 editor.putBoolean(SystemEventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
1254 editor.apply();
1255 toggleSetProfilePictureActivity(hasEnabledAccounts);
1256 reconfigurePushDistributor();
1257
1258 if (CallIntegration.hasSystemFeature(this)) {
1259 CallIntegrationConnectionService.togglePhoneAccountsAsync(this, this.accounts);
1260 }
1261
1262 restoreFromDatabase();
1263
1264 if (QuickConversationsService.isContactListIntegration(this)
1265 && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
1266 == PackageManager.PERMISSION_GRANTED) {
1267 startContactObserver();
1268 }
1269 FILE_OBSERVER_EXECUTOR.execute(fileBackend::deleteHistoricAvatarPath);
1270 if (Compatibility.hasStoragePermission(this)) {
1271 Log.d(Config.LOGTAG, "starting file observer");
1272 FILE_OBSERVER_EXECUTOR.execute(this.fileObserver::startWatching);
1273 FILE_OBSERVER_EXECUTOR.execute(this::checkForDeletedFiles);
1274 }
1275 if (Config.supportOpenPgp()) {
1276 this.pgpServiceConnection =
1277 new OpenPgpServiceConnection(
1278 this,
1279 "org.sufficientlysecure.keychain",
1280 new OpenPgpServiceConnection.OnBound() {
1281 @Override
1282 public void onBound(final IOpenPgpService2 service) {
1283 for (Account account : accounts) {
1284 final PgpDecryptionService pgp =
1285 account.getPgpDecryptionService();
1286 if (pgp != null) {
1287 pgp.continueDecryption(true);
1288 }
1289 }
1290 }
1291
1292 @Override
1293 public void onError(final Exception exception) {
1294 Log.e(
1295 Config.LOGTAG,
1296 "could not bind to OpenKeyChain",
1297 exception);
1298 }
1299 });
1300 this.pgpServiceConnection.bindToService();
1301 }
1302
1303 final PowerManager powerManager = getSystemService(PowerManager.class);
1304 if (powerManager != null) {
1305 this.wakeLock =
1306 powerManager.newWakeLock(
1307 PowerManager.PARTIAL_WAKE_LOCK, "Conversations:Service");
1308 }
1309
1310 toggleForegroundService();
1311 updateUnreadCountBadge();
1312 toggleScreenEventReceiver();
1313 final IntentFilter systemBroadcastFilter = new IntentFilter();
1314 scheduleNextIdlePing();
1315 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1316 systemBroadcastFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1317 }
1318 systemBroadcastFilter.addAction(NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED);
1319 ContextCompat.registerReceiver(
1320 this,
1321 this.mInternalEventReceiver,
1322 systemBroadcastFilter,
1323 ContextCompat.RECEIVER_NOT_EXPORTED);
1324 final IntentFilter exportedBroadcastFilter = new IntentFilter();
1325 exportedBroadcastFilter.addAction(TorServiceUtils.ACTION_STATUS);
1326 ContextCompat.registerReceiver(
1327 this,
1328 this.mInternalRestrictedEventReceiver,
1329 exportedBroadcastFilter,
1330 ContextCompat.RECEIVER_EXPORTED);
1331 mForceDuringOnCreate.set(false);
1332 toggleForegroundService();
1333 internalPingExecutor.scheduleWithFixedDelay(
1334 this::manageAccountConnectionStatesInternal, 10, 10, TimeUnit.SECONDS);
1335 final SharedPreferences sharedPreferences =
1336 androidx.preference.PreferenceManager.getDefaultSharedPreferences(this);
1337 sharedPreferences.registerOnSharedPreferenceChangeListener(
1338 new SharedPreferences.OnSharedPreferenceChangeListener() {
1339 @Override
1340 public void onSharedPreferenceChanged(
1341 SharedPreferences sharedPreferences, @Nullable String key) {
1342 Log.d(Config.LOGTAG, "preference '" + key + "' has changed");
1343 if (AppSettings.KEEP_FOREGROUND_SERVICE.equals(key)) {
1344 toggleForegroundService();
1345 }
1346 }
1347 });
1348 }
1349
1350 private void checkForDeletedFiles() {
1351 if (destroyed) {
1352 Log.d(
1353 Config.LOGTAG,
1354 "Do not check for deleted files because service has been destroyed");
1355 return;
1356 }
1357 final long start = SystemClock.elapsedRealtime();
1358 final List<DatabaseBackend.FilePathInfo> relativeFilePaths =
1359 databaseBackend.getFilePathInfo();
1360 final List<DatabaseBackend.FilePathInfo> changed = new ArrayList<>();
1361 for (final DatabaseBackend.FilePathInfo filePath : relativeFilePaths) {
1362 if (destroyed) {
1363 Log.d(
1364 Config.LOGTAG,
1365 "Stop checking for deleted files because service has been destroyed");
1366 return;
1367 }
1368 final File file = fileBackend.getFileForPath(filePath.path);
1369 if (filePath.setDeleted(!file.exists())) {
1370 changed.add(filePath);
1371 }
1372 }
1373 final long duration = SystemClock.elapsedRealtime() - start;
1374 Log.d(
1375 Config.LOGTAG,
1376 "found "
1377 + changed.size()
1378 + " changed files on start up. total="
1379 + relativeFilePaths.size()
1380 + ". ("
1381 + duration
1382 + "ms)");
1383 if (changed.size() > 0) {
1384 databaseBackend.markFilesAsChanged(changed);
1385 markChangedFiles(changed);
1386 }
1387 }
1388
1389 public void startContactObserver() {
1390 getContentResolver()
1391 .registerContentObserver(
1392 ContactsContract.Contacts.CONTENT_URI,
1393 true,
1394 new ContentObserver(null) {
1395 @Override
1396 public void onChange(boolean selfChange) {
1397 super.onChange(selfChange);
1398 if (restoredFromDatabaseLatch.getCount() == 0) {
1399 loadPhoneContacts();
1400 }
1401 }
1402 });
1403 }
1404
1405 @Override
1406 public void onTrimMemory(int level) {
1407 super.onTrimMemory(level);
1408 if (level >= TRIM_MEMORY_COMPLETE) {
1409 Log.d(Config.LOGTAG, "clear cache due to low memory");
1410 getBitmapCache().evictAll();
1411 }
1412 }
1413
1414 @Override
1415 public void onDestroy() {
1416 try {
1417 unregisterReceiver(this.mInternalEventReceiver);
1418 unregisterReceiver(this.mInternalRestrictedEventReceiver);
1419 unregisterReceiver(this.mInternalScreenEventReceiver);
1420 } catch (final IllegalArgumentException e) {
1421 // ignored
1422 }
1423 destroyed = false;
1424 fileObserver.stopWatching();
1425 internalPingExecutor.shutdown();
1426 super.onDestroy();
1427 }
1428
1429 public void restartFileObserver() {
1430 Log.d(Config.LOGTAG, "restarting file observer");
1431 FILE_OBSERVER_EXECUTOR.execute(this.fileObserver::restartWatching);
1432 FILE_OBSERVER_EXECUTOR.execute(this::checkForDeletedFiles);
1433 }
1434
1435 public void toggleScreenEventReceiver() {
1436 if (awayWhenScreenLocked() && !manuallyChangePresence()) {
1437 final IntentFilter filter = new IntentFilter();
1438 filter.addAction(Intent.ACTION_SCREEN_ON);
1439 filter.addAction(Intent.ACTION_SCREEN_OFF);
1440 filter.addAction(Intent.ACTION_USER_PRESENT);
1441 registerReceiver(this.mInternalScreenEventReceiver, filter);
1442 } else {
1443 try {
1444 unregisterReceiver(this.mInternalScreenEventReceiver);
1445 } catch (IllegalArgumentException e) {
1446 // ignored
1447 }
1448 }
1449 }
1450
1451 public void toggleForegroundService() {
1452 toggleForegroundService(false);
1453 }
1454
1455 public void setOngoingCall(
1456 AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
1457 ongoingCall.set(new OngoingCall(id, media, reconnecting));
1458 toggleForegroundService(false);
1459 }
1460
1461 public void removeOngoingCall() {
1462 ongoingCall.set(null);
1463 toggleForegroundService(false);
1464 }
1465
1466 private void toggleForegroundService(final boolean force) {
1467 final boolean status;
1468 final OngoingCall ongoing = ongoingCall.get();
1469 final boolean ongoingVideoTranscoding = mOngoingVideoTranscoding.get();
1470 final int id;
1471 if (force
1472 || mForceDuringOnCreate.get()
1473 || ongoingVideoTranscoding
1474 || ongoing != null
1475 || (appSettings.isKeepForegroundService() && hasEnabledAccounts())) {
1476 final Notification notification;
1477 if (ongoing != null) {
1478 notification = this.mNotificationService.getOngoingCallNotification(ongoing);
1479 id = NotificationService.ONGOING_CALL_NOTIFICATION_ID;
1480 startForegroundOrCatch(id, notification, true);
1481 } else if (ongoingVideoTranscoding) {
1482 notification = this.mNotificationService.getIndeterminateVideoTranscoding();
1483 id = NotificationService.ONGOING_VIDEO_TRANSCODING_NOTIFICATION_ID;
1484 startForegroundOrCatch(id, notification, false);
1485 } else {
1486 notification = this.mNotificationService.createForegroundNotification();
1487 id = NotificationService.FOREGROUND_NOTIFICATION_ID;
1488 startForegroundOrCatch(id, notification, false);
1489 }
1490 mNotificationService.notify(id, notification);
1491 status = true;
1492 } else {
1493 id = 0;
1494 stopForeground(true);
1495 status = false;
1496 }
1497
1498 for (final int toBeRemoved :
1499 Collections2.filter(
1500 Arrays.asList(
1501 NotificationService.FOREGROUND_NOTIFICATION_ID,
1502 NotificationService.ONGOING_CALL_NOTIFICATION_ID,
1503 NotificationService.ONGOING_VIDEO_TRANSCODING_NOTIFICATION_ID),
1504 i -> i != id)) {
1505 mNotificationService.cancel(toBeRemoved);
1506 }
1507 Log.d(
1508 Config.LOGTAG,
1509 "ForegroundService: " + (status ? "on" : "off") + ", notification: " + id);
1510 }
1511
1512 private void startForegroundOrCatch(
1513 final int id, final Notification notification, final boolean requireMicrophone) {
1514 try {
1515 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
1516 final int foregroundServiceType;
1517 if (requireMicrophone
1518 && ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
1519 == PackageManager.PERMISSION_GRANTED) {
1520 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE;
1521 Log.d(Config.LOGTAG, "defaulting to microphone foreground service type");
1522 } else if (getSystemService(PowerManager.class)
1523 .isIgnoringBatteryOptimizations(getPackageName())) {
1524 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED;
1525 } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
1526 == PackageManager.PERMISSION_GRANTED) {
1527 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE;
1528 } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
1529 == PackageManager.PERMISSION_GRANTED) {
1530 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA;
1531 } else {
1532 foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE;
1533 Log.w(Config.LOGTAG, "falling back to special use foreground service type");
1534 }
1535 startForeground(id, notification, foregroundServiceType);
1536 } else {
1537 startForeground(id, notification);
1538 }
1539 } catch (final IllegalStateException | SecurityException e) {
1540 Log.e(Config.LOGTAG, "Could not start foreground service", e);
1541 }
1542 }
1543
1544 public boolean foregroundNotificationNeedsUpdatingWhenErrorStateChanges() {
1545 return !mOngoingVideoTranscoding.get()
1546 && ongoingCall.get() == null
1547 && appSettings.isKeepForegroundService()
1548 && hasEnabledAccounts();
1549 }
1550
1551 @Override
1552 public void onTaskRemoved(final Intent rootIntent) {
1553 super.onTaskRemoved(rootIntent);
1554 if ((appSettings.isKeepForegroundService() && hasEnabledAccounts())
1555 || mOngoingVideoTranscoding.get()
1556 || ongoingCall.get() != null) {
1557 Log.d(Config.LOGTAG, "ignoring onTaskRemoved because foreground service is activated");
1558 } else {
1559 this.logoutAndSave(false);
1560 }
1561 }
1562
1563 private void logoutAndSave(boolean stop) {
1564 int activeAccounts = 0;
1565 for (final Account account : accounts) {
1566 if (account.isConnectionEnabled()) {
1567 account.getXmppConnection().getManager(RosterManager.class).writeToDatabase();
1568 activeAccounts++;
1569 }
1570 if (account.getXmppConnection() != null) {
1571 new Thread(() -> disconnect(account, false)).start();
1572 }
1573 }
1574 if (stop || activeAccounts == 0) {
1575 Log.d(Config.LOGTAG, "good bye");
1576 stopSelf();
1577 }
1578 }
1579
1580 private void schedulePostConnectivityChange() {
1581 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1582 if (alarmManager == null) {
1583 return;
1584 }
1585 final long triggerAtMillis =
1586 SystemClock.elapsedRealtime()
1587 + (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL * 1000);
1588 final Intent intent = new Intent(this, SystemEventReceiver.class);
1589 intent.setAction(ACTION_POST_CONNECTIVITY_CHANGE);
1590 try {
1591 final PendingIntent pendingIntent =
1592 PendingIntent.getBroadcast(
1593 this,
1594 1,
1595 intent,
1596 s()
1597 ? PendingIntent.FLAG_IMMUTABLE
1598 | PendingIntent.FLAG_UPDATE_CURRENT
1599 : PendingIntent.FLAG_UPDATE_CURRENT);
1600 alarmManager.setAndAllowWhileIdle(
1601 AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1602 } catch (RuntimeException e) {
1603 Log.e(Config.LOGTAG, "unable to schedule alarm for post connectivity change", e);
1604 }
1605 }
1606
1607 public void scheduleWakeUpCall(final int seconds, final int requestCode) {
1608 scheduleWakeUpCall((seconds < 0 ? 1 : seconds + 1) * 1000L, requestCode);
1609 }
1610
1611 public void scheduleWakeUpCall(final long milliSeconds, final int requestCode) {
1612 final var timeToWake = SystemClock.elapsedRealtime() + milliSeconds;
1613 final var alarmManager = getSystemService(AlarmManager.class);
1614 final Intent intent = new Intent(this, SystemEventReceiver.class);
1615 intent.setAction(ACTION_PING);
1616 try {
1617 final PendingIntent pendingIntent =
1618 PendingIntent.getBroadcast(
1619 this, requestCode, intent, PendingIntent.FLAG_IMMUTABLE);
1620 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1621 } catch (final RuntimeException e) {
1622 Log.e(Config.LOGTAG, "unable to schedule alarm for ping", e);
1623 }
1624 }
1625
1626 private void scheduleNextIdlePing() {
1627 final long timeToWake = SystemClock.elapsedRealtime() + (Config.IDLE_PING_INTERVAL * 1000);
1628 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1629 if (alarmManager == null) {
1630 return;
1631 }
1632 final Intent intent = new Intent(this, SystemEventReceiver.class);
1633 intent.setAction(ACTION_IDLE_PING);
1634 try {
1635 final PendingIntent pendingIntent =
1636 PendingIntent.getBroadcast(
1637 this,
1638 0,
1639 intent,
1640 s()
1641 ? PendingIntent.FLAG_IMMUTABLE
1642 | PendingIntent.FLAG_UPDATE_CURRENT
1643 : PendingIntent.FLAG_UPDATE_CURRENT);
1644 alarmManager.setAndAllowWhileIdle(
1645 AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1646 } catch (RuntimeException e) {
1647 Log.d(Config.LOGTAG, "unable to schedule alarm for idle ping", e);
1648 }
1649 }
1650
1651 public XmppConnection createConnection(final Account account) {
1652 final XmppConnection connection = new XmppConnection(account, this);
1653 connection.setOnJinglePacketReceivedListener((mJingleConnectionManager::deliverPacket));
1654 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
1655 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
1656 return connection;
1657 }
1658
1659 public void sendChatState(Conversation conversation) {
1660 if (sendChatStates()) {
1661 final var packet = mMessageGenerator.generateChatState(conversation);
1662 sendMessagePacket(conversation.getAccount(), packet);
1663 }
1664 }
1665
1666 private void sendFileMessage(
1667 final Message message, final boolean delay, final boolean forceP2P) {
1668 final var account = message.getConversation().getAccount();
1669 Log.d(
1670 Config.LOGTAG,
1671 account.getJid().asBareJid() + ": send file message. forceP2P=" + forceP2P);
1672 if ((account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1673 || message.getConversation().getMode() == Conversation.MODE_MULTI)
1674 && !forceP2P) {
1675 mHttpConnectionManager.createNewUploadConnection(message, delay);
1676 } else {
1677 mJingleConnectionManager.startJingleFileTransfer(message);
1678 }
1679 }
1680
1681 public void sendMessage(final Message message) {
1682 sendMessage(message, false, false, false);
1683 }
1684
1685 private void sendMessage(
1686 final Message message,
1687 final boolean resend,
1688 final boolean delay,
1689 final boolean forceP2P) {
1690 final Account account = message.getConversation().getAccount();
1691 if (account.setShowErrorNotification(true)) {
1692 databaseBackend.updateAccount(account);
1693 mNotificationService.updateErrorNotification();
1694 }
1695 final Conversation conversation = (Conversation) message.getConversation();
1696 account.deactivateGracePeriod();
1697
1698 if (QuickConversationsService.isQuicksy()
1699 && conversation.getMode() == Conversation.MODE_SINGLE) {
1700 final Contact contact = conversation.getContact();
1701 if (!contact.showInRoster() && contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1702 Log.d(
1703 Config.LOGTAG,
1704 account.getJid().asBareJid()
1705 + ": adding "
1706 + contact.getJid()
1707 + " on sending message");
1708 createContact(contact);
1709 }
1710 }
1711
1712 im.conversations.android.xmpp.model.stanza.Message packet = null;
1713 final boolean addToConversation = !message.edited();
1714 boolean saveInDb = addToConversation;
1715 message.setStatus(Message.STATUS_WAITING);
1716
1717 if (message.getEncryption() != Message.ENCRYPTION_NONE
1718 && conversation.getMode() == Conversation.MODE_MULTI
1719 && conversation.isPrivateAndNonAnonymous()) {
1720 if (conversation.setAttribute(
1721 Conversation.ATTRIBUTE_FORMERLY_PRIVATE_NON_ANONYMOUS, true)) {
1722 databaseBackend.updateConversation(conversation);
1723 }
1724 }
1725
1726 final boolean inProgressJoin = isJoinInProgress(conversation);
1727
1728 if (account.isOnlineAndConnected() && !inProgressJoin) {
1729 switch (message.getEncryption()) {
1730 case Message.ENCRYPTION_NONE:
1731 if (message.needsUploading()) {
1732 if (account.httpUploadAvailable(
1733 fileBackend.getFile(message, false).getSize())
1734 || conversation.getMode() == Conversation.MODE_MULTI
1735 || message.fixCounterpart()) {
1736 this.sendFileMessage(message, delay, forceP2P);
1737 } else {
1738 break;
1739 }
1740 } else {
1741 packet = mMessageGenerator.generateChat(message);
1742 }
1743 break;
1744 case Message.ENCRYPTION_PGP:
1745 case Message.ENCRYPTION_DECRYPTED:
1746 if (message.needsUploading()) {
1747 if (account.httpUploadAvailable(
1748 fileBackend.getFile(message, false).getSize())
1749 || conversation.getMode() == Conversation.MODE_MULTI
1750 || message.fixCounterpart()) {
1751 this.sendFileMessage(message, delay, forceP2P);
1752 } else {
1753 break;
1754 }
1755 } else {
1756 packet = mMessageGenerator.generatePgpChat(message);
1757 }
1758 break;
1759 case Message.ENCRYPTION_AXOLOTL:
1760 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1761 if (message.needsUploading()) {
1762 if (account.httpUploadAvailable(
1763 fileBackend.getFile(message, false).getSize())
1764 || conversation.getMode() == Conversation.MODE_MULTI
1765 || message.fixCounterpart()) {
1766 this.sendFileMessage(message, delay, forceP2P);
1767 } else {
1768 break;
1769 }
1770 } else {
1771 XmppAxolotlMessage axolotlMessage =
1772 account.getAxolotlService().fetchAxolotlMessageFromCache(message);
1773 if (axolotlMessage == null) {
1774 account.getAxolotlService().preparePayloadMessage(message, delay);
1775 } else {
1776 packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
1777 }
1778 }
1779 break;
1780 }
1781 if (packet != null) {
1782 if (account.getXmppConnection().getFeatures().sm()
1783 || (conversation.getMode() == Conversation.MODE_MULTI
1784 && message.getCounterpart().isBareJid())) {
1785 message.setStatus(Message.STATUS_UNSEND);
1786 } else {
1787 message.setStatus(Message.STATUS_SEND);
1788 }
1789 }
1790 } else {
1791 switch (message.getEncryption()) {
1792 case Message.ENCRYPTION_DECRYPTED:
1793 if (!message.needsUploading()) {
1794 String pgpBody = message.getEncryptedBody();
1795 String decryptedBody = message.getBody();
1796 message.setBody(pgpBody); // TODO might throw NPE
1797 message.setEncryption(Message.ENCRYPTION_PGP);
1798 if (message.edited()) {
1799 message.setBody(decryptedBody);
1800 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1801 if (!databaseBackend.updateMessage(message, message.getEditedId())) {
1802 Log.e(Config.LOGTAG, "error updated message in DB after edit");
1803 }
1804 updateConversationUi();
1805 return;
1806 } else {
1807 databaseBackend.createMessage(message);
1808 saveInDb = false;
1809 message.setBody(decryptedBody);
1810 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1811 }
1812 }
1813 break;
1814 case Message.ENCRYPTION_AXOLOTL:
1815 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1816 break;
1817 }
1818 }
1819
1820 boolean mucMessage =
1821 conversation.getMode() == Conversation.MODE_MULTI && !message.isPrivateMessage();
1822 if (mucMessage) {
1823 message.setCounterpart(conversation.getMucOptions().getSelf().getFullJid());
1824 }
1825
1826 if (resend) {
1827 if (packet != null && addToConversation) {
1828 if (account.getXmppConnection().getFeatures().sm() || mucMessage) {
1829 markMessage(message, Message.STATUS_UNSEND);
1830 } else {
1831 markMessage(message, Message.STATUS_SEND);
1832 }
1833 }
1834 } else {
1835 if (addToConversation) {
1836 conversation.add(message);
1837 }
1838 if (saveInDb) {
1839 databaseBackend.createMessage(message);
1840 } else if (message.edited()) {
1841 if (!databaseBackend.updateMessage(message, message.getEditedId())) {
1842 Log.e(Config.LOGTAG, "error updated message in DB after edit");
1843 }
1844 }
1845 updateConversationUi();
1846 }
1847 if (packet != null) {
1848 if (delay) {
1849 mMessageGenerator.addDelay(packet, message.getTimeSent());
1850 }
1851 if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
1852 if (this.sendChatStates()) {
1853 packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
1854 }
1855 }
1856 sendMessagePacket(account, packet);
1857 }
1858 }
1859
1860 private boolean isJoinInProgress(final Conversation conversation) {
1861 final Account account = conversation.getAccount();
1862 synchronized (account.inProgressConferenceJoins) {
1863 if (conversation.getMode() == Conversational.MODE_MULTI) {
1864 final boolean inProgress = account.inProgressConferenceJoins.contains(conversation);
1865 final boolean pending = account.pendingConferenceJoins.contains(conversation);
1866 final boolean inProgressJoin = inProgress || pending;
1867 if (inProgressJoin) {
1868 Log.d(
1869 Config.LOGTAG,
1870 account.getJid().asBareJid()
1871 + ": holding back message to group. inProgress="
1872 + inProgress
1873 + ", pending="
1874 + pending);
1875 }
1876 return inProgressJoin;
1877 } else {
1878 return false;
1879 }
1880 }
1881 }
1882
1883 public void sendUnsentMessages(final Conversation conversation) {
1884 conversation.findWaitingMessages(message -> resendMessage(message, true));
1885 }
1886
1887 public void resendMessage(final Message message, final boolean delay) {
1888 sendMessage(message, true, delay, false);
1889 }
1890
1891 public void requestEasyOnboardingInvite(
1892 final Account account, final EasyOnboardingInvite.OnInviteRequested callback) {
1893 final XmppConnection connection = account.getXmppConnection();
1894 final Jid jid =
1895 connection == null
1896 ? null
1897 : connection.getJidForCommand(Namespace.EASY_ONBOARDING_INVITE);
1898 if (jid == null) {
1899 callback.inviteRequestFailed(
1900 getString(R.string.server_does_not_support_easy_onboarding_invites));
1901 return;
1902 }
1903 final Iq request = new Iq(Iq.Type.SET);
1904 request.setTo(jid);
1905 final Element command = request.addChild("command", Namespace.COMMANDS);
1906 command.setAttribute("node", Namespace.EASY_ONBOARDING_INVITE);
1907 command.setAttribute("action", "execute");
1908 sendIqPacket(
1909 account,
1910 request,
1911 (response) -> {
1912 if (response.getType() == Iq.Type.RESULT) {
1913 final Element resultCommand =
1914 response.findChild("command", Namespace.COMMANDS);
1915 final Element x =
1916 resultCommand == null
1917 ? null
1918 : resultCommand.findChild("x", Namespace.DATA);
1919 if (x != null) {
1920 final Data data = Data.parse(x);
1921 final String uri = data.getValue("uri");
1922 final String landingUrl = data.getValue("landing-url");
1923 if (uri != null) {
1924 final EasyOnboardingInvite invite =
1925 new EasyOnboardingInvite(
1926 jid.getDomain().toString(), uri, landingUrl);
1927 callback.inviteRequested(invite);
1928 return;
1929 }
1930 }
1931 callback.inviteRequestFailed(getString(R.string.unable_to_parse_invite));
1932 Log.d(Config.LOGTAG, response.toString());
1933 } else if (response.getType() == Iq.Type.ERROR) {
1934 callback.inviteRequestFailed(IqParser.errorMessage(response));
1935 } else {
1936 callback.inviteRequestFailed(getString(R.string.remote_server_timeout));
1937 }
1938 });
1939 }
1940
1941 public void markReadUpToStanzaId(final Conversation conversation, final String stanzaId) {
1942 final Message message = conversation.findMessageWithServerMsgId(stanzaId);
1943 if (message == null) { // do we want to check if isRead?
1944 return;
1945 }
1946 markReadUpTo(conversation, message);
1947 }
1948
1949 public void markReadUpTo(final Conversation conversation, final Message message) {
1950 final boolean isDismissNotification = isDismissNotification(message);
1951 final var uuid = message.getUuid();
1952 Log.d(
1953 Config.LOGTAG,
1954 conversation.getAccount().getJid().asBareJid()
1955 + ": mark "
1956 + conversation.getJid().asBareJid()
1957 + " as read up to "
1958 + uuid);
1959 markRead(conversation, uuid, isDismissNotification);
1960 }
1961
1962 private static boolean isDismissNotification(final Message message) {
1963 Message next = message.next();
1964 while (next != null) {
1965 if (message.getStatus() == Message.STATUS_RECEIVED) {
1966 return false;
1967 }
1968 next = next.next();
1969 }
1970 return true;
1971 }
1972
1973 public void processModifiedBookmark(final Bookmark bookmark, final boolean pep) {
1974 final Account account = bookmark.getAccount();
1975 Conversation conversation = find(bookmark);
1976 if (conversation != null) {
1977 if (conversation.getMode() != Conversation.MODE_MULTI) {
1978 return;
1979 }
1980 bookmark.setConversation(conversation);
1981 if (pep && !bookmark.autojoin()) {
1982 Log.d(
1983 Config.LOGTAG,
1984 account.getJid().asBareJid()
1985 + ": archiving conference ("
1986 + conversation.getJid()
1987 + ") after receiving pep");
1988 archiveConversation(conversation, false);
1989 } else {
1990 final MucOptions mucOptions = conversation.getMucOptions();
1991 if (mucOptions.getError() == MucOptions.Error.NICK_IN_USE) {
1992 final String current = mucOptions.getActualNick();
1993 final String proposed = mucOptions.getProposedNickPure();
1994 if (current != null && !current.equals(proposed)) {
1995 Log.d(
1996 Config.LOGTAG,
1997 account.getJid().asBareJid()
1998 + ": proposed nick changed after bookmark push "
1999 + current
2000 + "->"
2001 + proposed);
2002 joinMuc(conversation);
2003 }
2004 } else {
2005 checkMucRequiresRename(conversation);
2006 }
2007 }
2008 } else if (bookmark.autojoin()) {
2009 conversation =
2010 findOrCreateConversation(account, bookmark.getFullJid(), true, true, false);
2011 bookmark.setConversation(conversation);
2012 }
2013 }
2014
2015 public void processModifiedBookmark(final Bookmark bookmark) {
2016 processModifiedBookmark(bookmark, true);
2017 }
2018
2019 public void ensureBookmarkIsAutoJoin(final Conversation conversation) {
2020 final var account = conversation.getAccount();
2021 final var existingBookmark = conversation.getBookmark();
2022 if (existingBookmark == null) {
2023 final var bookmark = new Bookmark(account, conversation.getJid().asBareJid());
2024 bookmark.setAutojoin(true);
2025 createBookmark(account, bookmark);
2026 } else {
2027 if (existingBookmark.autojoin()) {
2028 return;
2029 }
2030 existingBookmark.setAutojoin(true);
2031 createBookmark(account, existingBookmark);
2032 }
2033 }
2034
2035 public void createBookmark(final Account account, final Bookmark bookmark) {
2036 account.putBookmark(bookmark);
2037 final XmppConnection connection = account.getXmppConnection();
2038 final ListenableFuture<Void> future;
2039 if (connection.getManager(BookmarkManager.class).hasFeature()) {
2040 future = connection.getManager(BookmarkManager.class).publish(bookmark);
2041 } else if (connection.getManager(LegacyBookmarkManager.class).hasConversion()) {
2042 future =
2043 connection
2044 .getManager(LegacyBookmarkManager.class)
2045 .publish(account.getBookmarks());
2046 } else {
2047 future =
2048 connection
2049 .getManager(PrivateStorageManager.class)
2050 .publishBookmarks(account.getBookmarks());
2051 }
2052 Futures.addCallback(
2053 future,
2054 new FutureCallback<Void>() {
2055 @Override
2056 public void onSuccess(Void result) {
2057 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": created bookmark");
2058 }
2059
2060 @Override
2061 public void onFailure(@NonNull Throwable t) {
2062 Log.d(
2063 Config.LOGTAG,
2064 account.getJid().asBareJid() + ": could not create bookmark",
2065 t);
2066 }
2067 },
2068 MoreExecutors.directExecutor());
2069 }
2070
2071 public void deleteBookmark(final Account account, final Bookmark bookmark) {
2072 account.removeBookmark(bookmark);
2073 final XmppConnection connection = account.getXmppConnection();
2074 final ListenableFuture<Void> future;
2075 if (connection.getManager(BookmarkManager.class).hasFeature()) {
2076 future =
2077 connection
2078 .getManager(BookmarkManager.class)
2079 .retract(bookmark.getJid().asBareJid());
2080 } else if (connection.getManager(LegacyBookmarkManager.class).hasConversion()) {
2081 future =
2082 connection
2083 .getManager(LegacyBookmarkManager.class)
2084 .publish(account.getBookmarks());
2085 } else {
2086 future =
2087 connection
2088 .getManager(PrivateStorageManager.class)
2089 .publishBookmarks(account.getBookmarks());
2090 }
2091 Futures.addCallback(
2092 future,
2093 new FutureCallback<Void>() {
2094 @Override
2095 public void onSuccess(Void result) {
2096 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": deleted bookmark");
2097 }
2098
2099 @Override
2100 public void onFailure(@NonNull Throwable t) {
2101 Log.d(
2102 Config.LOGTAG,
2103 account.getJid().asBareJid() + ": could not delete bookmark",
2104 t);
2105 }
2106 },
2107 MoreExecutors.directExecutor());
2108 }
2109
2110 private void pushNodeAndEnforcePublishOptions(
2111 final Account account,
2112 final String node,
2113 final Element element,
2114 final String id,
2115 final Bundle options) {
2116 pushNodeAndEnforcePublishOptions(account, node, element, id, options, true);
2117 }
2118
2119 private void pushNodeAndEnforcePublishOptions(
2120 final Account account,
2121 final String node,
2122 final Element element,
2123 final String id,
2124 final Bundle options,
2125 final boolean retry) {
2126 final Iq packet = mIqGenerator.publishElement(node, element, id, options);
2127 sendIqPacket(
2128 account,
2129 packet,
2130 (response) -> {
2131 if (response.getType() == Iq.Type.RESULT) {
2132 return;
2133 }
2134 if (retry && PublishOptions.preconditionNotMet(response)) {
2135 pushNodeConfiguration(
2136 account,
2137 node,
2138 options,
2139 new OnConfigurationPushed() {
2140 @Override
2141 public void onPushSucceeded() {
2142 pushNodeAndEnforcePublishOptions(
2143 account, node, element, id, options, false);
2144 }
2145
2146 @Override
2147 public void onPushFailed() {
2148 Log.d(
2149 Config.LOGTAG,
2150 account.getJid().asBareJid()
2151 + ": unable to push node configuration ("
2152 + node
2153 + ")");
2154 }
2155 });
2156 } else {
2157 Log.d(
2158 Config.LOGTAG,
2159 account.getJid().asBareJid()
2160 + ": error publishing "
2161 + node
2162 + " (retry="
2163 + retry
2164 + ") "
2165 + response);
2166 }
2167 });
2168 }
2169
2170 private void restoreFromDatabase() {
2171 synchronized (this.conversations) {
2172 final Map<String, Account> accountLookupTable =
2173 ImmutableMap.copyOf(Maps.uniqueIndex(this.accounts, Account::getUuid));
2174 Log.d(Config.LOGTAG, "restoring conversations...");
2175 final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
2176 this.conversations.addAll(
2177 databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
2178 for (Iterator<Conversation> iterator = conversations.listIterator();
2179 iterator.hasNext(); ) {
2180 Conversation conversation = iterator.next();
2181 Account account = accountLookupTable.get(conversation.getAccountUuid());
2182 if (account != null) {
2183 conversation.setAccount(account);
2184 } else {
2185 Log.e(
2186 Config.LOGTAG,
2187 "unable to restore Conversations with " + conversation.getJid());
2188 iterator.remove();
2189 }
2190 }
2191 long diffConversationsRestore =
2192 SystemClock.elapsedRealtime() - startTimeConversationsRestore;
2193 Log.d(
2194 Config.LOGTAG,
2195 "finished restoring conversations in " + diffConversationsRestore + "ms");
2196 Runnable runnable =
2197 () -> {
2198 if (DatabaseBackend.requiresMessageIndexRebuild()) {
2199 DatabaseBackend.getInstance(this).rebuildMessagesIndex();
2200 }
2201 final long deletionDate = getAutomaticMessageDeletionDate();
2202 mLastExpiryRun.set(SystemClock.elapsedRealtime());
2203 if (deletionDate > 0) {
2204 Log.d(
2205 Config.LOGTAG,
2206 "deleting messages that are older than "
2207 + AbstractGenerator.getTimestamp(deletionDate));
2208 databaseBackend.expireOldMessages(deletionDate);
2209 }
2210 Log.d(Config.LOGTAG, "restoring roster...");
2211 for (final Account account : accounts) {
2212 account.getXmppConnection().getManager(RosterManager.class).restore();
2213 }
2214 getBitmapCache().evictAll();
2215 loadPhoneContacts();
2216 Log.d(Config.LOGTAG, "restoring messages...");
2217 final long startMessageRestore = SystemClock.elapsedRealtime();
2218 final Conversation quickLoad = QuickLoader.get(this.conversations);
2219 if (quickLoad != null) {
2220 restoreMessages(quickLoad);
2221 updateConversationUi();
2222 final long diffMessageRestore =
2223 SystemClock.elapsedRealtime() - startMessageRestore;
2224 Log.d(
2225 Config.LOGTAG,
2226 "quickly restored "
2227 + quickLoad.getName()
2228 + " after "
2229 + diffMessageRestore
2230 + "ms");
2231 }
2232 for (Conversation conversation : this.conversations) {
2233 if (quickLoad != conversation) {
2234 restoreMessages(conversation);
2235 }
2236 }
2237 mNotificationService.finishBacklog();
2238 restoredFromDatabaseLatch.countDown();
2239 final long diffMessageRestore =
2240 SystemClock.elapsedRealtime() - startMessageRestore;
2241 Log.d(
2242 Config.LOGTAG,
2243 "finished restoring messages in " + diffMessageRestore + "ms");
2244 updateConversationUi();
2245 };
2246 mDatabaseReaderExecutor.execute(
2247 runnable); // will contain one write command (expiry) but that's fine
2248 }
2249 }
2250
2251 private void restoreMessages(Conversation conversation) {
2252 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
2253 conversation.findUnsentTextMessages(
2254 message -> markMessage(message, Message.STATUS_WAITING));
2255 conversation.findUnreadMessagesAndCalls(mNotificationService::pushFromBacklog);
2256 }
2257
2258 public void loadPhoneContacts() {
2259 mContactMergerExecutor.execute(
2260 () -> {
2261 final Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
2262 Log.d(Config.LOGTAG, "start merging phone contacts with roster");
2263 // TODO if we do this merge this only on enabled accounts we need to trigger
2264 // this upon enable
2265 for (final Account account : accounts) {
2266 final var remaining =
2267 new ArrayList<>(
2268 account.getRoster()
2269 .getWithSystemAccounts(JabberIdContact.class));
2270 for (final JabberIdContact jidContact : contacts.values()) {
2271 final Contact contact =
2272 account.getRoster().getContact(jidContact.getJid());
2273 boolean needsCacheClean = contact.setPhoneContact(jidContact);
2274 if (needsCacheClean) {
2275 getAvatarService().clear(contact);
2276 }
2277 remaining.remove(contact);
2278 }
2279 for (final Contact contact : remaining) {
2280 boolean needsCacheClean =
2281 contact.unsetPhoneContact(JabberIdContact.class);
2282 if (needsCacheClean) {
2283 getAvatarService().clear(contact);
2284 }
2285 }
2286 }
2287 Log.d(Config.LOGTAG, "finished merging phone contacts");
2288 mShortcutService.refresh(
2289 mInitialAddressbookSyncCompleted.compareAndSet(false, true));
2290 updateRosterUi();
2291 mQuickConversationsService.considerSync();
2292 });
2293 }
2294
2295 public List<Conversation> getConversations() {
2296 return this.conversations;
2297 }
2298
2299 private void markFileDeleted(final File file) {
2300 synchronized (FILENAMES_TO_IGNORE_DELETION) {
2301 if (FILENAMES_TO_IGNORE_DELETION.remove(file.getAbsolutePath())) {
2302 Log.d(Config.LOGTAG, "ignored deletion of " + file.getAbsolutePath());
2303 return;
2304 }
2305 }
2306 final boolean isInternalFile = fileBackend.isInternalFile(file);
2307 final List<String> uuids = databaseBackend.markFileAsDeleted(file, isInternalFile);
2308 Log.d(
2309 Config.LOGTAG,
2310 "deleted file "
2311 + file.getAbsolutePath()
2312 + " internal="
2313 + isInternalFile
2314 + ", database hits="
2315 + uuids.size());
2316 markUuidsAsDeletedFiles(uuids);
2317 }
2318
2319 private void markUuidsAsDeletedFiles(List<String> uuids) {
2320 boolean deleted = false;
2321 for (Conversation conversation : getConversations()) {
2322 deleted |= conversation.markAsDeleted(uuids);
2323 }
2324 for (final String uuid : uuids) {
2325 evictPreview(uuid);
2326 }
2327 if (deleted) {
2328 updateConversationUi();
2329 }
2330 }
2331
2332 private void markChangedFiles(List<DatabaseBackend.FilePathInfo> infos) {
2333 boolean changed = false;
2334 for (Conversation conversation : getConversations()) {
2335 changed |= conversation.markAsChanged(infos);
2336 }
2337 if (changed) {
2338 updateConversationUi();
2339 }
2340 }
2341
2342 public void populateWithOrderedConversations(final List<Conversation> list) {
2343 populateWithOrderedConversations(list, true, true);
2344 }
2345
2346 public void populateWithOrderedConversations(
2347 final List<Conversation> list, final boolean includeNoFileUpload) {
2348 populateWithOrderedConversations(list, includeNoFileUpload, true);
2349 }
2350
2351 public void populateWithOrderedConversations(
2352 final List<Conversation> list, final boolean includeNoFileUpload, final boolean sort) {
2353 final List<String> orderedUuids;
2354 if (sort) {
2355 orderedUuids = null;
2356 } else {
2357 orderedUuids = new ArrayList<>();
2358 for (Conversation conversation : list) {
2359 orderedUuids.add(conversation.getUuid());
2360 }
2361 }
2362 list.clear();
2363 if (includeNoFileUpload) {
2364 list.addAll(getConversations());
2365 } else {
2366 for (Conversation conversation : getConversations()) {
2367 if (conversation.getMode() == Conversation.MODE_SINGLE
2368 || (conversation.getAccount().httpUploadAvailable()
2369 && conversation.getMucOptions().participating())) {
2370 list.add(conversation);
2371 }
2372 }
2373 }
2374 try {
2375 if (orderedUuids != null) {
2376 Collections.sort(
2377 list,
2378 (a, b) -> {
2379 final int indexA = orderedUuids.indexOf(a.getUuid());
2380 final int indexB = orderedUuids.indexOf(b.getUuid());
2381 if (indexA == -1 || indexB == -1 || indexA == indexB) {
2382 return a.compareTo(b);
2383 }
2384 return indexA - indexB;
2385 });
2386 } else {
2387 Collections.sort(list);
2388 }
2389 } catch (IllegalArgumentException e) {
2390 // ignore
2391 }
2392 }
2393
2394 public void loadMoreMessages(
2395 final Conversation conversation,
2396 final long timestamp,
2397 final OnMoreMessagesLoaded callback) {
2398 if (XmppConnectionService.this
2399 .getMessageArchiveService()
2400 .queryInProgress(conversation, callback)) {
2401 return;
2402 } else if (timestamp == 0) {
2403 return;
2404 }
2405 Log.d(
2406 Config.LOGTAG,
2407 "load more messages for "
2408 + conversation.getName()
2409 + " prior to "
2410 + MessageGenerator.getTimestamp(timestamp));
2411 final Runnable runnable =
2412 () -> {
2413 final Account account = conversation.getAccount();
2414 List<Message> messages =
2415 databaseBackend.getMessages(conversation, 50, timestamp);
2416 if (messages.size() > 0) {
2417 conversation.addAll(0, messages);
2418 callback.onMoreMessagesLoaded(messages.size(), conversation);
2419 } else if (conversation.hasMessagesLeftOnServer()
2420 && account.isOnlineAndConnected()
2421 && conversation.getLastClearHistory().getTimestamp() == 0) {
2422 final boolean mamAvailable;
2423 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2424 mamAvailable =
2425 account.getXmppConnection().getFeatures().mam()
2426 && !conversation.getContact().isBlocked();
2427 } else {
2428 mamAvailable = conversation.getMucOptions().mamSupport();
2429 }
2430 if (mamAvailable) {
2431 MessageArchiveService.Query query =
2432 getMessageArchiveService()
2433 .query(
2434 conversation,
2435 new MamReference(0),
2436 timestamp,
2437 false);
2438 if (query != null) {
2439 query.setCallback(callback);
2440 callback.informUser(R.string.fetching_history_from_server);
2441 } else {
2442 callback.informUser(R.string.not_fetching_history_retention_period);
2443 }
2444 }
2445 }
2446 };
2447 mDatabaseReaderExecutor.execute(runnable);
2448 }
2449
2450 public List<Account> getAccounts() {
2451 return this.accounts;
2452 }
2453
2454 /**
2455 * This will find all conferences with the contact as member and also the conference that is the
2456 * contact (that 'fake' contact is used to store the avatar)
2457 */
2458 public List<Conversation> findAllConferencesWith(Contact contact) {
2459 final ArrayList<Conversation> results = new ArrayList<>();
2460 for (final Conversation c : conversations) {
2461 if (c.getMode() != Conversation.MODE_MULTI) {
2462 continue;
2463 }
2464 final MucOptions mucOptions = c.getMucOptions();
2465 if (c.getJid().asBareJid().equals(contact.getJid().asBareJid())
2466 || (mucOptions != null && mucOptions.isContactInRoom(contact))) {
2467 results.add(c);
2468 }
2469 }
2470 return results;
2471 }
2472
2473 public Conversation find(final Contact contact) {
2474 for (final Conversation conversation : this.conversations) {
2475 if (conversation.getContact() == contact) {
2476 return conversation;
2477 }
2478 }
2479 return null;
2480 }
2481
2482 public Conversation find(
2483 final Iterable<Conversation> haystack, final Account account, final Jid jid) {
2484 if (jid == null) {
2485 return null;
2486 }
2487 for (final Conversation conversation : haystack) {
2488 if ((account == null || conversation.getAccount() == account)
2489 && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
2490 return conversation;
2491 }
2492 }
2493 return null;
2494 }
2495
2496 public boolean isConversationsListEmpty(final Conversation ignore) {
2497 synchronized (this.conversations) {
2498 final int size = this.conversations.size();
2499 return size == 0 || size == 1 && this.conversations.get(0) == ignore;
2500 }
2501 }
2502
2503 public boolean isConversationStillOpen(final Conversation conversation) {
2504 synchronized (this.conversations) {
2505 for (Conversation current : this.conversations) {
2506 if (current == conversation) {
2507 return true;
2508 }
2509 }
2510 }
2511 return false;
2512 }
2513
2514 public Conversation findOrCreateConversation(
2515 Account account, Jid jid, boolean muc, final boolean async) {
2516 return this.findOrCreateConversation(account, jid, muc, false, async);
2517 }
2518
2519 public Conversation findOrCreateConversation(
2520 final Account account,
2521 final Jid jid,
2522 final boolean muc,
2523 final boolean joinAfterCreate,
2524 final boolean async) {
2525 return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
2526 }
2527
2528 public Conversation findOrCreateConversation(
2529 final Account account,
2530 final Jid jid,
2531 final boolean muc,
2532 final boolean joinAfterCreate,
2533 final MessageArchiveService.Query query,
2534 final boolean async) {
2535 synchronized (this.conversations) {
2536 final var cached = find(account, jid);
2537 if (cached != null) {
2538 return cached;
2539 }
2540 final var existing = databaseBackend.findConversation(account, jid);
2541 final Conversation conversation;
2542 final boolean loadMessagesFromDb;
2543 if (existing != null) {
2544 conversation = existing;
2545 loadMessagesFromDb = restoreFromArchive(conversation, jid, muc);
2546 } else {
2547 String conversationName;
2548 final Contact contact = account.getRoster().getContact(jid);
2549 if (contact != null) {
2550 conversationName = contact.getDisplayName();
2551 } else {
2552 conversationName = jid.getLocal();
2553 }
2554 if (muc) {
2555 conversation =
2556 new Conversation(
2557 conversationName, account, jid, Conversation.MODE_MULTI);
2558 } else {
2559 conversation =
2560 new Conversation(
2561 conversationName,
2562 account,
2563 jid.asBareJid(),
2564 Conversation.MODE_SINGLE);
2565 }
2566 this.databaseBackend.createConversation(conversation);
2567 loadMessagesFromDb = false;
2568 }
2569 if (async) {
2570 mDatabaseReaderExecutor.execute(
2571 () ->
2572 postProcessConversation(
2573 conversation, loadMessagesFromDb, joinAfterCreate, query));
2574 } else {
2575 postProcessConversation(conversation, loadMessagesFromDb, joinAfterCreate, query);
2576 }
2577 this.conversations.add(conversation);
2578 updateConversationUi();
2579 return conversation;
2580 }
2581 }
2582
2583 public Conversation findConversationByUuidReliable(final String uuid) {
2584 final var cached = findConversationByUuid(uuid);
2585 if (cached != null) {
2586 return cached;
2587 }
2588 final var existing = databaseBackend.findConversation(uuid);
2589 if (existing == null) {
2590 return null;
2591 }
2592 Log.d(Config.LOGTAG, "restoring conversation with " + existing.getJid() + " from DB");
2593 final Map<String, Account> accounts =
2594 ImmutableMap.copyOf(Maps.uniqueIndex(this.accounts, Account::getUuid));
2595 final var account = accounts.get(existing.getAccountUuid());
2596 if (account == null) {
2597 Log.d(Config.LOGTAG, "could not find account " + existing.getAccountUuid());
2598 return null;
2599 }
2600 existing.setAccount(account);
2601 final var loadMessagesFromDb = restoreFromArchive(existing);
2602 mDatabaseReaderExecutor.execute(
2603 () ->
2604 postProcessConversation(
2605 existing,
2606 loadMessagesFromDb,
2607 existing.getMode() == Conversational.MODE_MULTI,
2608 null));
2609 this.conversations.add(existing);
2610 if (existing.getMode() == Conversational.MODE_MULTI) {
2611 ensureBookmarkIsAutoJoin(existing);
2612 }
2613 updateConversationUi();
2614 return existing;
2615 }
2616
2617 private boolean restoreFromArchive(
2618 final Conversation conversation, final Jid jid, final boolean muc) {
2619 if (muc) {
2620 conversation.setMode(Conversation.MODE_MULTI);
2621 conversation.setContactJid(jid);
2622 } else {
2623 conversation.setMode(Conversation.MODE_SINGLE);
2624 conversation.setContactJid(jid.asBareJid());
2625 }
2626 return restoreFromArchive(conversation);
2627 }
2628
2629 private boolean restoreFromArchive(final Conversation conversation) {
2630 conversation.setStatus(Conversation.STATUS_AVAILABLE);
2631 databaseBackend.updateConversation(conversation);
2632 return conversation.messagesLoaded.compareAndSet(true, false);
2633 }
2634
2635 private void postProcessConversation(
2636 final Conversation c,
2637 final boolean loadMessagesFromDb,
2638 final boolean joinAfterCreate,
2639 final MessageArchiveService.Query query) {
2640 final var singleMode = c.getMode() == Conversational.MODE_SINGLE;
2641 final var account = c.getAccount();
2642 if (loadMessagesFromDb) {
2643 c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
2644 updateConversationUi();
2645 c.messagesLoaded.set(true);
2646 }
2647 if (account.getXmppConnection() != null
2648 && !c.getContact().isBlocked()
2649 && account.getXmppConnection().getFeatures().mam()
2650 && singleMode) {
2651 if (query == null) {
2652 mMessageArchiveService.query(c);
2653 } else {
2654 if (query.getConversation() == null) {
2655 mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
2656 }
2657 }
2658 }
2659 if (joinAfterCreate) {
2660 joinMuc(c);
2661 }
2662 }
2663
2664 public void archiveConversation(Conversation conversation) {
2665 archiveConversation(conversation, true);
2666 }
2667
2668 public void archiveConversation(
2669 Conversation conversation, final boolean maySynchronizeWithBookmarks) {
2670 getNotificationService().clear(conversation);
2671 conversation.setStatus(Conversation.STATUS_ARCHIVED);
2672 conversation.setNextMessage(null);
2673 synchronized (this.conversations) {
2674 getMessageArchiveService().kill(conversation);
2675 if (conversation.getMode() == Conversation.MODE_MULTI) {
2676 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2677 final Bookmark bookmark = conversation.getBookmark();
2678 if (maySynchronizeWithBookmarks && bookmark != null) {
2679 if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2680 Account account = bookmark.getAccount();
2681 bookmark.setConversation(null);
2682 deleteBookmark(account, bookmark);
2683 } else if (bookmark.autojoin()) {
2684 bookmark.setAutojoin(false);
2685 createBookmark(bookmark.getAccount(), bookmark);
2686 }
2687 }
2688 }
2689 leaveMuc(conversation);
2690 } else {
2691 if (conversation
2692 .getContact()
2693 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2694 stopPresenceUpdatesTo(conversation.getContact());
2695 }
2696 }
2697 updateConversation(conversation);
2698 this.conversations.remove(conversation);
2699 updateConversationUi();
2700 }
2701 }
2702
2703 public void stopPresenceUpdatesTo(final Contact contact) {
2704 Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
2705 contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2706 contact.getAccount()
2707 .getXmppConnection()
2708 .getManager(PresenceManager.class)
2709 .unsubscribed(contact.getJid().asBareJid());
2710 }
2711
2712 public void createAccount(final Account account) {
2713 account.setXmppConnection(createConnection(account));
2714 databaseBackend.createAccount(account);
2715 if (CallIntegration.hasSystemFeature(this)) {
2716 CallIntegrationConnectionService.togglePhoneAccountAsync(this, account);
2717 }
2718 this.accounts.add(account);
2719 this.reconnectAccountInBackground(account);
2720 updateAccountUi();
2721 syncEnabledAccountSetting();
2722 toggleForegroundService();
2723 }
2724
2725 private void syncEnabledAccountSetting() {
2726 final boolean hasEnabledAccounts = hasEnabledAccounts();
2727 getPreferences()
2728 .edit()
2729 .putBoolean(SystemEventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts)
2730 .apply();
2731 toggleSetProfilePictureActivity(hasEnabledAccounts);
2732 }
2733
2734 private void toggleSetProfilePictureActivity(final boolean enabled) {
2735 try {
2736 final ComponentName name =
2737 new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
2738 final int targetState =
2739 enabled
2740 ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
2741 : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
2742 getPackageManager()
2743 .setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
2744 } catch (IllegalStateException e) {
2745 Log.d(Config.LOGTAG, "unable to toggle profile picture activity");
2746 }
2747 }
2748
2749 public boolean reconfigurePushDistributor() {
2750 return this.unifiedPushBroker.reconfigurePushDistributor();
2751 }
2752
2753 private Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints(
2754 final UnifiedPushBroker.PushTargetMessenger pushTargetMessenger) {
2755 return this.unifiedPushBroker.renewUnifiedPushEndpoints(pushTargetMessenger);
2756 }
2757
2758 public Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints() {
2759 return this.unifiedPushBroker.renewUnifiedPushEndpoints(null);
2760 }
2761
2762 public UnifiedPushBroker getUnifiedPushBroker() {
2763 return this.unifiedPushBroker;
2764 }
2765
2766 private void provisionAccount(final String address, final String password) {
2767 final Jid jid = Jid.of(address);
2768 final Account account = new Account(jid, password);
2769 account.setOption(Account.OPTION_DISABLED, true);
2770 Log.d(Config.LOGTAG, jid.asBareJid().toString() + ": provisioning account");
2771 createAccount(account);
2772 }
2773
2774 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
2775 new Thread(
2776 () -> {
2777 try {
2778 final X509Certificate[] chain =
2779 KeyChain.getCertificateChain(this, alias);
2780 final X509Certificate cert =
2781 chain != null && chain.length > 0 ? chain[0] : null;
2782 if (cert == null) {
2783 callback.informUser(R.string.unable_to_parse_certificate);
2784 return;
2785 }
2786 Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
2787 if (info == null) {
2788 callback.informUser(R.string.certificate_does_not_contain_jid);
2789 return;
2790 }
2791 if (findAccountByJid(info.first) == null) {
2792 final Account account = new Account(info.first, "");
2793 account.setPrivateKeyAlias(alias);
2794 account.setOption(Account.OPTION_DISABLED, true);
2795 account.setOption(Account.OPTION_FIXED_USERNAME, true);
2796 account.setDisplayName(info.second);
2797 createAccount(account);
2798 callback.onAccountCreated(account);
2799 if (Config.X509_VERIFICATION) {
2800 try {
2801 getMemorizingTrustManager()
2802 .getNonInteractive(account.getServer())
2803 .checkClientTrusted(chain, "RSA");
2804 } catch (CertificateException e) {
2805 callback.informUser(
2806 R.string.certificate_chain_is_not_trusted);
2807 }
2808 }
2809 } else {
2810 callback.informUser(R.string.account_already_exists);
2811 }
2812 } catch (Exception e) {
2813 callback.informUser(R.string.unable_to_parse_certificate);
2814 }
2815 })
2816 .start();
2817 }
2818
2819 public void updateKeyInAccount(final Account account, final String alias) {
2820 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
2821 try {
2822 X509Certificate[] chain =
2823 KeyChain.getCertificateChain(XmppConnectionService.this, alias);
2824 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
2825 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
2826 if (info == null) {
2827 showErrorToastInUi(R.string.certificate_does_not_contain_jid);
2828 return;
2829 }
2830 if (account.getJid().asBareJid().equals(info.first)) {
2831 account.setPrivateKeyAlias(alias);
2832 account.setDisplayName(info.second);
2833 databaseBackend.updateAccount(account);
2834 if (Config.X509_VERIFICATION) {
2835 try {
2836 getMemorizingTrustManager()
2837 .getNonInteractive()
2838 .checkClientTrusted(chain, "RSA");
2839 } catch (CertificateException e) {
2840 showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
2841 }
2842 account.getAxolotlService().regenerateKeys(true);
2843 }
2844 } else {
2845 showErrorToastInUi(R.string.jid_does_not_match_certificate);
2846 }
2847 } catch (Exception e) {
2848 e.printStackTrace();
2849 }
2850 }
2851
2852 public boolean updateAccount(final Account account) {
2853 if (databaseBackend.updateAccount(account)) {
2854 account.setShowErrorNotification(true);
2855 // TODO what was the purpose of that? will likely be triggered by reconnect anyway?
2856 // this.statusListener.onStatusChanged(account);
2857 databaseBackend.updateAccount(account);
2858 reconnectAccountInBackground(account);
2859 updateAccountUi();
2860 getNotificationService().updateErrorNotification();
2861 toggleForegroundService();
2862 syncEnabledAccountSetting();
2863 mChannelDiscoveryService.cleanCache();
2864 if (CallIntegration.hasSystemFeature(this)) {
2865 CallIntegrationConnectionService.togglePhoneAccountAsync(this, account);
2866 }
2867 return true;
2868 } else {
2869 return false;
2870 }
2871 }
2872
2873 public void updateAccountPasswordOnServer(
2874 final Account account,
2875 final String newPassword,
2876 final OnAccountPasswordChanged callback) {
2877 final Iq iq = getIqGenerator().generateSetPassword(account, newPassword);
2878 sendIqPacket(
2879 account,
2880 iq,
2881 (packet) -> {
2882 if (packet.getType() == Iq.Type.RESULT) {
2883 account.setPassword(newPassword);
2884 account.setOption(Account.OPTION_MAGIC_CREATE, false);
2885 databaseBackend.updateAccount(account);
2886 callback.onPasswordChangeSucceeded();
2887 } else {
2888 callback.onPasswordChangeFailed();
2889 }
2890 });
2891 }
2892
2893 public void unregisterAccount(final Account account, final Consumer<Boolean> callback) {
2894 final Iq iqPacket = new Iq(Iq.Type.SET);
2895 final Element query = iqPacket.addChild("query", Namespace.REGISTER);
2896 query.addChild("remove");
2897 sendIqPacket(
2898 account,
2899 iqPacket,
2900 (response) -> {
2901 if (response.getType() == Iq.Type.RESULT) {
2902 deleteAccount(account);
2903 callback.accept(true);
2904 } else {
2905 callback.accept(false);
2906 }
2907 });
2908 }
2909
2910 public void deleteAccount(final Account account) {
2911 final boolean connected = account.getStatus() == Account.State.ONLINE;
2912 synchronized (this.conversations) {
2913 if (connected) {
2914 account.getAxolotlService().deleteOmemoIdentity();
2915 }
2916 for (final Conversation conversation : conversations) {
2917 if (conversation.getAccount() == account) {
2918 if (conversation.getMode() == Conversation.MODE_MULTI) {
2919 if (connected) {
2920 leaveMuc(conversation);
2921 }
2922 }
2923 conversations.remove(conversation);
2924 mNotificationService.clear(conversation);
2925 }
2926 }
2927 if (account.getXmppConnection() != null) {
2928 new Thread(() -> disconnect(account, !connected)).start();
2929 }
2930 final Runnable runnable =
2931 () -> {
2932 if (!databaseBackend.deleteAccount(account)) {
2933 Log.d(
2934 Config.LOGTAG,
2935 account.getJid().asBareJid() + ": unable to delete account");
2936 }
2937 };
2938 mDatabaseWriterExecutor.execute(runnable);
2939 this.accounts.remove(account);
2940 if (CallIntegration.hasSystemFeature(this)) {
2941 CallIntegrationConnectionService.unregisterPhoneAccount(this, account);
2942 }
2943 updateAccountUi();
2944 mNotificationService.updateErrorNotification();
2945 syncEnabledAccountSetting();
2946 toggleForegroundService();
2947 }
2948 }
2949
2950 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
2951 final boolean remainingListeners;
2952 synchronized (LISTENER_LOCK) {
2953 remainingListeners = checkListeners();
2954 if (!this.mOnConversationUpdates.add(listener)) {
2955 Log.w(
2956 Config.LOGTAG,
2957 listener.getClass().getName()
2958 + " is already registered as ConversationListChangedListener");
2959 }
2960 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2961 }
2962 if (remainingListeners) {
2963 switchToForeground();
2964 }
2965 }
2966
2967 public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
2968 final boolean remainingListeners;
2969 synchronized (LISTENER_LOCK) {
2970 this.mOnConversationUpdates.remove(listener);
2971 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2972 remainingListeners = checkListeners();
2973 }
2974 if (remainingListeners) {
2975 switchToBackground();
2976 }
2977 }
2978
2979 public void setOnShowErrorToastListener(OnShowErrorToast listener) {
2980 final boolean remainingListeners;
2981 synchronized (LISTENER_LOCK) {
2982 remainingListeners = checkListeners();
2983 if (!this.mOnShowErrorToasts.add(listener)) {
2984 Log.w(
2985 Config.LOGTAG,
2986 listener.getClass().getName()
2987 + " is already registered as OnShowErrorToastListener");
2988 }
2989 }
2990 if (remainingListeners) {
2991 switchToForeground();
2992 }
2993 }
2994
2995 public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
2996 final boolean remainingListeners;
2997 synchronized (LISTENER_LOCK) {
2998 this.mOnShowErrorToasts.remove(onShowErrorToast);
2999 remainingListeners = checkListeners();
3000 }
3001 if (remainingListeners) {
3002 switchToBackground();
3003 }
3004 }
3005
3006 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
3007 final boolean remainingListeners;
3008 synchronized (LISTENER_LOCK) {
3009 remainingListeners = checkListeners();
3010 if (!this.mOnAccountUpdates.add(listener)) {
3011 Log.w(
3012 Config.LOGTAG,
3013 listener.getClass().getName()
3014 + " is already registered as OnAccountListChangedtListener");
3015 }
3016 }
3017 if (remainingListeners) {
3018 switchToForeground();
3019 }
3020 }
3021
3022 public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
3023 final boolean remainingListeners;
3024 synchronized (LISTENER_LOCK) {
3025 this.mOnAccountUpdates.remove(listener);
3026 remainingListeners = checkListeners();
3027 }
3028 if (remainingListeners) {
3029 switchToBackground();
3030 }
3031 }
3032
3033 public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
3034 final boolean remainingListeners;
3035 synchronized (LISTENER_LOCK) {
3036 remainingListeners = checkListeners();
3037 if (!this.mOnCaptchaRequested.add(listener)) {
3038 Log.w(
3039 Config.LOGTAG,
3040 listener.getClass().getName()
3041 + " is already registered as OnCaptchaRequestListener");
3042 }
3043 }
3044 if (remainingListeners) {
3045 switchToForeground();
3046 }
3047 }
3048
3049 public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
3050 final boolean remainingListeners;
3051 synchronized (LISTENER_LOCK) {
3052 this.mOnCaptchaRequested.remove(listener);
3053 remainingListeners = checkListeners();
3054 }
3055 if (remainingListeners) {
3056 switchToBackground();
3057 }
3058 }
3059
3060 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
3061 final boolean remainingListeners;
3062 synchronized (LISTENER_LOCK) {
3063 remainingListeners = checkListeners();
3064 if (!this.mOnRosterUpdates.add(listener)) {
3065 Log.w(
3066 Config.LOGTAG,
3067 listener.getClass().getName()
3068 + " is already registered as OnRosterUpdateListener");
3069 }
3070 }
3071 if (remainingListeners) {
3072 switchToForeground();
3073 }
3074 }
3075
3076 public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
3077 final boolean remainingListeners;
3078 synchronized (LISTENER_LOCK) {
3079 this.mOnRosterUpdates.remove(listener);
3080 remainingListeners = checkListeners();
3081 }
3082 if (remainingListeners) {
3083 switchToBackground();
3084 }
3085 }
3086
3087 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
3088 final boolean remainingListeners;
3089 synchronized (LISTENER_LOCK) {
3090 remainingListeners = checkListeners();
3091 if (!this.mOnUpdateBlocklist.add(listener)) {
3092 Log.w(
3093 Config.LOGTAG,
3094 listener.getClass().getName()
3095 + " is already registered as OnUpdateBlocklistListener");
3096 }
3097 }
3098 if (remainingListeners) {
3099 switchToForeground();
3100 }
3101 }
3102
3103 public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
3104 final boolean remainingListeners;
3105 synchronized (LISTENER_LOCK) {
3106 this.mOnUpdateBlocklist.remove(listener);
3107 remainingListeners = checkListeners();
3108 }
3109 if (remainingListeners) {
3110 switchToBackground();
3111 }
3112 }
3113
3114 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
3115 final boolean remainingListeners;
3116 synchronized (LISTENER_LOCK) {
3117 remainingListeners = checkListeners();
3118 if (!this.mOnKeyStatusUpdated.add(listener)) {
3119 Log.w(
3120 Config.LOGTAG,
3121 listener.getClass().getName()
3122 + " is already registered as OnKeyStatusUpdateListener");
3123 }
3124 }
3125 if (remainingListeners) {
3126 switchToForeground();
3127 }
3128 }
3129
3130 public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
3131 final boolean remainingListeners;
3132 synchronized (LISTENER_LOCK) {
3133 this.mOnKeyStatusUpdated.remove(listener);
3134 remainingListeners = checkListeners();
3135 }
3136 if (remainingListeners) {
3137 switchToBackground();
3138 }
3139 }
3140
3141 public void setOnRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
3142 final boolean remainingListeners;
3143 synchronized (LISTENER_LOCK) {
3144 remainingListeners = checkListeners();
3145 if (!this.onJingleRtpConnectionUpdate.add(listener)) {
3146 Log.w(
3147 Config.LOGTAG,
3148 listener.getClass().getName()
3149 + " is already registered as OnJingleRtpConnectionUpdate");
3150 }
3151 }
3152 if (remainingListeners) {
3153 switchToForeground();
3154 }
3155 }
3156
3157 public void removeRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
3158 final boolean remainingListeners;
3159 synchronized (LISTENER_LOCK) {
3160 this.onJingleRtpConnectionUpdate.remove(listener);
3161 remainingListeners = checkListeners();
3162 }
3163 if (remainingListeners) {
3164 switchToBackground();
3165 }
3166 }
3167
3168 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
3169 final boolean remainingListeners;
3170 synchronized (LISTENER_LOCK) {
3171 remainingListeners = checkListeners();
3172 if (!this.mOnMucRosterUpdate.add(listener)) {
3173 Log.w(
3174 Config.LOGTAG,
3175 listener.getClass().getName()
3176 + " is already registered as OnMucRosterListener");
3177 }
3178 }
3179 if (remainingListeners) {
3180 switchToForeground();
3181 }
3182 }
3183
3184 public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
3185 final boolean remainingListeners;
3186 synchronized (LISTENER_LOCK) {
3187 this.mOnMucRosterUpdate.remove(listener);
3188 remainingListeners = checkListeners();
3189 }
3190 if (remainingListeners) {
3191 switchToBackground();
3192 }
3193 }
3194
3195 public boolean checkListeners() {
3196 return (this.mOnAccountUpdates.isEmpty()
3197 && this.mOnConversationUpdates.isEmpty()
3198 && this.mOnRosterUpdates.isEmpty()
3199 && this.mOnCaptchaRequested.isEmpty()
3200 && this.mOnMucRosterUpdate.isEmpty()
3201 && this.mOnUpdateBlocklist.isEmpty()
3202 && this.mOnShowErrorToasts.isEmpty()
3203 && this.onJingleRtpConnectionUpdate.isEmpty()
3204 && this.mOnKeyStatusUpdated.isEmpty());
3205 }
3206
3207 private void switchToForeground() {
3208 toggleSoftDisabled(false);
3209 final boolean broadcastLastActivity = broadcastLastActivity();
3210 for (Conversation conversation : getConversations()) {
3211 if (conversation.getMode() == Conversation.MODE_MULTI) {
3212 conversation.getMucOptions().resetChatState();
3213 } else {
3214 conversation.setIncomingChatState(Config.DEFAULT_CHAT_STATE);
3215 }
3216 }
3217 for (Account account : getAccounts()) {
3218 if (account.getStatus() == Account.State.ONLINE) {
3219 account.deactivateGracePeriod();
3220 final XmppConnection connection = account.getXmppConnection();
3221 if (connection != null) {
3222 if (connection.getFeatures().csi()) {
3223 connection.sendActive();
3224 }
3225 if (broadcastLastActivity) {
3226 sendPresence(
3227 account,
3228 false); // send new presence but don't include idle because we are
3229 // not
3230 }
3231 }
3232 }
3233 }
3234 Log.d(Config.LOGTAG, "app switched into foreground");
3235 }
3236
3237 private void switchToBackground() {
3238 final boolean broadcastLastActivity = broadcastLastActivity();
3239 if (broadcastLastActivity) {
3240 mLastActivity = System.currentTimeMillis();
3241 final SharedPreferences.Editor editor = getPreferences().edit();
3242 editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
3243 editor.apply();
3244 }
3245 for (Account account : getAccounts()) {
3246 if (account.getStatus() == Account.State.ONLINE) {
3247 XmppConnection connection = account.getXmppConnection();
3248 if (connection != null) {
3249 if (broadcastLastActivity) {
3250 sendPresence(account, true);
3251 }
3252 if (connection.getFeatures().csi()) {
3253 connection.sendInactive();
3254 }
3255 }
3256 }
3257 }
3258 this.mNotificationService.setIsInForeground(false);
3259 Log.d(Config.LOGTAG, "app switched into background");
3260 }
3261
3262 public void connectMultiModeConversations(Account account) {
3263 List<Conversation> conversations = getConversations();
3264 for (Conversation conversation : conversations) {
3265 if (conversation.getMode() == Conversation.MODE_MULTI
3266 && conversation.getAccount() == account) {
3267 joinMuc(conversation);
3268 }
3269 }
3270 }
3271
3272 public void mucSelfPingAndRejoin(final Conversation conversation) {
3273 final Account account = conversation.getAccount();
3274 synchronized (account.inProgressConferenceJoins) {
3275 if (account.inProgressConferenceJoins.contains(conversation)) {
3276 Log.d(
3277 Config.LOGTAG,
3278 account.getJid().asBareJid()
3279 + ": canceling muc self ping because join is already under way");
3280 return;
3281 }
3282 }
3283 synchronized (account.inProgressConferencePings) {
3284 if (!account.inProgressConferencePings.add(conversation)) {
3285 Log.d(
3286 Config.LOGTAG,
3287 account.getJid().asBareJid()
3288 + ": canceling muc self ping because ping is already under way");
3289 return;
3290 }
3291 }
3292 // TODO use PingManager
3293 final Jid self = conversation.getMucOptions().getSelf().getFullJid();
3294 final Iq ping = new Iq(Iq.Type.GET);
3295 ping.setTo(self);
3296 ping.addChild("ping", Namespace.PING);
3297 sendIqPacket(
3298 conversation.getAccount(),
3299 ping,
3300 (response) -> {
3301 if (response.getType() == Iq.Type.ERROR) {
3302 final var error = response.getError();
3303 if (error == null
3304 || error.hasChild("service-unavailable")
3305 || error.hasChild("feature-not-implemented")
3306 || error.hasChild("item-not-found")) {
3307 Log.d(
3308 Config.LOGTAG,
3309 account.getJid().asBareJid()
3310 + ": ping to "
3311 + self
3312 + " came back as ignorable error");
3313 } else {
3314 Log.d(
3315 Config.LOGTAG,
3316 account.getJid().asBareJid()
3317 + ": ping to "
3318 + self
3319 + " failed. attempting rejoin");
3320 joinMuc(conversation);
3321 }
3322 } else if (response.getType() == Iq.Type.RESULT) {
3323 Log.d(
3324 Config.LOGTAG,
3325 account.getJid().asBareJid()
3326 + ": ping to "
3327 + self
3328 + " came back fine");
3329 }
3330 synchronized (account.inProgressConferencePings) {
3331 account.inProgressConferencePings.remove(conversation);
3332 }
3333 });
3334 }
3335
3336 public void joinMuc(Conversation conversation) {
3337 joinMuc(conversation, null, false);
3338 }
3339
3340 public void joinMuc(Conversation conversation, boolean followedInvite) {
3341 joinMuc(conversation, null, followedInvite);
3342 }
3343
3344 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
3345 joinMuc(conversation, onConferenceJoined, false);
3346 }
3347
3348 private void joinMuc(
3349 final Conversation conversation,
3350 final OnConferenceJoined onConferenceJoined,
3351 final boolean followedInvite) {
3352 final Account account = conversation.getAccount();
3353 synchronized (account.pendingConferenceJoins) {
3354 account.pendingConferenceJoins.remove(conversation);
3355 }
3356 synchronized (account.pendingConferenceLeaves) {
3357 account.pendingConferenceLeaves.remove(conversation);
3358 }
3359 if (account.getStatus() == Account.State.ONLINE) {
3360 synchronized (account.inProgressConferenceJoins) {
3361 account.inProgressConferenceJoins.add(conversation);
3362 }
3363 if (Config.MUC_LEAVE_BEFORE_JOIN) {
3364 sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
3365 }
3366 conversation.resetMucOptions();
3367 if (onConferenceJoined != null) {
3368 conversation.getMucOptions().flagNoAutoPushConfiguration();
3369 }
3370 conversation.setHasMessagesLeftOnServer(false);
3371 fetchConferenceConfiguration(
3372 conversation,
3373 new OnConferenceConfigurationFetched() {
3374
3375 private void join(Conversation conversation) {
3376 Account account = conversation.getAccount();
3377 final MucOptions mucOptions = conversation.getMucOptions();
3378
3379 if (mucOptions.nonanonymous()
3380 && !mucOptions.membersOnly()
3381 && !conversation.getBooleanAttribute(
3382 "accept_non_anonymous", false)) {
3383 synchronized (account.inProgressConferenceJoins) {
3384 account.inProgressConferenceJoins.remove(conversation);
3385 }
3386 mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
3387 updateConversationUi();
3388 if (onConferenceJoined != null) {
3389 onConferenceJoined.onConferenceJoined(conversation);
3390 }
3391 return;
3392 }
3393
3394 final Jid joinJid = mucOptions.getSelf().getFullJid();
3395 Log.d(
3396 Config.LOGTAG,
3397 account.getJid().asBareJid().toString()
3398 + ": joining conversation "
3399 + joinJid.toString());
3400 final var packet =
3401 mPresenceGenerator.selfPresence(
3402 account,
3403 im.conversations.android.xmpp.model.stanza.Presence
3404 .Availability.ONLINE,
3405 mucOptions.nonanonymous()
3406 || onConferenceJoined != null);
3407 packet.setTo(joinJid);
3408 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
3409 if (conversation.getMucOptions().getPassword() != null) {
3410 x.addChild("password").setContent(mucOptions.getPassword());
3411 }
3412
3413 if (mucOptions.mamSupport()) {
3414 // Use MAM instead of the limited muc history to get history
3415 x.addChild("history").setAttribute("maxchars", "0");
3416 } else {
3417 // Fallback to muc history
3418 x.addChild("history")
3419 .setAttribute(
3420 "since",
3421 PresenceGenerator.getTimestamp(
3422 conversation
3423 .getLastMessageTransmitted()
3424 .getTimestamp()));
3425 }
3426 sendPresencePacket(account, packet);
3427 if (onConferenceJoined != null) {
3428 onConferenceJoined.onConferenceJoined(conversation);
3429 }
3430 if (!joinJid.equals(conversation.getJid())) {
3431 conversation.setContactJid(joinJid);
3432 databaseBackend.updateConversation(conversation);
3433 }
3434
3435 if (mucOptions.mamSupport()) {
3436 getMessageArchiveService().catchupMUC(conversation);
3437 }
3438 if (mucOptions.isPrivateAndNonAnonymous()) {
3439 fetchConferenceMembers(conversation);
3440
3441 if (followedInvite) {
3442 final Bookmark bookmark = conversation.getBookmark();
3443 if (bookmark != null) {
3444 if (!bookmark.autojoin()) {
3445 bookmark.setAutojoin(true);
3446 createBookmark(account, bookmark);
3447 }
3448 } else {
3449 saveConversationAsBookmark(conversation, null);
3450 }
3451 }
3452 }
3453 synchronized (account.inProgressConferenceJoins) {
3454 account.inProgressConferenceJoins.remove(conversation);
3455 sendUnsentMessages(conversation);
3456 }
3457 }
3458
3459 @Override
3460 public void onConferenceConfigurationFetched(Conversation conversation) {
3461 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3462 Log.d(
3463 Config.LOGTAG,
3464 account.getJid().asBareJid()
3465 + ": conversation ("
3466 + conversation.getJid()
3467 + ") got archived before IQ result");
3468 return;
3469 }
3470 join(conversation);
3471 }
3472
3473 @Override
3474 public void onFetchFailed(
3475 final Conversation conversation, final String errorCondition) {
3476 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3477 Log.d(
3478 Config.LOGTAG,
3479 account.getJid().asBareJid()
3480 + ": conversation ("
3481 + conversation.getJid()
3482 + ") got archived before IQ result");
3483 return;
3484 }
3485 if ("remote-server-not-found".equals(errorCondition)) {
3486 synchronized (account.inProgressConferenceJoins) {
3487 account.inProgressConferenceJoins.remove(conversation);
3488 }
3489 conversation
3490 .getMucOptions()
3491 .setError(MucOptions.Error.SERVER_NOT_FOUND);
3492 updateConversationUi();
3493 } else {
3494 join(conversation);
3495 fetchConferenceConfiguration(conversation);
3496 }
3497 }
3498 });
3499 updateConversationUi();
3500 } else {
3501 synchronized (account.pendingConferenceJoins) {
3502 account.pendingConferenceJoins.add(conversation);
3503 }
3504 conversation.resetMucOptions();
3505 conversation.setHasMessagesLeftOnServer(false);
3506 updateConversationUi();
3507 }
3508 }
3509
3510 private void fetchConferenceMembers(final Conversation conversation) {
3511 final Account account = conversation.getAccount();
3512 final AxolotlService axolotlService = account.getAxolotlService();
3513 final String[] affiliations = {"member", "admin", "owner"};
3514 final Consumer<Iq> callback =
3515 new Consumer<Iq>() {
3516
3517 private int i = 0;
3518 private boolean success = true;
3519
3520 @Override
3521 public void accept(Iq response) {
3522 final boolean omemoEnabled =
3523 conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
3524 Element query = response.query("http://jabber.org/protocol/muc#admin");
3525 if (response.getType() == Iq.Type.RESULT && query != null) {
3526 for (Element child : query.getChildren()) {
3527 if ("item".equals(child.getName())) {
3528 MucOptions.User user =
3529 AbstractParser.parseItem(conversation, child);
3530 if (!user.realJidMatchesAccount()) {
3531 boolean isNew =
3532 conversation.getMucOptions().updateUser(user);
3533 Contact contact = user.getContact();
3534 if (omemoEnabled
3535 && isNew
3536 && user.getRealJid() != null
3537 && (contact == null
3538 || !contact.mutualPresenceSubscription())
3539 && axolotlService.hasEmptyDeviceList(
3540 user.getRealJid())) {
3541 axolotlService.fetchDeviceIds(user.getRealJid());
3542 }
3543 }
3544 }
3545 }
3546 } else {
3547 success = false;
3548 Log.d(
3549 Config.LOGTAG,
3550 account.getJid().asBareJid()
3551 + ": could not request affiliation "
3552 + affiliations[i]
3553 + " in "
3554 + conversation.getJid().asBareJid());
3555 }
3556 ++i;
3557 if (i >= affiliations.length) {
3558 final var mucOptions = conversation.getMucOptions();
3559 final var members = mucOptions.getMembers(true);
3560 if (success) {
3561 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
3562 boolean changed = false;
3563 for (ListIterator<Jid> iterator = cryptoTargets.listIterator();
3564 iterator.hasNext(); ) {
3565 Jid jid = iterator.next();
3566 if (!members.contains(jid)
3567 && !members.contains(jid.getDomain())) {
3568 iterator.remove();
3569 Log.d(
3570 Config.LOGTAG,
3571 account.getJid().asBareJid()
3572 + ": removed "
3573 + jid
3574 + " from crypto targets of "
3575 + conversation.getName());
3576 changed = true;
3577 }
3578 }
3579 if (changed) {
3580 conversation.setAcceptedCryptoTargets(cryptoTargets);
3581 updateConversation(conversation);
3582 }
3583 }
3584 getAvatarService().clear(mucOptions);
3585 updateMucRosterUi();
3586 updateConversationUi();
3587 }
3588 }
3589 };
3590 for (String affiliation : affiliations) {
3591 sendIqPacket(
3592 account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
3593 }
3594 Log.d(
3595 Config.LOGTAG,
3596 account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
3597 }
3598
3599 public void providePasswordForMuc(final Conversation conversation, final String password) {
3600 if (conversation.getMode() == Conversation.MODE_MULTI) {
3601 conversation.getMucOptions().setPassword(password);
3602 if (conversation.getBookmark() != null) {
3603 final Bookmark bookmark = conversation.getBookmark();
3604 bookmark.setAutojoin(true);
3605 createBookmark(conversation.getAccount(), bookmark);
3606 }
3607 updateConversation(conversation);
3608 joinMuc(conversation);
3609 }
3610 }
3611
3612 public void deleteAvatar(final Account account) {
3613 final AtomicBoolean executed = new AtomicBoolean(false);
3614 final Runnable onDeleted =
3615 () -> {
3616 if (executed.compareAndSet(false, true)) {
3617 account.setAvatar(null);
3618 databaseBackend.updateAccount(account);
3619 getAvatarService().clear(account);
3620 updateAccountUi();
3621 }
3622 };
3623 deleteVcardAvatar(account, onDeleted);
3624 deletePepNode(account, Namespace.AVATAR_DATA);
3625 deletePepNode(account, Namespace.AVATAR_METADATA, onDeleted);
3626 }
3627
3628 public void deletePepNode(final Account account, final String node) {
3629 deletePepNode(account, node, null);
3630 }
3631
3632 private void deletePepNode(final Account account, final String node, final Runnable runnable) {
3633 final Iq request = mIqGenerator.deleteNode(node);
3634 sendIqPacket(
3635 account,
3636 request,
3637 (packet) -> {
3638 if (packet.getType() == Iq.Type.RESULT) {
3639 Log.d(
3640 Config.LOGTAG,
3641 account.getJid().asBareJid()
3642 + ": successfully deleted pep node "
3643 + node);
3644 if (runnable != null) {
3645 runnable.run();
3646 }
3647 } else {
3648 Log.d(
3649 Config.LOGTAG,
3650 account.getJid().asBareJid() + ": failed to delete " + packet);
3651 }
3652 });
3653 }
3654
3655 private void deleteVcardAvatar(final Account account, @NonNull final Runnable runnable) {
3656 final Iq retrieveVcard = mIqGenerator.retrieveVcardAvatar(account.getJid().asBareJid());
3657 sendIqPacket(
3658 account,
3659 retrieveVcard,
3660 (response) -> {
3661 if (response.getType() != Iq.Type.RESULT) {
3662 Log.d(
3663 Config.LOGTAG,
3664 account.getJid().asBareJid() + ": no vCard set. nothing to do");
3665 return;
3666 }
3667 final Element vcard = response.findChild("vCard", "vcard-temp");
3668 if (vcard == null) {
3669 Log.d(
3670 Config.LOGTAG,
3671 account.getJid().asBareJid() + ": no vCard set. nothing to do");
3672 return;
3673 }
3674 Element photo = vcard.findChild("PHOTO");
3675 if (photo == null) {
3676 photo = vcard.addChild("PHOTO");
3677 }
3678 photo.clearChildren();
3679 final Iq publication = new Iq(Iq.Type.SET);
3680 publication.setTo(account.getJid().asBareJid());
3681 publication.addChild(vcard);
3682 sendIqPacket(
3683 account,
3684 publication,
3685 (publicationResponse) -> {
3686 if (publicationResponse.getType() == Iq.Type.RESULT) {
3687 Log.d(
3688 Config.LOGTAG,
3689 account.getJid().asBareJid()
3690 + ": successfully deleted vcard avatar");
3691 runnable.run();
3692 } else {
3693 Log.d(
3694 Config.LOGTAG,
3695 "failed to publish vcard "
3696 + publicationResponse.getErrorCondition());
3697 }
3698 });
3699 });
3700 }
3701
3702 private boolean hasEnabledAccounts() {
3703 if (this.accounts == null) {
3704 return false;
3705 }
3706 for (final Account account : this.accounts) {
3707 if (account.isConnectionEnabled()) {
3708 return true;
3709 }
3710 }
3711 return false;
3712 }
3713
3714 public void getAttachments(
3715 final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
3716 getAttachments(
3717 conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
3718 }
3719
3720 public void getAttachments(
3721 final Account account,
3722 final Jid jid,
3723 final int limit,
3724 final OnMediaLoaded onMediaLoaded) {
3725 getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
3726 }
3727
3728 public void getAttachments(
3729 final String account,
3730 final Jid jid,
3731 final int limit,
3732 final OnMediaLoaded onMediaLoaded) {
3733 new Thread(
3734 () ->
3735 onMediaLoaded.onMediaLoaded(
3736 fileBackend.convertToAttachments(
3737 databaseBackend.getRelativeFilePaths(
3738 account, jid, limit))))
3739 .start();
3740 }
3741
3742 public void persistSelfNick(final MucOptions.User self, final boolean modified) {
3743 final Conversation conversation = self.getConversation();
3744 final Account account = conversation.getAccount();
3745 final Jid full = self.getFullJid();
3746 if (!full.equals(conversation.getJid())) {
3747 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persisting full jid " + full);
3748 conversation.setContactJid(full);
3749 databaseBackend.updateConversation(conversation);
3750 }
3751
3752 final Bookmark bookmark = conversation.getBookmark();
3753 if (bookmark == null || !modified) {
3754 return;
3755 }
3756 final var nick = full.getResource();
3757 final String defaultNick = MucOptions.defaultNick(account);
3758 if (nick.equals(defaultNick) || nick.equals(bookmark.getNick())) {
3759 return;
3760 }
3761 Log.d(
3762 Config.LOGTAG,
3763 account.getJid().asBareJid()
3764 + ": persist nick '"
3765 + full.getResource()
3766 + "' into bookmark for "
3767 + conversation.getJid().asBareJid());
3768 bookmark.setNick(nick);
3769 createBookmark(bookmark.getAccount(), bookmark);
3770 }
3771
3772 public boolean renameInMuc(
3773 final Conversation conversation,
3774 final String nick,
3775 final UiCallback<Conversation> callback) {
3776 final Account account = conversation.getAccount();
3777 final Bookmark bookmark = conversation.getBookmark();
3778 final MucOptions options = conversation.getMucOptions();
3779 final Jid joinJid = options.createJoinJid(nick);
3780 if (joinJid == null) {
3781 return false;
3782 }
3783 if (options.online()) {
3784 options.setOnRenameListener(
3785 new OnRenameListener() {
3786
3787 @Override
3788 public void onSuccess() {
3789 callback.success(conversation);
3790 }
3791
3792 @Override
3793 public void onFailure() {
3794 callback.error(R.string.nick_in_use, conversation);
3795 }
3796 });
3797
3798 final var packet =
3799 mPresenceGenerator.selfPresence(
3800 account,
3801 im.conversations.android.xmpp.model.stanza.Presence.Availability.ONLINE,
3802 options.nonanonymous());
3803 packet.setTo(joinJid);
3804 sendPresencePacket(account, packet);
3805 if (nick.equals(MucOptions.defaultNick(account))
3806 && bookmark != null
3807 && bookmark.getNick() != null) {
3808 Log.d(
3809 Config.LOGTAG,
3810 account.getJid().asBareJid()
3811 + ": removing nick from bookmark for "
3812 + bookmark.getJid());
3813 bookmark.setNick(null);
3814 createBookmark(account, bookmark);
3815 }
3816 } else {
3817 conversation.setContactJid(joinJid);
3818 databaseBackend.updateConversation(conversation);
3819 if (account.getStatus() == Account.State.ONLINE) {
3820 if (bookmark != null) {
3821 bookmark.setNick(nick);
3822 createBookmark(account, bookmark);
3823 }
3824 joinMuc(conversation);
3825 }
3826 }
3827 return true;
3828 }
3829
3830 public void checkMucRequiresRename() {
3831 synchronized (this.conversations) {
3832 for (final Conversation conversation : this.conversations) {
3833 if (conversation.getMode() == Conversational.MODE_MULTI) {
3834 checkMucRequiresRename(conversation);
3835 }
3836 }
3837 }
3838 }
3839
3840 private void checkMucRequiresRename(final Conversation conversation) {
3841 final var options = conversation.getMucOptions();
3842 if (!options.online()) {
3843 return;
3844 }
3845 final var account = conversation.getAccount();
3846 final String current = options.getActualNick();
3847 final String proposed = options.getProposedNickPure();
3848 if (current == null || current.equals(proposed)) {
3849 return;
3850 }
3851 final Jid joinJid = options.createJoinJid(proposed);
3852 Log.d(
3853 Config.LOGTAG,
3854 String.format(
3855 "%s: muc rename required %s (was: %s)",
3856 account.getJid().asBareJid(), joinJid, current));
3857 final var packet =
3858 mPresenceGenerator.selfPresence(
3859 account,
3860 im.conversations.android.xmpp.model.stanza.Presence.Availability.ONLINE,
3861 options.nonanonymous());
3862 packet.setTo(joinJid);
3863 sendPresencePacket(account, packet);
3864 }
3865
3866 public void leaveMuc(Conversation conversation) {
3867 leaveMuc(conversation, false);
3868 }
3869
3870 private void leaveMuc(Conversation conversation, boolean now) {
3871 final Account account = conversation.getAccount();
3872 synchronized (account.pendingConferenceJoins) {
3873 account.pendingConferenceJoins.remove(conversation);
3874 }
3875 synchronized (account.pendingConferenceLeaves) {
3876 account.pendingConferenceLeaves.remove(conversation);
3877 }
3878 if (account.getStatus() == Account.State.ONLINE || now) {
3879 sendPresencePacket(
3880 conversation.getAccount(),
3881 mPresenceGenerator.leave(conversation.getMucOptions()));
3882 conversation.getMucOptions().setOffline();
3883 Bookmark bookmark = conversation.getBookmark();
3884 if (bookmark != null) {
3885 bookmark.setConversation(null);
3886 }
3887 Log.d(
3888 Config.LOGTAG,
3889 conversation.getAccount().getJid().asBareJid()
3890 + ": leaving muc "
3891 + conversation.getJid());
3892 final var connection = account.getXmppConnection();
3893 if (connection != null) {
3894 connection.getManager(DiscoManager.class).clear(conversation.getJid().asBareJid());
3895 }
3896 } else {
3897 synchronized (account.pendingConferenceLeaves) {
3898 account.pendingConferenceLeaves.add(conversation);
3899 }
3900 }
3901 }
3902
3903 public String findConferenceServer(final Account account) {
3904 String server;
3905 if (account.getXmppConnection() != null) {
3906 server = account.getXmppConnection().getMucServer();
3907 if (server != null) {
3908 return server;
3909 }
3910 }
3911 for (Account other : getAccounts()) {
3912 if (other != account && other.getXmppConnection() != null) {
3913 server = other.getXmppConnection().getMucServer();
3914 if (server != null) {
3915 return server;
3916 }
3917 }
3918 }
3919 return null;
3920 }
3921
3922 public void createPublicChannel(
3923 final Account account,
3924 final String name,
3925 final Jid address,
3926 final UiCallback<Conversation> callback) {
3927 joinMuc(
3928 findOrCreateConversation(account, address, true, false, true),
3929 conversation -> {
3930 final Bundle configuration = IqGenerator.defaultChannelConfiguration();
3931 if (!TextUtils.isEmpty(name)) {
3932 configuration.putString("muc#roomconfig_roomname", name);
3933 }
3934 pushConferenceConfiguration(
3935 conversation,
3936 configuration,
3937 new OnConfigurationPushed() {
3938 @Override
3939 public void onPushSucceeded() {
3940 saveConversationAsBookmark(conversation, name);
3941 callback.success(conversation);
3942 }
3943
3944 @Override
3945 public void onPushFailed() {
3946 if (conversation
3947 .getMucOptions()
3948 .getSelf()
3949 .getAffiliation()
3950 .ranks(MucOptions.Affiliation.OWNER)) {
3951 callback.error(
3952 R.string.unable_to_set_channel_configuration,
3953 conversation);
3954 } else {
3955 callback.error(
3956 R.string.joined_an_existing_channel, conversation);
3957 }
3958 }
3959 });
3960 });
3961 }
3962
3963 public boolean createAdhocConference(
3964 final Account account,
3965 final String name,
3966 final Iterable<Jid> jids,
3967 final UiCallback<Conversation> callback) {
3968 Log.d(
3969 Config.LOGTAG,
3970 account.getJid().asBareJid().toString()
3971 + ": creating adhoc conference with "
3972 + jids.toString());
3973 if (account.getStatus() == Account.State.ONLINE) {
3974 try {
3975 String server = findConferenceServer(account);
3976 if (server == null) {
3977 if (callback != null) {
3978 callback.error(R.string.no_conference_server_found, null);
3979 }
3980 return false;
3981 }
3982 final Jid jid = Jid.of(CryptoHelper.pronounceable(), server, null);
3983 final Conversation conversation =
3984 findOrCreateConversation(account, jid, true, false, true);
3985 joinMuc(
3986 conversation,
3987 new OnConferenceJoined() {
3988 @Override
3989 public void onConferenceJoined(final Conversation conversation) {
3990 final Bundle configuration =
3991 IqGenerator.defaultGroupChatConfiguration();
3992 if (!TextUtils.isEmpty(name)) {
3993 configuration.putString("muc#roomconfig_roomname", name);
3994 }
3995 pushConferenceConfiguration(
3996 conversation,
3997 configuration,
3998 new OnConfigurationPushed() {
3999 @Override
4000 public void onPushSucceeded() {
4001 for (Jid invite : jids) {
4002 invite(conversation, invite);
4003 }
4004 for (String resource :
4005 account.getSelfContact()
4006 .getPresences()
4007 .toResourceArray()) {
4008 Jid other =
4009 account.getJid().withResource(resource);
4010 Log.d(
4011 Config.LOGTAG,
4012 account.getJid().asBareJid()
4013 + ": sending direct invite to "
4014 + other);
4015 directInvite(conversation, other);
4016 }
4017 saveConversationAsBookmark(conversation, name);
4018 if (callback != null) {
4019 callback.success(conversation);
4020 }
4021 }
4022
4023 @Override
4024 public void onPushFailed() {
4025 archiveConversation(conversation);
4026 if (callback != null) {
4027 callback.error(
4028 R.string.conference_creation_failed,
4029 conversation);
4030 }
4031 }
4032 });
4033 }
4034 });
4035 return true;
4036 } catch (IllegalArgumentException e) {
4037 if (callback != null) {
4038 callback.error(R.string.conference_creation_failed, null);
4039 }
4040 return false;
4041 }
4042 } else {
4043 if (callback != null) {
4044 callback.error(R.string.not_connected_try_again, null);
4045 }
4046 return false;
4047 }
4048 }
4049
4050 public void fetchConferenceConfiguration(final Conversation conversation) {
4051 fetchConferenceConfiguration(conversation, null);
4052 }
4053
4054 public void fetchConferenceConfiguration(
4055 final Conversation conversation, final OnConferenceConfigurationFetched callback) {
4056 final var account = conversation.getAccount();
4057 final var connection = account.getXmppConnection();
4058 if (connection == null) {
4059 return;
4060 }
4061 final var future =
4062 connection
4063 .getManager(DiscoManager.class)
4064 .info(Entity.discoItem(conversation.getJid().asBareJid()), null);
4065 Futures.addCallback(
4066 future,
4067 new FutureCallback<>() {
4068 @Override
4069 public void onSuccess(InfoQuery result) {
4070 final MucOptions mucOptions = conversation.getMucOptions();
4071 final Bookmark bookmark = conversation.getBookmark();
4072 final boolean sameBefore =
4073 StringUtils.equals(
4074 bookmark == null ? null : bookmark.getBookmarkName(),
4075 mucOptions.getName());
4076
4077 final var hadOccupantId = mucOptions.occupantId();
4078 if (mucOptions.updateConfiguration(result)) {
4079 Log.d(
4080 Config.LOGTAG,
4081 account.getJid().asBareJid()
4082 + ": muc configuration changed for "
4083 + conversation.getJid().asBareJid());
4084 updateConversation(conversation);
4085 }
4086
4087 final var hasOccupantId = mucOptions.occupantId();
4088
4089 if (!hadOccupantId && hasOccupantId && mucOptions.online()) {
4090 final var me = mucOptions.getSelf().getFullJid();
4091 Log.d(
4092 Config.LOGTAG,
4093 account.getJid().asBareJid()
4094 + ": gained support for occupant-id in "
4095 + me
4096 + ". resending presence");
4097 final var packet =
4098 mPresenceGenerator.selfPresence(
4099 account,
4100 im.conversations.android.xmpp.model.stanza.Presence
4101 .Availability.ONLINE,
4102 mucOptions.nonanonymous());
4103 packet.setTo(me);
4104 sendPresencePacket(account, packet);
4105 }
4106
4107 if (bookmark != null
4108 && (sameBefore || bookmark.getBookmarkName() == null)) {
4109 if (bookmark.setBookmarkName(
4110 StringUtils.nullOnEmpty(mucOptions.getName()))) {
4111 createBookmark(account, bookmark);
4112 }
4113 }
4114
4115 if (callback != null) {
4116 callback.onConferenceConfigurationFetched(conversation);
4117 }
4118
4119 updateConversationUi();
4120 }
4121
4122 @Override
4123 public void onFailure(@NonNull Throwable throwable) {
4124 if (throwable instanceof TimeoutException) {
4125 Log.d(
4126 Config.LOGTAG,
4127 account.getJid().asBareJid()
4128 + ": received timeout waiting for conference"
4129 + " configuration fetch");
4130 } else if (throwable instanceof IqErrorException errorResponseException) {
4131 if (callback != null) {
4132 callback.onFetchFailed(
4133 conversation,
4134 errorResponseException.getResponse().getErrorCondition());
4135 }
4136 }
4137 }
4138 },
4139 MoreExecutors.directExecutor());
4140 }
4141
4142 public void pushNodeConfiguration(
4143 Account account,
4144 final String node,
4145 final Bundle options,
4146 final OnConfigurationPushed callback) {
4147 pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
4148 }
4149
4150 public void pushNodeConfiguration(
4151 Account account,
4152 final Jid jid,
4153 final String node,
4154 final Bundle options,
4155 final OnConfigurationPushed callback) {
4156 Log.d(Config.LOGTAG, "pushing node configuration");
4157 sendIqPacket(
4158 account,
4159 mIqGenerator.requestPubsubConfiguration(jid, node),
4160 responseToRequest -> {
4161 if (responseToRequest.getType() == Iq.Type.RESULT) {
4162 Element pubsub =
4163 responseToRequest.findChild(
4164 "pubsub", "http://jabber.org/protocol/pubsub#owner");
4165 Element configuration =
4166 pubsub == null ? null : pubsub.findChild("configure");
4167 Element x =
4168 configuration == null
4169 ? null
4170 : configuration.findChild("x", Namespace.DATA);
4171 if (x != null) {
4172 final Data data = Data.parse(x);
4173 data.submit(options);
4174 sendIqPacket(
4175 account,
4176 mIqGenerator.publishPubsubConfiguration(jid, node, data),
4177 responseToPublish -> {
4178 if (responseToPublish.getType() == Iq.Type.RESULT
4179 && callback != null) {
4180 Log.d(
4181 Config.LOGTAG,
4182 account.getJid().asBareJid()
4183 + ": successfully changed node"
4184 + " configuration for node "
4185 + node);
4186 callback.onPushSucceeded();
4187 } else if (responseToPublish.getType() == Iq.Type.ERROR
4188 && callback != null) {
4189 callback.onPushFailed();
4190 }
4191 });
4192 } else if (callback != null) {
4193 callback.onPushFailed();
4194 }
4195 } else if (responseToRequest.getType() == Iq.Type.ERROR && callback != null) {
4196 callback.onPushFailed();
4197 }
4198 });
4199 }
4200
4201 public void pushConferenceConfiguration(
4202 final Conversation conversation,
4203 final Bundle options,
4204 final OnConfigurationPushed callback) {
4205 if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
4206 conversation.setAttribute("accept_non_anonymous", true);
4207 updateConversation(conversation);
4208 }
4209 if (options.containsKey("muc#roomconfig_moderatedroom")) {
4210 final boolean moderated = "1".equals(options.getString("muc#roomconfig_moderatedroom"));
4211 options.putString("members_by_default", moderated ? "0" : "1");
4212 }
4213 if (options.containsKey("muc#roomconfig_allowpm")) {
4214 // ejabberd :-/
4215 final boolean allow = "anyone".equals(options.getString("muc#roomconfig_allowpm"));
4216 options.putString("allow_private_messages", allow ? "1" : "0");
4217 options.putString("allow_private_messages_from_visitors", allow ? "anyone" : "nobody");
4218 }
4219 final var account = conversation.getAccount();
4220 final Iq request = new Iq(Iq.Type.GET);
4221 request.setTo(conversation.getJid().asBareJid());
4222 request.query("http://jabber.org/protocol/muc#owner");
4223 sendIqPacket(
4224 account,
4225 request,
4226 response -> {
4227 if (response.getType() == Iq.Type.RESULT) {
4228 final Data data =
4229 Data.parse(response.query().findChild("x", Namespace.DATA));
4230 data.submit(options);
4231 final Iq set = new Iq(Iq.Type.SET);
4232 set.setTo(conversation.getJid().asBareJid());
4233 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
4234 sendIqPacket(
4235 account,
4236 set,
4237 packet -> {
4238 if (callback != null) {
4239 if (packet.getType() == Iq.Type.RESULT) {
4240 callback.onPushSucceeded();
4241 } else {
4242 Log.d(Config.LOGTAG, "failed: " + packet);
4243 callback.onPushFailed();
4244 }
4245 }
4246 });
4247 } else {
4248 if (callback != null) {
4249 callback.onPushFailed();
4250 }
4251 }
4252 });
4253 }
4254
4255 public void pushSubjectToConference(final Conversation conference, final String subject) {
4256 final var packet =
4257 this.getMessageGenerator()
4258 .conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
4259 this.sendMessagePacket(conference.getAccount(), packet);
4260 }
4261
4262 public void changeAffiliationInConference(
4263 final Conversation conference,
4264 Jid user,
4265 final MucOptions.Affiliation affiliation,
4266 final OnAffiliationChanged callback) {
4267 final Jid jid = user.asBareJid();
4268 final Iq request =
4269 this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
4270 sendIqPacket(
4271 conference.getAccount(),
4272 request,
4273 (response) -> {
4274 if (response.getType() == Iq.Type.RESULT) {
4275 final var mucOptions = conference.getMucOptions();
4276 mucOptions.changeAffiliation(jid, affiliation);
4277 getAvatarService().clear(mucOptions);
4278 if (callback != null) {
4279 callback.onAffiliationChangedSuccessful(jid);
4280 } else {
4281 Log.d(
4282 Config.LOGTAG,
4283 "changed affiliation of " + user + " to " + affiliation);
4284 }
4285 } else if (callback != null) {
4286 callback.onAffiliationChangeFailed(
4287 jid, R.string.could_not_change_affiliation);
4288 } else {
4289 Log.d(Config.LOGTAG, "unable to change affiliation");
4290 }
4291 });
4292 }
4293
4294 public void changeRoleInConference(
4295 final Conversation conference, final String nick, MucOptions.Role role) {
4296 final var account = conference.getAccount();
4297 final Iq request = this.mIqGenerator.changeRole(conference, nick, role.toString());
4298 sendIqPacket(
4299 account,
4300 request,
4301 (packet) -> {
4302 if (packet.getType() != Iq.Type.RESULT) {
4303 Log.d(
4304 Config.LOGTAG,
4305 account.getJid().asBareJid() + " unable to change role of " + nick);
4306 }
4307 });
4308 }
4309
4310 public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
4311 final Iq request = new Iq(Iq.Type.SET);
4312 request.setTo(conversation.getJid().asBareJid());
4313 request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
4314 sendIqPacket(
4315 conversation.getAccount(),
4316 request,
4317 response -> {
4318 if (response.getType() == Iq.Type.RESULT) {
4319 if (callback != null) {
4320 callback.onRoomDestroySucceeded();
4321 }
4322 } else if (response.getType() == Iq.Type.ERROR) {
4323 if (callback != null) {
4324 callback.onRoomDestroyFailed();
4325 }
4326 }
4327 });
4328 }
4329
4330 private void disconnect(final Account account, boolean force) {
4331 final XmppConnection connection = account.getXmppConnection();
4332 if (connection == null) {
4333 return;
4334 }
4335 if (!force) {
4336 final List<Conversation> conversations = getConversations();
4337 for (Conversation conversation : conversations) {
4338 if (conversation.getAccount() == account) {
4339 if (conversation.getMode() == Conversation.MODE_MULTI) {
4340 leaveMuc(conversation, true);
4341 }
4342 }
4343 }
4344 sendOfflinePresence(account);
4345 }
4346 connection.disconnect(force);
4347 }
4348
4349 @Override
4350 public IBinder onBind(Intent intent) {
4351 return mBinder;
4352 }
4353
4354 public void updateMessage(Message message) {
4355 updateMessage(message, true);
4356 }
4357
4358 public void updateMessage(Message message, boolean includeBody) {
4359 databaseBackend.updateMessage(message, includeBody);
4360 updateConversationUi();
4361 }
4362
4363 public void createMessageAsync(final Message message) {
4364 mDatabaseWriterExecutor.execute(() -> databaseBackend.createMessage(message));
4365 }
4366
4367 public void updateMessage(Message message, String uuid) {
4368 if (!databaseBackend.updateMessage(message, uuid)) {
4369 Log.e(Config.LOGTAG, "error updated message in DB after edit");
4370 }
4371 updateConversationUi();
4372 }
4373
4374 public void createContact(final Contact contact) {
4375 createContact(contact, null);
4376 }
4377
4378 public void createContact(final Contact contact, final String preAuth) {
4379 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
4380 contact.setOption(Contact.Options.ASKING);
4381 final var connection = contact.getAccount().getXmppConnection();
4382 connection.getManager(RosterManager.class).addRosterItem(contact, preAuth);
4383 }
4384
4385 public void deleteContactOnServer(final Contact contact) {
4386 final var connection = contact.getAccount().getXmppConnection();
4387 connection.getManager(RosterManager.class).deleteRosterItem(contact);
4388 }
4389
4390 public void publishMucAvatar(
4391 final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
4392 new Thread(
4393 () -> {
4394 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
4395 final int size = Config.AVATAR_SIZE;
4396 final Avatar avatar =
4397 getFileBackend().getPepAvatar(image, size, format);
4398 if (avatar != null) {
4399 if (!getFileBackend().save(avatar)) {
4400 callback.onAvatarPublicationFailed(
4401 R.string.error_saving_avatar);
4402 return;
4403 }
4404 avatar.owner = conversation.getJid().asBareJid();
4405 publishMucAvatar(conversation, avatar, callback);
4406 } else {
4407 callback.onAvatarPublicationFailed(
4408 R.string.error_publish_avatar_converting);
4409 }
4410 })
4411 .start();
4412 }
4413
4414 public void publishAvatarAsync(
4415 final Account account,
4416 final Uri image,
4417 final boolean open,
4418 final OnAvatarPublication callback) {
4419 new Thread(() -> publishAvatar(account, image, open, callback)).start();
4420 }
4421
4422 private void publishAvatar(
4423 final Account account,
4424 final Uri image,
4425 final boolean open,
4426 final OnAvatarPublication callback) {
4427 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
4428 final int size = Config.AVATAR_SIZE;
4429 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
4430 if (avatar != null) {
4431 if (!getFileBackend().save(avatar)) {
4432 Log.d(Config.LOGTAG, "unable to save vcard");
4433 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
4434 return;
4435 }
4436 publishAvatar(account, avatar, open, callback);
4437 } else {
4438 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
4439 }
4440 }
4441
4442 private void publishMucAvatar(
4443 Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
4444 final var account = conversation.getAccount();
4445 final Iq retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
4446 sendIqPacket(
4447 account,
4448 retrieve,
4449 (response) -> {
4450 boolean itemNotFound =
4451 response.getType() == Iq.Type.ERROR
4452 && response.hasChild("error")
4453 && response.findChild("error").hasChild("item-not-found");
4454 if (response.getType() == Iq.Type.RESULT || itemNotFound) {
4455 Element vcard = response.findChild("vCard", "vcard-temp");
4456 if (vcard == null) {
4457 vcard = new Element("vCard", "vcard-temp");
4458 }
4459 Element photo = vcard.findChild("PHOTO");
4460 if (photo == null) {
4461 photo = vcard.addChild("PHOTO");
4462 }
4463 photo.clearChildren();
4464 photo.addChild("TYPE").setContent(avatar.type);
4465 photo.addChild("BINVAL").setContent(avatar.image);
4466 final Iq publication = new Iq(Iq.Type.SET);
4467 publication.setTo(conversation.getJid().asBareJid());
4468 publication.addChild(vcard);
4469 sendIqPacket(
4470 account,
4471 publication,
4472 (publicationResponse) -> {
4473 if (publicationResponse.getType() == Iq.Type.RESULT) {
4474 callback.onAvatarPublicationSucceeded();
4475 } else {
4476 Log.d(
4477 Config.LOGTAG,
4478 "failed to publish vcard "
4479 + publicationResponse.getErrorCondition());
4480 callback.onAvatarPublicationFailed(
4481 R.string.error_publish_avatar_server_reject);
4482 }
4483 });
4484 } else {
4485 Log.d(Config.LOGTAG, "failed to request vcard " + response);
4486 callback.onAvatarPublicationFailed(
4487 R.string.error_publish_avatar_no_server_support);
4488 }
4489 });
4490 }
4491
4492 public void publishAvatar(
4493 final Account account,
4494 final Avatar avatar,
4495 final boolean open,
4496 final OnAvatarPublication callback) {
4497 final Bundle options;
4498 if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
4499 options = open ? PublishOptions.openAccess() : PublishOptions.presenceAccess();
4500 } else {
4501 options = null;
4502 }
4503 publishAvatar(account, avatar, options, true, callback);
4504 }
4505
4506 public void publishAvatar(
4507 Account account,
4508 final Avatar avatar,
4509 final Bundle options,
4510 final boolean retry,
4511 final OnAvatarPublication callback) {
4512 Log.d(
4513 Config.LOGTAG,
4514 account.getJid().asBareJid() + ": publishing avatar. options=" + options);
4515 final Iq packet = this.mIqGenerator.publishAvatar(avatar, options);
4516 this.sendIqPacket(
4517 account,
4518 packet,
4519 result -> {
4520 if (result.getType() == Iq.Type.RESULT) {
4521 publishAvatarMetadata(account, avatar, options, true, callback);
4522 } else if (retry && PublishOptions.preconditionNotMet(result)) {
4523 pushNodeConfiguration(
4524 account,
4525 Namespace.AVATAR_DATA,
4526 options,
4527 new OnConfigurationPushed() {
4528 @Override
4529 public void onPushSucceeded() {
4530 Log.d(
4531 Config.LOGTAG,
4532 account.getJid().asBareJid()
4533 + ": changed node configuration for avatar"
4534 + " node");
4535 publishAvatar(account, avatar, options, false, callback);
4536 }
4537
4538 @Override
4539 public void onPushFailed() {
4540 Log.d(
4541 Config.LOGTAG,
4542 account.getJid().asBareJid()
4543 + ": unable to change node configuration"
4544 + " for avatar node");
4545 publishAvatar(account, avatar, null, false, callback);
4546 }
4547 });
4548 } else {
4549 Element error = result.findChild("error");
4550 Log.d(
4551 Config.LOGTAG,
4552 account.getJid().asBareJid()
4553 + ": server rejected avatar "
4554 + (avatar.size / 1024)
4555 + "KiB "
4556 + (error != null ? error.toString() : ""));
4557 if (callback != null) {
4558 callback.onAvatarPublicationFailed(
4559 R.string.error_publish_avatar_server_reject);
4560 }
4561 }
4562 });
4563 }
4564
4565 public void publishAvatarMetadata(
4566 Account account,
4567 final Avatar avatar,
4568 final Bundle options,
4569 final boolean retry,
4570 final OnAvatarPublication callback) {
4571 final Iq packet =
4572 XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
4573 sendIqPacket(
4574 account,
4575 packet,
4576 result -> {
4577 if (result.getType() == Iq.Type.RESULT) {
4578 if (account.setAvatar(avatar.getFilename())) {
4579 getAvatarService().clear(account);
4580 databaseBackend.updateAccount(account);
4581 notifyAccountAvatarHasChanged(account);
4582 }
4583 Log.d(
4584 Config.LOGTAG,
4585 account.getJid().asBareJid()
4586 + ": published avatar "
4587 + (avatar.size / 1024)
4588 + "KiB");
4589 if (callback != null) {
4590 callback.onAvatarPublicationSucceeded();
4591 }
4592 } else if (retry && PublishOptions.preconditionNotMet(result)) {
4593 pushNodeConfiguration(
4594 account,
4595 Namespace.AVATAR_METADATA,
4596 options,
4597 new OnConfigurationPushed() {
4598 @Override
4599 public void onPushSucceeded() {
4600 Log.d(
4601 Config.LOGTAG,
4602 account.getJid().asBareJid()
4603 + ": changed node configuration for avatar"
4604 + " meta data node");
4605 publishAvatarMetadata(
4606 account, avatar, options, false, callback);
4607 }
4608
4609 @Override
4610 public void onPushFailed() {
4611 Log.d(
4612 Config.LOGTAG,
4613 account.getJid().asBareJid()
4614 + ": unable to change node configuration"
4615 + " for avatar meta data node");
4616 publishAvatarMetadata(
4617 account, avatar, null, false, callback);
4618 }
4619 });
4620 } else {
4621 if (callback != null) {
4622 callback.onAvatarPublicationFailed(
4623 R.string.error_publish_avatar_server_reject);
4624 }
4625 }
4626 });
4627 }
4628
4629 public void republishAvatarIfNeeded(final Account account) {
4630 if (account.getAxolotlService().isPepBroken()) {
4631 Log.d(
4632 Config.LOGTAG,
4633 account.getJid().asBareJid()
4634 + ": skipping republication of avatar because pep is broken");
4635 return;
4636 }
4637 final Iq packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4638 this.sendIqPacket(
4639 account,
4640 packet,
4641 new Consumer<Iq>() {
4642
4643 private Avatar parseAvatar(final Iq packet) {
4644 final var pubsub = packet.getExtension(PubSub.class);
4645 if (pubsub == null) {
4646 return null;
4647 }
4648 final var items = pubsub.getItems();
4649 if (items == null) {
4650 return null;
4651 }
4652 final var item = items.getFirstItemWithId(Metadata.class);
4653 if (item == null) {
4654 return null;
4655 }
4656 return Avatar.parseMetadata(item.getKey(), item.getValue());
4657 }
4658
4659 private boolean errorIsItemNotFound(Iq packet) {
4660 Element error = packet.findChild("error");
4661 return packet.getType() == Iq.Type.ERROR
4662 && error != null
4663 && error.hasChild("item-not-found");
4664 }
4665
4666 @Override
4667 public void accept(final Iq packet) {
4668 if (packet.getType() == Iq.Type.RESULT || errorIsItemNotFound(packet)) {
4669 final Avatar serverAvatar = parseAvatar(packet);
4670 if (serverAvatar == null && account.getAvatar() != null) {
4671 final Avatar avatar =
4672 fileBackend.getStoredPepAvatar(account.getAvatar());
4673 if (avatar != null) {
4674 Log.d(
4675 Config.LOGTAG,
4676 account.getJid().asBareJid()
4677 + ": avatar on server was null. republishing");
4678 // publishing as 'open' - old server (that requires
4679 // republication) likely doesn't support access models anyway
4680 publishAvatar(
4681 account,
4682 fileBackend.getStoredPepAvatar(account.getAvatar()),
4683 true,
4684 null);
4685 } else {
4686 Log.e(
4687 Config.LOGTAG,
4688 account.getJid().asBareJid()
4689 + ": error rereading avatar");
4690 }
4691 }
4692 }
4693 }
4694 });
4695 }
4696
4697 public void cancelAvatarFetches(final Account account) {
4698 synchronized (mInProgressAvatarFetches) {
4699 for (final Iterator<String> iterator = mInProgressAvatarFetches.iterator();
4700 iterator.hasNext(); ) {
4701 final String KEY = iterator.next();
4702 if (KEY.startsWith(account.getJid().asBareJid() + "_")) {
4703 iterator.remove();
4704 }
4705 }
4706 }
4707 }
4708
4709 public void fetchAvatar(Account account, Avatar avatar) {
4710 fetchAvatar(account, avatar, null);
4711 }
4712
4713 public void fetchAvatar(
4714 Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4715 final String KEY = generateFetchKey(account, avatar);
4716 synchronized (this.mInProgressAvatarFetches) {
4717 if (mInProgressAvatarFetches.add(KEY)) {
4718 switch (avatar.origin) {
4719 case PEP:
4720 this.mInProgressAvatarFetches.add(KEY);
4721 fetchAvatarPep(account, avatar, callback);
4722 break;
4723 case VCARD:
4724 this.mInProgressAvatarFetches.add(KEY);
4725 fetchAvatarVcard(account, avatar, callback);
4726 break;
4727 }
4728 } else if (avatar.origin == Avatar.Origin.PEP) {
4729 mOmittedPepAvatarFetches.add(KEY);
4730 } else {
4731 Log.d(
4732 Config.LOGTAG,
4733 account.getJid().asBareJid()
4734 + ": already fetching "
4735 + avatar.origin
4736 + " avatar for "
4737 + avatar.owner);
4738 }
4739 }
4740 }
4741
4742 private void fetchAvatarPep(
4743 final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4744 final Iq packet = this.mIqGenerator.retrievePepAvatar(avatar);
4745 sendIqPacket(
4746 account,
4747 packet,
4748 (result) -> {
4749 synchronized (mInProgressAvatarFetches) {
4750 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
4751 }
4752 final String ERROR =
4753 account.getJid().asBareJid()
4754 + ": fetching avatar for "
4755 + avatar.owner
4756 + " failed ";
4757 if (result.getType() == Iq.Type.RESULT) {
4758 avatar.image = IqParser.avatarData(result);
4759 if (avatar.image != null) {
4760 if (getFileBackend().save(avatar)) {
4761 if (account.getJid().asBareJid().equals(avatar.owner)) {
4762 if (account.setAvatar(avatar.getFilename())) {
4763 databaseBackend.updateAccount(account);
4764 }
4765 getAvatarService().clear(account);
4766 updateConversationUi();
4767 updateAccountUi();
4768 } else {
4769 final Contact contact =
4770 account.getRoster().getContact(avatar.owner);
4771 contact.setAvatar(avatar);
4772 account.getXmppConnection()
4773 .getManager(RosterManager.class)
4774 .writeToDatabaseAsync();
4775 getAvatarService().clear(contact);
4776 updateConversationUi();
4777 updateRosterUi();
4778 }
4779 if (callback != null) {
4780 callback.success(avatar);
4781 }
4782 Log.d(
4783 Config.LOGTAG,
4784 account.getJid().asBareJid()
4785 + ": successfully fetched pep avatar for "
4786 + avatar.owner);
4787 return;
4788 }
4789 } else {
4790
4791 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
4792 }
4793 } else {
4794 Element error = result.findChild("error");
4795 if (error == null) {
4796 Log.d(Config.LOGTAG, ERROR + "(server error)");
4797 } else {
4798 Log.d(Config.LOGTAG, ERROR + error);
4799 }
4800 }
4801 if (callback != null) {
4802 callback.error(0, null);
4803 }
4804 });
4805 }
4806
4807 private void fetchAvatarVcard(
4808 final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4809 final Iq packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
4810 this.sendIqPacket(
4811 account,
4812 packet,
4813 response -> {
4814 final boolean previouslyOmittedPepFetch;
4815 synchronized (mInProgressAvatarFetches) {
4816 final String KEY = generateFetchKey(account, avatar);
4817 mInProgressAvatarFetches.remove(KEY);
4818 previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
4819 }
4820 if (response.getType() == Iq.Type.RESULT) {
4821 Element vCard = response.findChild("vCard", "vcard-temp");
4822 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
4823 String image = photo != null ? photo.findChildContent("BINVAL") : null;
4824 if (image != null) {
4825 avatar.image = image;
4826 if (getFileBackend().save(avatar)) {
4827 Log.d(
4828 Config.LOGTAG,
4829 account.getJid().asBareJid()
4830 + ": successfully fetched vCard avatar for "
4831 + avatar.owner
4832 + " omittedPep="
4833 + previouslyOmittedPepFetch);
4834 if (avatar.owner.isBareJid()) {
4835 if (account.getJid().asBareJid().equals(avatar.owner)
4836 && account.getAvatar() == null) {
4837 Log.d(
4838 Config.LOGTAG,
4839 account.getJid().asBareJid()
4840 + ": had no avatar. replacing with vcard");
4841 account.setAvatar(avatar.getFilename());
4842 databaseBackend.updateAccount(account);
4843 getAvatarService().clear(account);
4844 updateAccountUi();
4845 } else {
4846 final Contact contact =
4847 account.getRoster().getContact(avatar.owner);
4848 contact.setAvatar(avatar, previouslyOmittedPepFetch);
4849 account.getXmppConnection()
4850 .getManager(RosterManager.class)
4851 .writeToDatabaseAsync();
4852 getAvatarService().clear(contact);
4853 updateRosterUi();
4854 }
4855 updateConversationUi();
4856 } else {
4857 Conversation conversation =
4858 find(account, avatar.owner.asBareJid());
4859 if (conversation != null
4860 && conversation.getMode() == Conversation.MODE_MULTI) {
4861 MucOptions.User user =
4862 conversation
4863 .getMucOptions()
4864 .findUserByFullJid(avatar.owner);
4865 if (user != null) {
4866 if (user.setAvatar(avatar)) {
4867 getAvatarService().clear(user);
4868 updateConversationUi();
4869 updateMucRosterUi();
4870 }
4871 if (user.getRealJid() != null) {
4872 Contact contact =
4873 account.getRoster()
4874 .getContact(user.getRealJid());
4875 contact.setAvatar(avatar);
4876 account.getXmppConnection()
4877 .getManager(RosterManager.class)
4878 .writeToDatabaseAsync();
4879 getAvatarService().clear(contact);
4880 updateRosterUi();
4881 }
4882 }
4883 }
4884 }
4885 }
4886 }
4887 }
4888 });
4889 }
4890
4891 public void checkForAvatar(final Account account, final UiCallback<Avatar> callback) {
4892 final Iq packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4893 this.sendIqPacket(
4894 account,
4895 packet,
4896 response -> {
4897 if (response.getType() != Iq.Type.RESULT) {
4898 callback.error(0, null);
4899 }
4900 final var pubsub = packet.getExtension(PubSub.class);
4901 if (pubsub == null) {
4902 callback.error(0, null);
4903 return;
4904 }
4905 final var items = pubsub.getItems();
4906 if (items == null) {
4907 callback.error(0, null);
4908 return;
4909 }
4910 final var item = items.getFirstItemWithId(Metadata.class);
4911 if (item == null) {
4912 callback.error(0, null);
4913 return;
4914 }
4915 final var avatar = Avatar.parseMetadata(item.getKey(), item.getValue());
4916 if (avatar == null) {
4917 callback.error(0, null);
4918 return;
4919 }
4920 avatar.owner = account.getJid().asBareJid();
4921 if (fileBackend.isAvatarCached(avatar)) {
4922 if (account.setAvatar(avatar.getFilename())) {
4923 databaseBackend.updateAccount(account);
4924 }
4925 getAvatarService().clear(account);
4926 callback.success(avatar);
4927 } else {
4928 fetchAvatarPep(account, avatar, callback);
4929 }
4930 });
4931 }
4932
4933 public void notifyAccountAvatarHasChanged(final Account account) {
4934 final XmppConnection connection = account.getXmppConnection();
4935 // this was bookmark conversion for a bit which doesn't make sense
4936 if (connection.getManager(AvatarManager.class).hasPepToVCardConversion()) {
4937 Log.d(
4938 Config.LOGTAG,
4939 account.getJid().asBareJid()
4940 + ": avatar changed. resending presence to online group chats");
4941 for (Conversation conversation : conversations) {
4942 if (conversation.getAccount() == account
4943 && conversation.getMode() == Conversational.MODE_MULTI) {
4944 final MucOptions mucOptions = conversation.getMucOptions();
4945 if (mucOptions.online()) {
4946 final var packet =
4947 mPresenceGenerator.selfPresence(
4948 account,
4949 im.conversations.android.xmpp.model.stanza.Presence
4950 .Availability.ONLINE,
4951 mucOptions.nonanonymous());
4952 packet.setTo(mucOptions.getSelf().getFullJid());
4953 connection.sendPresencePacket(packet);
4954 }
4955 }
4956 }
4957 }
4958 }
4959
4960 public void updateConversation(final Conversation conversation) {
4961 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
4962 }
4963
4964 public void reconnectAccount(
4965 final Account account, final boolean force, final boolean interactive) {
4966 synchronized (account) {
4967 final XmppConnection connection = account.getXmppConnection();
4968 final boolean hasInternet = hasInternetConnection();
4969 if (account.isConnectionEnabled() && hasInternet) {
4970 if (!force) {
4971 disconnect(account, false);
4972 }
4973 Thread thread = new Thread(connection);
4974 connection.setInteractive(interactive);
4975 connection.prepareNewConnection();
4976 connection.interrupt();
4977 thread.start();
4978 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
4979 } else {
4980 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
4981 connection.getManager(RosterManager.class).clearPresences();
4982 connection.resetEverything();
4983 final AxolotlService axolotlService = account.getAxolotlService();
4984 if (axolotlService != null) {
4985 axolotlService.resetBrokenness();
4986 }
4987 if (!hasInternet) {
4988 // TODO should this go via XmppConnection.setStatusAndTriggerProcessor()?
4989 account.setStatus(Account.State.NO_INTERNET);
4990 }
4991 }
4992 }
4993 }
4994
4995 public void reconnectAccountInBackground(final Account account) {
4996 new Thread(() -> reconnectAccount(account, false, true)).start();
4997 }
4998
4999 public void invite(final Conversation conversation, final Jid contact) {
5000 Log.d(
5001 Config.LOGTAG,
5002 conversation.getAccount().getJid().asBareJid()
5003 + ": inviting "
5004 + contact
5005 + " to "
5006 + conversation.getJid().asBareJid());
5007 final MucOptions.User user =
5008 conversation.getMucOptions().findUserByRealJid(contact.asBareJid());
5009 if (user == null || user.getAffiliation() == MucOptions.Affiliation.OUTCAST) {
5010 changeAffiliationInConference(conversation, contact, MucOptions.Affiliation.NONE, null);
5011 }
5012 final var packet = mMessageGenerator.invite(conversation, contact);
5013 sendMessagePacket(conversation.getAccount(), packet);
5014 }
5015
5016 public void directInvite(Conversation conversation, Jid jid) {
5017 final var packet = mMessageGenerator.directInvite(conversation, jid);
5018 sendMessagePacket(conversation.getAccount(), packet);
5019 }
5020
5021 public void resetSendingToWaiting(Account account) {
5022 for (Conversation conversation : getConversations()) {
5023 if (conversation.getAccount() == account) {
5024 conversation.findUnsentTextMessages(
5025 message -> markMessage(message, Message.STATUS_WAITING));
5026 }
5027 }
5028 }
5029
5030 public Message markMessage(
5031 final Account account, final Jid recipient, final String uuid, final int status) {
5032 return markMessage(account, recipient, uuid, status, null);
5033 }
5034
5035 public Message markMessage(
5036 final Account account,
5037 final Jid recipient,
5038 final String uuid,
5039 final int status,
5040 String errorMessage) {
5041 if (uuid == null) {
5042 return null;
5043 }
5044 for (Conversation conversation : getConversations()) {
5045 if (conversation.getJid().asBareJid().equals(recipient)
5046 && conversation.getAccount() == account) {
5047 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
5048 if (message != null) {
5049 markMessage(message, status, errorMessage);
5050 }
5051 return message;
5052 }
5053 }
5054 return null;
5055 }
5056
5057 public boolean markMessage(
5058 final Conversation conversation,
5059 final String uuid,
5060 final int status,
5061 final String serverMessageId) {
5062 return markMessage(conversation, uuid, status, serverMessageId, null);
5063 }
5064
5065 public boolean markMessage(
5066 final Conversation conversation,
5067 final String uuid,
5068 final int status,
5069 final String serverMessageId,
5070 final LocalizedContent body) {
5071 if (uuid == null) {
5072 return false;
5073 } else {
5074 final Message message = conversation.findSentMessageWithUuid(uuid);
5075 if (message != null) {
5076 if (message.getServerMsgId() == null) {
5077 message.setServerMsgId(serverMessageId);
5078 }
5079 if (message.getEncryption() == Message.ENCRYPTION_NONE
5080 && message.isTypeText()
5081 && isBodyModified(message, body)) {
5082 message.setBody(body.content);
5083 if (body.count > 1) {
5084 message.setBodyLanguage(body.language);
5085 }
5086 markMessage(message, status, null, true);
5087 } else {
5088 markMessage(message, status);
5089 }
5090 return true;
5091 } else {
5092 return false;
5093 }
5094 }
5095 }
5096
5097 private static boolean isBodyModified(final Message message, final LocalizedContent body) {
5098 if (body == null || body.content == null) {
5099 return false;
5100 }
5101 return !body.content.equals(message.getBody());
5102 }
5103
5104 public void markMessage(Message message, int status) {
5105 markMessage(message, status, null);
5106 }
5107
5108 public void markMessage(final Message message, final int status, final String errorMessage) {
5109 markMessage(message, status, errorMessage, false);
5110 }
5111
5112 public void markMessage(
5113 final Message message,
5114 final int status,
5115 final String errorMessage,
5116 final boolean includeBody) {
5117 final int oldStatus = message.getStatus();
5118 if (status == Message.STATUS_SEND_FAILED
5119 && (oldStatus == Message.STATUS_SEND_RECEIVED
5120 || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
5121 return;
5122 }
5123 if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
5124 return;
5125 }
5126 message.setErrorMessage(errorMessage);
5127 message.setStatus(status);
5128 databaseBackend.updateMessage(message, includeBody);
5129 updateConversationUi();
5130 if (oldStatus != status && status == Message.STATUS_SEND_FAILED) {
5131 mNotificationService.pushFailedDelivery(message);
5132 }
5133 }
5134
5135 private SharedPreferences getPreferences() {
5136 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
5137 }
5138
5139 public long getAutomaticMessageDeletionDate() {
5140 final long timeout =
5141 getLongPreference(
5142 AppSettings.AUTOMATIC_MESSAGE_DELETION,
5143 R.integer.automatic_message_deletion);
5144 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
5145 }
5146
5147 public long getLongPreference(String name, @IntegerRes int res) {
5148 long defaultValue = getResources().getInteger(res);
5149 try {
5150 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
5151 } catch (NumberFormatException e) {
5152 return defaultValue;
5153 }
5154 }
5155
5156 public boolean getBooleanPreference(String name, @BoolRes int res) {
5157 return getPreferences().getBoolean(name, getResources().getBoolean(res));
5158 }
5159
5160 public boolean confirmMessages() {
5161 return appSettings.isConfirmMessages();
5162 }
5163
5164 public boolean allowMessageCorrection() {
5165 return appSettings.isAllowMessageCorrection();
5166 }
5167
5168 public boolean sendChatStates() {
5169 return getBooleanPreference("chat_states", R.bool.chat_states);
5170 }
5171
5172 public boolean useTorToConnect() {
5173 return appSettings.isUseTor();
5174 }
5175
5176 public boolean broadcastLastActivity() {
5177 return appSettings.isBroadcastLastActivity();
5178 }
5179
5180 public int unreadCount() {
5181 int count = 0;
5182 for (Conversation conversation : getConversations()) {
5183 count += conversation.unreadCount();
5184 }
5185 return count;
5186 }
5187
5188 private <T> List<T> threadSafeList(Set<T> set) {
5189 synchronized (LISTENER_LOCK) {
5190 return set.isEmpty() ? Collections.emptyList() : new ArrayList<>(set);
5191 }
5192 }
5193
5194 public void showErrorToastInUi(int resId) {
5195 for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
5196 listener.onShowErrorToast(resId);
5197 }
5198 }
5199
5200 public void updateConversationUi() {
5201 for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
5202 listener.onConversationUpdate();
5203 }
5204 }
5205
5206 public void notifyJingleRtpConnectionUpdate(
5207 final Account account,
5208 final Jid with,
5209 final String sessionId,
5210 final RtpEndUserState state) {
5211 for (OnJingleRtpConnectionUpdate listener :
5212 threadSafeList(this.onJingleRtpConnectionUpdate)) {
5213 listener.onJingleRtpConnectionUpdate(account, with, sessionId, state);
5214 }
5215 }
5216
5217 public void notifyJingleRtpConnectionUpdate(
5218 CallIntegration.AudioDevice selectedAudioDevice,
5219 Set<CallIntegration.AudioDevice> availableAudioDevices) {
5220 for (OnJingleRtpConnectionUpdate listener :
5221 threadSafeList(this.onJingleRtpConnectionUpdate)) {
5222 listener.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
5223 }
5224 }
5225
5226 public void updateAccountUi() {
5227 for (final OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
5228 listener.onAccountUpdate();
5229 }
5230 }
5231
5232 public void updateRosterUi() {
5233 for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
5234 listener.onRosterUpdate();
5235 }
5236 }
5237
5238 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
5239 if (mOnCaptchaRequested.size() > 0) {
5240 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
5241 Bitmap scaled =
5242 Bitmap.createScaledBitmap(
5243 captcha,
5244 (int) (captcha.getWidth() * metrics.scaledDensity),
5245 (int) (captcha.getHeight() * metrics.scaledDensity),
5246 false);
5247 for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
5248 listener.onCaptchaRequested(account, id, data, scaled);
5249 }
5250 return true;
5251 }
5252 return false;
5253 }
5254
5255 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
5256 for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
5257 listener.OnUpdateBlocklist(status);
5258 }
5259 }
5260
5261 public void updateMucRosterUi() {
5262 for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
5263 listener.onMucRosterUpdate();
5264 }
5265 }
5266
5267 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
5268 for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
5269 listener.onKeyStatusUpdated(report);
5270 }
5271 }
5272
5273 public Account findAccountByJid(final Jid jid) {
5274 for (final Account account : this.accounts) {
5275 if (account.getJid().asBareJid().equals(jid.asBareJid())) {
5276 return account;
5277 }
5278 }
5279 return null;
5280 }
5281
5282 public Account findAccountByUuid(final String uuid) {
5283 for (Account account : this.accounts) {
5284 if (account.getUuid().equals(uuid)) {
5285 return account;
5286 }
5287 }
5288 return null;
5289 }
5290
5291 public Conversation findConversationByUuid(String uuid) {
5292 for (Conversation conversation : getConversations()) {
5293 if (conversation.getUuid().equals(uuid)) {
5294 return conversation;
5295 }
5296 }
5297 return null;
5298 }
5299
5300 public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
5301 List<Conversation> findings = new ArrayList<>();
5302 for (Conversation c : getConversations()) {
5303 if (c.getAccount().isEnabled()
5304 && c.getJid().asBareJid().equals(xmppUri.getJid())
5305 && ((c.getMode() == Conversational.MODE_MULTI)
5306 == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
5307 findings.add(c);
5308 }
5309 }
5310 return findings.size() == 1 ? findings.get(0) : null;
5311 }
5312
5313 public boolean markRead(final Conversation conversation, boolean dismiss) {
5314 return markRead(conversation, null, dismiss).size() > 0;
5315 }
5316
5317 public void markRead(final Conversation conversation) {
5318 markRead(conversation, null, true);
5319 }
5320
5321 public List<Message> markRead(
5322 final Conversation conversation, String upToUuid, boolean dismiss) {
5323 if (dismiss) {
5324 mNotificationService.clear(conversation);
5325 }
5326 final List<Message> readMessages = conversation.markRead(upToUuid);
5327 if (readMessages.size() > 0) {
5328 Runnable runnable =
5329 () -> {
5330 for (Message message : readMessages) {
5331 databaseBackend.updateMessage(message, false);
5332 }
5333 };
5334 mDatabaseWriterExecutor.execute(runnable);
5335 updateConversationUi();
5336 updateUnreadCountBadge();
5337 return readMessages;
5338 } else {
5339 return readMessages;
5340 }
5341 }
5342
5343 public synchronized void updateUnreadCountBadge() {
5344 int count = unreadCount();
5345 if (unreadCount != count) {
5346 Log.d(Config.LOGTAG, "update unread count to " + count);
5347 if (count > 0) {
5348 ShortcutBadger.applyCount(getApplicationContext(), count);
5349 } else {
5350 ShortcutBadger.removeCount(getApplicationContext());
5351 }
5352 unreadCount = count;
5353 }
5354 }
5355
5356 public void sendReadMarker(final Conversation conversation, final String upToUuid) {
5357 final boolean isPrivateAndNonAnonymousMuc =
5358 conversation.getMode() == Conversation.MODE_MULTI
5359 && conversation.isPrivateAndNonAnonymous();
5360 final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
5361 if (readMessages.isEmpty()) {
5362 return;
5363 }
5364 final var account = conversation.getAccount();
5365 final var connection = account.getXmppConnection();
5366 updateConversationUi();
5367 final var last =
5368 Iterables.getLast(
5369 Collections2.filter(
5370 readMessages,
5371 m ->
5372 !m.isPrivateMessage()
5373 && m.getStatus() == Message.STATUS_RECEIVED),
5374 null);
5375 if (last == null) {
5376 return;
5377 }
5378
5379 final boolean sendDisplayedMarker =
5380 confirmMessages()
5381 && (last.trusted() || isPrivateAndNonAnonymousMuc)
5382 && last.getRemoteMsgId() != null
5383 && (last.markable || isPrivateAndNonAnonymousMuc);
5384 final boolean serverAssist =
5385 connection != null && connection.getFeatures().mdsServerAssist();
5386
5387 final String stanzaId = last.getServerMsgId();
5388
5389 if (sendDisplayedMarker && serverAssist) {
5390 final var mdsDisplayed = mIqGenerator.mdsDisplayed(stanzaId, conversation);
5391 final var packet = mMessageGenerator.confirm(last);
5392 packet.addChild(mdsDisplayed);
5393 if (!last.isPrivateMessage()) {
5394 packet.setTo(packet.getTo().asBareJid());
5395 }
5396 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server assisted " + packet);
5397 this.sendMessagePacket(account, packet);
5398 } else {
5399 publishMds(last);
5400 // read markers will be sent after MDS to flush the CSI stanza queue
5401 if (sendDisplayedMarker) {
5402 Log.d(
5403 Config.LOGTAG,
5404 conversation.getAccount().getJid().asBareJid()
5405 + ": sending displayed marker to "
5406 + last.getCounterpart().toString());
5407 final var packet = mMessageGenerator.confirm(last);
5408 this.sendMessagePacket(account, packet);
5409 }
5410 }
5411 }
5412
5413 private void publishMds(@Nullable final Message message) {
5414 final String stanzaId = message == null ? null : message.getServerMsgId();
5415 if (Strings.isNullOrEmpty(stanzaId)) {
5416 return;
5417 }
5418 final Conversation conversation;
5419 final var conversational = message.getConversation();
5420 if (conversational instanceof Conversation c) {
5421 conversation = c;
5422 } else {
5423 return;
5424 }
5425 final var account = conversation.getAccount();
5426 final var connection = account.getXmppConnection();
5427 if (connection == null || !connection.getFeatures().mds()) {
5428 return;
5429 }
5430 final Jid itemId;
5431 if (message.isPrivateMessage()) {
5432 itemId = message.getCounterpart();
5433 } else {
5434 itemId = conversation.getJid().asBareJid();
5435 }
5436 Log.d(Config.LOGTAG, "publishing mds for " + itemId + "/" + stanzaId);
5437 publishMds(account, itemId, stanzaId, conversation);
5438 }
5439
5440 private void publishMds(
5441 final Account account,
5442 final Jid itemId,
5443 final String stanzaId,
5444 final Conversation conversation) {
5445 final var item = mIqGenerator.mdsDisplayed(stanzaId, conversation);
5446 pushNodeAndEnforcePublishOptions(
5447 account,
5448 Namespace.MDS_DISPLAYED,
5449 item,
5450 itemId.toString(),
5451 PublishOptions.persistentWhitelistAccessMaxItems());
5452 }
5453
5454 public boolean sendReactions(final Message message, final Collection<String> reactions) {
5455 if (message.getConversation() instanceof Conversation conversation) {
5456 final var isPrivateMessage = message.isPrivateMessage();
5457 final Jid reactTo;
5458 final boolean typeGroupChat;
5459 final String reactToId;
5460 final Collection<Reaction> combinedReactions;
5461 if (conversation.getMode() == Conversational.MODE_MULTI && !isPrivateMessage) {
5462 final var mucOptions = conversation.getMucOptions();
5463 if (!mucOptions.participating()) {
5464 Log.e(Config.LOGTAG, "not participating in MUC");
5465 return false;
5466 }
5467 final var self = mucOptions.getSelf();
5468 final String occupantId = self.getOccupantId();
5469 if (Strings.isNullOrEmpty(occupantId)) {
5470 Log.e(Config.LOGTAG, "occupant id not found for reaction in MUC");
5471 return false;
5472 }
5473 final var existingRaw =
5474 ImmutableSet.copyOf(
5475 Collections2.transform(message.getReactions(), r -> r.reaction));
5476 final var reactionsAsExistingVariants =
5477 ImmutableSet.copyOf(
5478 Collections2.transform(
5479 reactions, r -> Emoticons.existingVariant(r, existingRaw)));
5480 if (!reactions.equals(reactionsAsExistingVariants)) {
5481 Log.d(Config.LOGTAG, "modified reactions to existing variants");
5482 }
5483 reactToId = message.getServerMsgId();
5484 reactTo = conversation.getJid().asBareJid();
5485 typeGroupChat = true;
5486 combinedReactions =
5487 Reaction.withOccupantId(
5488 message.getReactions(),
5489 reactionsAsExistingVariants,
5490 false,
5491 self.getFullJid(),
5492 conversation.getAccount().getJid(),
5493 occupantId);
5494 } else {
5495 if (message.isCarbon() || message.getStatus() == Message.STATUS_RECEIVED) {
5496 reactToId = message.getRemoteMsgId();
5497 } else {
5498 reactToId = message.getUuid();
5499 }
5500 typeGroupChat = false;
5501 if (isPrivateMessage) {
5502 reactTo = message.getCounterpart();
5503 } else {
5504 reactTo = conversation.getJid().asBareJid();
5505 }
5506 combinedReactions =
5507 Reaction.withFrom(
5508 message.getReactions(),
5509 reactions,
5510 false,
5511 conversation.getAccount().getJid());
5512 }
5513 if (reactTo == null || Strings.isNullOrEmpty(reactToId)) {
5514 Log.e(Config.LOGTAG, "could not find id to react to");
5515 return false;
5516 }
5517 final var reactionMessage =
5518 mMessageGenerator.reaction(reactTo, typeGroupChat, reactToId, reactions);
5519 sendMessagePacket(conversation.getAccount(), reactionMessage);
5520 message.setReactions(combinedReactions);
5521 updateMessage(message, false);
5522 return true;
5523 } else {
5524 return false;
5525 }
5526 }
5527
5528 public MemorizingTrustManager getMemorizingTrustManager() {
5529 return this.mMemorizingTrustManager;
5530 }
5531
5532 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
5533 this.mMemorizingTrustManager = trustManager;
5534 }
5535
5536 public void updateMemorizingTrustManager() {
5537 final MemorizingTrustManager trustManager;
5538 if (appSettings.isTrustSystemCAStore()) {
5539 trustManager = new MemorizingTrustManager(getApplicationContext());
5540 } else {
5541 trustManager = new MemorizingTrustManager(getApplicationContext(), null);
5542 }
5543 setMemorizingTrustManager(trustManager);
5544 }
5545
5546 public LruCache<String, Bitmap> getBitmapCache() {
5547 return this.mBitmapCache;
5548 }
5549
5550 public Collection<String> getKnownHosts() {
5551 final Set<String> hosts = new HashSet<>();
5552 for (final Account account : getAccounts()) {
5553 hosts.add(account.getServer());
5554 for (final Contact contact : account.getRoster().getContacts()) {
5555 if (contact.showInRoster()) {
5556 final String server = contact.getServer();
5557 if (server != null) {
5558 hosts.add(server);
5559 }
5560 }
5561 }
5562 }
5563 if (Config.QUICKSY_DOMAIN != null) {
5564 hosts.remove(
5565 Config.QUICKSY_DOMAIN
5566 .toString()); // we only want to show this when we type a e164
5567 // number
5568 }
5569 if (Config.MAGIC_CREATE_DOMAIN != null) {
5570 hosts.add(Config.MAGIC_CREATE_DOMAIN);
5571 }
5572 return hosts;
5573 }
5574
5575 public Collection<String> getKnownConferenceHosts() {
5576 final Set<String> mucServers = new HashSet<>();
5577 for (final Account account : accounts) {
5578 if (account.getXmppConnection() != null) {
5579 mucServers.addAll(account.getXmppConnection().getMucServers());
5580 for (final Bookmark bookmark : account.getBookmarks()) {
5581 final Jid jid = bookmark.getJid();
5582 final String s = jid == null ? null : jid.getDomain().toString();
5583 if (s != null) {
5584 mucServers.add(s);
5585 }
5586 }
5587 }
5588 }
5589 return mucServers;
5590 }
5591
5592 public void sendMessagePacket(
5593 final Account account,
5594 final im.conversations.android.xmpp.model.stanza.Message packet) {
5595 final XmppConnection connection = account.getXmppConnection();
5596 if (connection != null) {
5597 connection.sendMessagePacket(packet);
5598 }
5599 }
5600
5601 public void sendPresencePacket(
5602 final Account account,
5603 final im.conversations.android.xmpp.model.stanza.Presence packet) {
5604 final XmppConnection connection = account.getXmppConnection();
5605 if (connection != null) {
5606 connection.sendPresencePacket(packet);
5607 }
5608 }
5609
5610 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
5611 final XmppConnection connection = account.getXmppConnection();
5612 if (connection == null) {
5613 return;
5614 }
5615 connection.sendCreateAccountWithCaptchaPacket(id, data);
5616 }
5617
5618 public ListenableFuture<Iq> sendIqPacket(final Account account, final Iq request) {
5619 final XmppConnection connection = account.getXmppConnection();
5620 if (connection == null) {
5621 return Futures.immediateFailedFuture(new TimeoutException());
5622 }
5623 return connection.sendIqPacket(request);
5624 }
5625
5626 public void sendIqPacket(final Account account, final Iq packet, final Consumer<Iq> callback) {
5627 final XmppConnection connection = account.getXmppConnection();
5628 if (connection != null) {
5629 connection.sendIqPacket(packet, callback);
5630 } else if (callback != null) {
5631 callback.accept(Iq.TIMEOUT);
5632 }
5633 }
5634
5635 public void sendPresence(final Account account) {
5636 sendPresence(account, checkListeners() && broadcastLastActivity());
5637 }
5638
5639 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
5640 final im.conversations.android.xmpp.model.stanza.Presence.Availability status;
5641 if (manuallyChangePresence()) {
5642 status = account.getPresenceStatus();
5643 } else {
5644 status = getTargetPresence();
5645 }
5646 final var packet = mPresenceGenerator.selfPresence(account, status);
5647 if (mLastActivity > 0 && includeIdleTimestamp) {
5648 long since =
5649 Math.min(mLastActivity, System.currentTimeMillis()); // don't send future dates
5650 packet.addChild("idle", Namespace.IDLE)
5651 .setAttribute("since", AbstractGenerator.getTimestamp(since));
5652 }
5653 sendPresencePacket(account, packet);
5654 }
5655
5656 private void deactivateGracePeriod() {
5657 for (Account account : getAccounts()) {
5658 account.deactivateGracePeriod();
5659 }
5660 }
5661
5662 public void refreshAllPresences() {
5663 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
5664 for (Account account : getAccounts()) {
5665 if (account.isConnectionEnabled()) {
5666 sendPresence(account, includeIdleTimestamp);
5667 }
5668 }
5669 }
5670
5671 private void refreshAllFcmTokens() {
5672 for (Account account : getAccounts()) {
5673 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
5674 mPushManagementService.registerPushTokenOnServer(account);
5675 }
5676 }
5677 }
5678
5679 private void sendOfflinePresence(final Account account) {
5680 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
5681 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
5682 }
5683
5684 public MessageGenerator getMessageGenerator() {
5685 return this.mMessageGenerator;
5686 }
5687
5688 public PresenceGenerator getPresenceGenerator() {
5689 return this.mPresenceGenerator;
5690 }
5691
5692 public IqGenerator getIqGenerator() {
5693 return this.mIqGenerator;
5694 }
5695
5696 public JingleConnectionManager getJingleConnectionManager() {
5697 return this.mJingleConnectionManager;
5698 }
5699
5700 public boolean hasJingleRtpConnection(final Account account) {
5701 return this.mJingleConnectionManager.hasJingleRtpConnection(account);
5702 }
5703
5704 public MessageArchiveService getMessageArchiveService() {
5705 return this.mMessageArchiveService;
5706 }
5707
5708 public QuickConversationsService getQuickConversationsService() {
5709 return this.mQuickConversationsService;
5710 }
5711
5712 public List<Contact> findContacts(Jid jid, String accountJid) {
5713 ArrayList<Contact> contacts = new ArrayList<>();
5714 for (Account account : getAccounts()) {
5715 if ((account.isEnabled() || accountJid != null)
5716 && (accountJid == null
5717 || accountJid.equals(account.getJid().asBareJid().toString()))) {
5718 Contact contact = account.getRoster().getContactFromContactList(jid);
5719 if (contact != null) {
5720 contacts.add(contact);
5721 }
5722 }
5723 }
5724 return contacts;
5725 }
5726
5727 public Conversation findFirstMuc(Jid jid) {
5728 for (Conversation conversation : getConversations()) {
5729 if (conversation.getAccount().isEnabled()
5730 && conversation.getJid().asBareJid().equals(jid.asBareJid())
5731 && conversation.getMode() == Conversation.MODE_MULTI) {
5732 return conversation;
5733 }
5734 }
5735 return null;
5736 }
5737
5738 public NotificationService getNotificationService() {
5739 return this.mNotificationService;
5740 }
5741
5742 public HttpConnectionManager getHttpConnectionManager() {
5743 return this.mHttpConnectionManager;
5744 }
5745
5746 public void resendFailedMessages(final Message message, final boolean forceP2P) {
5747 message.setTime(System.currentTimeMillis());
5748 markMessage(message, Message.STATUS_WAITING);
5749 this.sendMessage(message, true, false, forceP2P);
5750 if (message.getConversation() instanceof Conversation c) {
5751 c.sort();
5752 }
5753 updateConversationUi();
5754 }
5755
5756 public void clearConversationHistory(final Conversation conversation) {
5757 final long clearDate;
5758 final String reference;
5759 if (conversation.countMessages() > 0) {
5760 Message latestMessage = conversation.getLatestMessage();
5761 clearDate = latestMessage.getTimeSent() + 1000;
5762 reference = latestMessage.getServerMsgId();
5763 } else {
5764 clearDate = System.currentTimeMillis();
5765 reference = null;
5766 }
5767 conversation.clearMessages();
5768 conversation.setHasMessagesLeftOnServer(false); // avoid messages getting loaded through mam
5769 conversation.setLastClearHistory(clearDate, reference);
5770 Runnable runnable =
5771 () -> {
5772 databaseBackend.deleteMessagesInConversation(conversation);
5773 databaseBackend.updateConversation(conversation);
5774 };
5775 mDatabaseWriterExecutor.execute(runnable);
5776 }
5777
5778 public boolean sendBlockRequest(
5779 final Blockable blockable, final boolean reportSpam, final String serverMsgId) {
5780 final var account = blockable.getAccount();
5781 final var connection = account.getXmppConnection();
5782 return connection
5783 .getManager(BlockingManager.class)
5784 .block(blockable, reportSpam, serverMsgId);
5785 }
5786
5787 public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
5788 boolean removed = false;
5789 synchronized (this.conversations) {
5790 boolean domainJid = blockedJid.getLocal() == null;
5791 for (Conversation conversation : this.conversations) {
5792 boolean jidMatches =
5793 (domainJid
5794 && blockedJid
5795 .getDomain()
5796 .equals(conversation.getJid().getDomain()))
5797 || blockedJid.equals(conversation.getJid().asBareJid());
5798 if (conversation.getAccount() == account
5799 && conversation.getMode() == Conversation.MODE_SINGLE
5800 && jidMatches) {
5801 this.conversations.remove(conversation);
5802 markRead(conversation);
5803 conversation.setStatus(Conversation.STATUS_ARCHIVED);
5804 Log.d(
5805 Config.LOGTAG,
5806 account.getJid().asBareJid()
5807 + ": archiving conversation "
5808 + conversation.getJid().asBareJid()
5809 + " because jid was blocked");
5810 updateConversation(conversation);
5811 removed = true;
5812 }
5813 }
5814 }
5815 return removed;
5816 }
5817
5818 public void sendUnblockRequest(final Blockable blockable) {
5819 final var account = blockable.getAccount();
5820 final var connection = account.getXmppConnection();
5821 connection.getManager(BlockingManager.class).unblock(blockable);
5822 }
5823
5824 public void publishDisplayName(final Account account) {
5825 final var connection = account.getXmppConnection();
5826 final String displayName = account.getDisplayName();
5827 mAvatarService.clear(account);
5828 final var future = connection.getManager(NickManager.class).publish(displayName);
5829 Futures.addCallback(
5830 future,
5831 new FutureCallback<Void>() {
5832 @Override
5833 public void onSuccess(Void result) {
5834 Log.d(
5835 Config.LOGTAG,
5836 account.getJid().asBareJid() + ": published User Nick");
5837 }
5838
5839 @Override
5840 public void onFailure(@NonNull Throwable t) {
5841 Log.d(Config.LOGTAG, "could not publish User Nick", t);
5842 }
5843 },
5844 MoreExecutors.directExecutor());
5845 }
5846
5847 public void fetchMamPreferences(final Account account, final OnMamPreferencesFetched callback) {
5848 final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
5849 final Iq request = new Iq(Iq.Type.GET);
5850 request.addChild("prefs", version.namespace);
5851 sendIqPacket(
5852 account,
5853 request,
5854 (packet) -> {
5855 final Element prefs = packet.findChild("prefs", version.namespace);
5856 if (packet.getType() == Iq.Type.RESULT && prefs != null) {
5857 callback.onPreferencesFetched(prefs);
5858 } else {
5859 callback.onPreferencesFetchFailed();
5860 }
5861 });
5862 }
5863
5864 public PushManagementService getPushManagementService() {
5865 return mPushManagementService;
5866 }
5867
5868 public void changeStatus(Account account, PresenceTemplate template, String signature) {
5869 if (!template.getStatusMessage().isEmpty()) {
5870 databaseBackend.insertPresenceTemplate(template);
5871 }
5872 account.setPgpSignature(signature);
5873 account.setPresenceStatus(template.getStatus());
5874 account.setPresenceStatusMessage(template.getStatusMessage());
5875 databaseBackend.updateAccount(account);
5876 sendPresence(account);
5877 }
5878
5879 public List<PresenceTemplate> getPresenceTemplates(Account account) {
5880 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
5881 for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
5882 if (!templates.contains(template)) {
5883 templates.add(0, template);
5884 }
5885 }
5886 return templates;
5887 }
5888
5889 public void saveConversationAsBookmark(final Conversation conversation, final String name) {
5890 final Account account = conversation.getAccount();
5891 final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
5892 final String nick = conversation.getJid().getResource();
5893 if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
5894 bookmark.setNick(nick);
5895 }
5896 if (!TextUtils.isEmpty(name)) {
5897 bookmark.setBookmarkName(name);
5898 }
5899 bookmark.setAutojoin(true);
5900 createBookmark(account, bookmark);
5901 bookmark.setConversation(conversation);
5902 }
5903
5904 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
5905 boolean performedVerification = false;
5906 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
5907 for (XmppUri.Fingerprint fp : fingerprints) {
5908 if (fp.type == XmppUri.FingerprintType.OMEMO) {
5909 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
5910 FingerprintStatus fingerprintStatus =
5911 axolotlService.getFingerprintTrust(fingerprint);
5912 if (fingerprintStatus != null) {
5913 if (!fingerprintStatus.isVerified()) {
5914 performedVerification = true;
5915 axolotlService.setFingerprintTrust(
5916 fingerprint, fingerprintStatus.toVerified());
5917 }
5918 } else {
5919 axolotlService.preVerifyFingerprint(contact, fingerprint);
5920 }
5921 }
5922 }
5923 return performedVerification;
5924 }
5925
5926 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
5927 final AxolotlService axolotlService = account.getAxolotlService();
5928 boolean verifiedSomething = false;
5929 for (XmppUri.Fingerprint fp : fingerprints) {
5930 if (fp.type == XmppUri.FingerprintType.OMEMO) {
5931 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
5932 Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
5933 FingerprintStatus fingerprintStatus =
5934 axolotlService.getFingerprintTrust(fingerprint);
5935 if (fingerprintStatus != null) {
5936 if (!fingerprintStatus.isVerified()) {
5937 axolotlService.setFingerprintTrust(
5938 fingerprint, fingerprintStatus.toVerified());
5939 verifiedSomething = true;
5940 }
5941 } else {
5942 axolotlService.preVerifyFingerprint(account, fingerprint);
5943 verifiedSomething = true;
5944 }
5945 }
5946 }
5947 return verifiedSomething;
5948 }
5949
5950 public ShortcutService getShortcutService() {
5951 return mShortcutService;
5952 }
5953
5954 public void pushMamPreferences(Account account, Element prefs) {
5955 final Iq set = new Iq(Iq.Type.SET);
5956 set.addChild(prefs);
5957 sendIqPacket(account, set, null);
5958 }
5959
5960 public void evictPreview(String uuid) {
5961 if (mBitmapCache.remove(uuid) != null) {
5962 Log.d(Config.LOGTAG, "deleted cached preview");
5963 }
5964 }
5965
5966 public interface OnMamPreferencesFetched {
5967 void onPreferencesFetched(Element prefs);
5968
5969 void onPreferencesFetchFailed();
5970 }
5971
5972 public interface OnAccountCreated {
5973 void onAccountCreated(Account account);
5974
5975 void informUser(int r);
5976 }
5977
5978 public interface OnMoreMessagesLoaded {
5979 void onMoreMessagesLoaded(int count, Conversation conversation);
5980
5981 void informUser(int r);
5982 }
5983
5984 public interface OnAccountPasswordChanged {
5985 void onPasswordChangeSucceeded();
5986
5987 void onPasswordChangeFailed();
5988 }
5989
5990 public interface OnRoomDestroy {
5991 void onRoomDestroySucceeded();
5992
5993 void onRoomDestroyFailed();
5994 }
5995
5996 public interface OnAffiliationChanged {
5997 void onAffiliationChangedSuccessful(Jid jid);
5998
5999 void onAffiliationChangeFailed(Jid jid, int resId);
6000 }
6001
6002 public interface OnConversationUpdate {
6003 void onConversationUpdate();
6004 }
6005
6006 public interface OnJingleRtpConnectionUpdate {
6007 void onJingleRtpConnectionUpdate(
6008 final Account account,
6009 final Jid with,
6010 final String sessionId,
6011 final RtpEndUserState state);
6012
6013 void onAudioDeviceChanged(
6014 CallIntegration.AudioDevice selectedAudioDevice,
6015 Set<CallIntegration.AudioDevice> availableAudioDevices);
6016 }
6017
6018 public interface OnAccountUpdate {
6019 void onAccountUpdate();
6020 }
6021
6022 public interface OnCaptchaRequested {
6023 void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
6024 }
6025
6026 public interface OnRosterUpdate {
6027 void onRosterUpdate();
6028 }
6029
6030 public interface OnMucRosterUpdate {
6031 void onMucRosterUpdate();
6032 }
6033
6034 public interface OnConferenceConfigurationFetched {
6035 void onConferenceConfigurationFetched(Conversation conversation);
6036
6037 void onFetchFailed(Conversation conversation, String errorCondition);
6038 }
6039
6040 public interface OnConferenceJoined {
6041 void onConferenceJoined(Conversation conversation);
6042 }
6043
6044 public interface OnConfigurationPushed {
6045 void onPushSucceeded();
6046
6047 void onPushFailed();
6048 }
6049
6050 public interface OnShowErrorToast {
6051 void onShowErrorToast(int resId);
6052 }
6053
6054 public class XmppConnectionBinder extends Binder {
6055 public XmppConnectionService getService() {
6056 return XmppConnectionService.this;
6057 }
6058 }
6059
6060 private class InternalEventReceiver extends BroadcastReceiver {
6061
6062 @Override
6063 public void onReceive(final Context context, final Intent intent) {
6064 onStartCommand(intent, 0, 0);
6065 }
6066 }
6067
6068 private class RestrictedEventReceiver extends BroadcastReceiver {
6069
6070 private final Collection<String> allowedActions;
6071
6072 private RestrictedEventReceiver(final Collection<String> allowedActions) {
6073 this.allowedActions = allowedActions;
6074 }
6075
6076 @Override
6077 public void onReceive(final Context context, final Intent intent) {
6078 final String action = intent == null ? null : intent.getAction();
6079 if (allowedActions.contains(action)) {
6080 onStartCommand(intent, 0, 0);
6081 } else {
6082 Log.e(Config.LOGTAG, "restricting broadcast of event " + action);
6083 }
6084 }
6085 }
6086
6087 public static class OngoingCall {
6088 public final AbstractJingleConnection.Id id;
6089 public final Set<Media> media;
6090 public final boolean reconnecting;
6091
6092 public OngoingCall(
6093 AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
6094 this.id = id;
6095 this.media = media;
6096 this.reconnecting = reconnecting;
6097 }
6098
6099 @Override
6100 public boolean equals(Object o) {
6101 if (this == o) return true;
6102 if (o == null || getClass() != o.getClass()) return false;
6103 OngoingCall that = (OngoingCall) o;
6104 return reconnecting == that.reconnecting
6105 && Objects.equal(id, that.id)
6106 && Objects.equal(media, that.media);
6107 }
6108
6109 @Override
6110 public int hashCode() {
6111 return Objects.hashCode(id, media, reconnecting);
6112 }
6113 }
6114
6115 public static void toggleForegroundService(final XmppConnectionService service) {
6116 if (service == null) {
6117 return;
6118 }
6119 service.toggleForegroundService();
6120 }
6121
6122 public static void toggleForegroundService(final ConversationsActivity activity) {
6123 if (activity == null) {
6124 return;
6125 }
6126 toggleForegroundService(activity.xmppConnectionService);
6127 }
6128}