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