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