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 // TODO use PingManager
3614 final Jid self = conversation.getMucOptions().getSelf().getFullJid();
3615 final Iq ping = new Iq(Iq.Type.GET);
3616 ping.setTo(self);
3617 ping.addChild("ping", Namespace.PING);
3618 sendIqPacket(
3619 conversation.getAccount(),
3620 ping,
3621 (response) -> {
3622 if (response.getType() == Iq.Type.ERROR) {
3623 final var error = response.getError();
3624 if (error == null
3625 || error.hasChild("service-unavailable")
3626 || error.hasChild("feature-not-implemented")
3627 || error.hasChild("item-not-found")) {
3628 Log.d(
3629 Config.LOGTAG,
3630 account.getJid().asBareJid()
3631 + ": ping to "
3632 + self
3633 + " came back as ignorable error");
3634 } else {
3635 Log.d(
3636 Config.LOGTAG,
3637 account.getJid().asBareJid()
3638 + ": ping to "
3639 + self
3640 + " failed. attempting rejoin");
3641 joinMuc(conversation);
3642 }
3643 } else if (response.getType() == Iq.Type.RESULT) {
3644 Log.d(
3645 Config.LOGTAG,
3646 account.getJid().asBareJid()
3647 + ": ping to "
3648 + self
3649 + " came back fine");
3650 }
3651 synchronized (account.inProgressConferencePings) {
3652 account.inProgressConferencePings.remove(conversation);
3653 }
3654 });
3655 }
3656
3657 public void joinMuc(Conversation conversation) {
3658 joinMuc(conversation, null, false);
3659 }
3660
3661 public void joinMuc(Conversation conversation, boolean followedInvite) {
3662 joinMuc(conversation, null, followedInvite);
3663 }
3664
3665 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
3666 joinMuc(conversation, onConferenceJoined, false);
3667 }
3668
3669 private void joinMuc(
3670 final Conversation conversation,
3671 final OnConferenceJoined onConferenceJoined,
3672 final boolean followedInvite) {
3673 final Account account = conversation.getAccount();
3674 synchronized (account.pendingConferenceJoins) {
3675 account.pendingConferenceJoins.remove(conversation);
3676 }
3677 synchronized (account.pendingConferenceLeaves) {
3678 account.pendingConferenceLeaves.remove(conversation);
3679 }
3680 if (account.getStatus() == Account.State.ONLINE) {
3681 synchronized (account.inProgressConferenceJoins) {
3682 account.inProgressConferenceJoins.add(conversation);
3683 }
3684 if (Config.MUC_LEAVE_BEFORE_JOIN) {
3685 sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
3686 }
3687 conversation.resetMucOptions();
3688 if (onConferenceJoined != null) {
3689 conversation.getMucOptions().flagNoAutoPushConfiguration();
3690 }
3691 conversation.setHasMessagesLeftOnServer(false);
3692 fetchConferenceConfiguration(
3693 conversation,
3694 new OnConferenceConfigurationFetched() {
3695
3696 private void join(Conversation conversation) {
3697 Account account = conversation.getAccount();
3698 final MucOptions mucOptions = conversation.getMucOptions();
3699
3700 if (mucOptions.nonanonymous()
3701 && !mucOptions.membersOnly()
3702 && !conversation.getBooleanAttribute(
3703 "accept_non_anonymous", false)) {
3704 synchronized (account.inProgressConferenceJoins) {
3705 account.inProgressConferenceJoins.remove(conversation);
3706 }
3707 mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
3708 updateConversationUi();
3709 if (onConferenceJoined != null) {
3710 onConferenceJoined.onConferenceJoined(conversation);
3711 }
3712 return;
3713 }
3714
3715 final Jid joinJid = mucOptions.getSelf().getFullJid();
3716 Log.d(
3717 Config.LOGTAG,
3718 account.getJid().asBareJid().toString()
3719 + ": joining conversation "
3720 + joinJid.toString());
3721 final var packet =
3722 mPresenceGenerator.selfPresence(
3723 account,
3724 im.conversations.android.xmpp.model.stanza.Presence
3725 .Availability.ONLINE,
3726 mucOptions.nonanonymous()
3727 || onConferenceJoined != null);
3728 packet.setTo(joinJid);
3729 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
3730 if (conversation.getMucOptions().getPassword() != null) {
3731 x.addChild("password").setContent(mucOptions.getPassword());
3732 }
3733
3734 if (mucOptions.mamSupport()) {
3735 // Use MAM instead of the limited muc history to get history
3736 x.addChild("history").setAttribute("maxchars", "0");
3737 } else {
3738 // Fallback to muc history
3739 x.addChild("history")
3740 .setAttribute(
3741 "since",
3742 PresenceGenerator.getTimestamp(
3743 conversation
3744 .getLastMessageTransmitted()
3745 .getTimestamp()));
3746 }
3747 sendPresencePacket(account, packet);
3748 if (onConferenceJoined != null) {
3749 onConferenceJoined.onConferenceJoined(conversation);
3750 }
3751 if (!joinJid.equals(conversation.getJid())) {
3752 conversation.setContactJid(joinJid);
3753 databaseBackend.updateConversation(conversation);
3754 }
3755
3756 if (mucOptions.mamSupport()) {
3757 getMessageArchiveService().catchupMUC(conversation);
3758 }
3759 if (mucOptions.isPrivateAndNonAnonymous()) {
3760 fetchConferenceMembers(conversation);
3761
3762 if (followedInvite) {
3763 final Bookmark bookmark = conversation.getBookmark();
3764 if (bookmark != null) {
3765 if (!bookmark.autojoin()) {
3766 bookmark.setAutojoin(true);
3767 createBookmark(account, bookmark);
3768 }
3769 } else {
3770 saveConversationAsBookmark(conversation, null);
3771 }
3772 }
3773 }
3774 synchronized (account.inProgressConferenceJoins) {
3775 account.inProgressConferenceJoins.remove(conversation);
3776 sendUnsentMessages(conversation);
3777 }
3778 }
3779
3780 @Override
3781 public void onConferenceConfigurationFetched(Conversation conversation) {
3782 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3783 Log.d(
3784 Config.LOGTAG,
3785 account.getJid().asBareJid()
3786 + ": conversation ("
3787 + conversation.getJid()
3788 + ") got archived before IQ result");
3789 return;
3790 }
3791 join(conversation);
3792 }
3793
3794 @Override
3795 public void onFetchFailed(
3796 final Conversation conversation, final String errorCondition) {
3797 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3798 Log.d(
3799 Config.LOGTAG,
3800 account.getJid().asBareJid()
3801 + ": conversation ("
3802 + conversation.getJid()
3803 + ") got archived before IQ result");
3804 return;
3805 }
3806 if ("remote-server-not-found".equals(errorCondition)) {
3807 synchronized (account.inProgressConferenceJoins) {
3808 account.inProgressConferenceJoins.remove(conversation);
3809 }
3810 conversation
3811 .getMucOptions()
3812 .setError(MucOptions.Error.SERVER_NOT_FOUND);
3813 updateConversationUi();
3814 } else {
3815 join(conversation);
3816 fetchConferenceConfiguration(conversation);
3817 }
3818 }
3819 });
3820 updateConversationUi();
3821 } else {
3822 synchronized (account.pendingConferenceJoins) {
3823 account.pendingConferenceJoins.add(conversation);
3824 }
3825 conversation.resetMucOptions();
3826 conversation.setHasMessagesLeftOnServer(false);
3827 updateConversationUi();
3828 }
3829 }
3830
3831 private void fetchConferenceMembers(final Conversation conversation) {
3832 final Account account = conversation.getAccount();
3833 final AxolotlService axolotlService = account.getAxolotlService();
3834 final String[] affiliations = {"member", "admin", "owner"};
3835 final Consumer<Iq> callback =
3836 new Consumer<Iq>() {
3837
3838 private int i = 0;
3839 private boolean success = true;
3840
3841 @Override
3842 public void accept(Iq response) {
3843 final boolean omemoEnabled =
3844 conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
3845 Element query = response.query("http://jabber.org/protocol/muc#admin");
3846 if (response.getType() == Iq.Type.RESULT && query != null) {
3847 for (Element child : query.getChildren()) {
3848 if ("item".equals(child.getName())) {
3849 MucOptions.User user =
3850 AbstractParser.parseItem(conversation, child);
3851 if (!user.realJidMatchesAccount()) {
3852 boolean isNew =
3853 conversation.getMucOptions().updateUser(user);
3854 Contact contact = user.getContact();
3855 if (omemoEnabled
3856 && isNew
3857 && user.getRealJid() != null
3858 && (contact == null
3859 || !contact.mutualPresenceSubscription())
3860 && axolotlService.hasEmptyDeviceList(
3861 user.getRealJid())) {
3862 axolotlService.fetchDeviceIds(user.getRealJid());
3863 }
3864 }
3865 }
3866 }
3867 } else {
3868 success = false;
3869 Log.d(
3870 Config.LOGTAG,
3871 account.getJid().asBareJid()
3872 + ": could not request affiliation "
3873 + affiliations[i]
3874 + " in "
3875 + conversation.getJid().asBareJid());
3876 }
3877 ++i;
3878 if (i >= affiliations.length) {
3879 final var mucOptions = conversation.getMucOptions();
3880 final var members = mucOptions.getMembers(true);
3881 if (success) {
3882 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
3883 boolean changed = false;
3884 for (ListIterator<Jid> iterator = cryptoTargets.listIterator();
3885 iterator.hasNext(); ) {
3886 Jid jid = iterator.next();
3887 if (!members.contains(jid)
3888 && !members.contains(jid.getDomain())) {
3889 iterator.remove();
3890 Log.d(
3891 Config.LOGTAG,
3892 account.getJid().asBareJid()
3893 + ": removed "
3894 + jid
3895 + " from crypto targets of "
3896 + conversation.getName());
3897 changed = true;
3898 }
3899 }
3900 if (changed) {
3901 conversation.setAcceptedCryptoTargets(cryptoTargets);
3902 updateConversation(conversation);
3903 }
3904 }
3905 getAvatarService().clear(mucOptions);
3906 updateMucRosterUi();
3907 updateConversationUi();
3908 }
3909 }
3910 };
3911 for (String affiliation : affiliations) {
3912 sendIqPacket(
3913 account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
3914 }
3915 Log.d(
3916 Config.LOGTAG,
3917 account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
3918 }
3919
3920 public void providePasswordForMuc(final Conversation conversation, final String password) {
3921 if (conversation.getMode() == Conversation.MODE_MULTI) {
3922 conversation.getMucOptions().setPassword(password);
3923 if (conversation.getBookmark() != null) {
3924 final Bookmark bookmark = conversation.getBookmark();
3925 bookmark.setAutojoin(true);
3926 createBookmark(conversation.getAccount(), bookmark);
3927 }
3928 updateConversation(conversation);
3929 joinMuc(conversation);
3930 }
3931 }
3932
3933 public void deleteAvatar(final Account account) {
3934 final AtomicBoolean executed = new AtomicBoolean(false);
3935 final Runnable onDeleted =
3936 () -> {
3937 if (executed.compareAndSet(false, true)) {
3938 account.setAvatar(null);
3939 databaseBackend.updateAccount(account);
3940 getAvatarService().clear(account);
3941 updateAccountUi();
3942 }
3943 };
3944 deleteVcardAvatar(account, onDeleted);
3945 deletePepNode(account, Namespace.AVATAR_DATA);
3946 deletePepNode(account, Namespace.AVATAR_METADATA, onDeleted);
3947 }
3948
3949 public void deletePepNode(final Account account, final String node) {
3950 deletePepNode(account, node, null);
3951 }
3952
3953 private void deletePepNode(final Account account, final String node, final Runnable runnable) {
3954 final Iq request = mIqGenerator.deleteNode(node);
3955 sendIqPacket(
3956 account,
3957 request,
3958 (packet) -> {
3959 if (packet.getType() == Iq.Type.RESULT) {
3960 Log.d(
3961 Config.LOGTAG,
3962 account.getJid().asBareJid()
3963 + ": successfully deleted pep node "
3964 + node);
3965 if (runnable != null) {
3966 runnable.run();
3967 }
3968 } else {
3969 Log.d(
3970 Config.LOGTAG,
3971 account.getJid().asBareJid() + ": failed to delete " + packet);
3972 }
3973 });
3974 }
3975
3976 private void deleteVcardAvatar(final Account account, @NonNull final Runnable runnable) {
3977 final Iq retrieveVcard = mIqGenerator.retrieveVcardAvatar(account.getJid().asBareJid());
3978 sendIqPacket(
3979 account,
3980 retrieveVcard,
3981 (response) -> {
3982 if (response.getType() != Iq.Type.RESULT) {
3983 Log.d(
3984 Config.LOGTAG,
3985 account.getJid().asBareJid() + ": no vCard set. nothing to do");
3986 return;
3987 }
3988 final Element vcard = response.findChild("vCard", "vcard-temp");
3989 if (vcard == null) {
3990 Log.d(
3991 Config.LOGTAG,
3992 account.getJid().asBareJid() + ": no vCard set. nothing to do");
3993 return;
3994 }
3995 Element photo = vcard.findChild("PHOTO");
3996 if (photo == null) {
3997 photo = vcard.addChild("PHOTO");
3998 }
3999 photo.clearChildren();
4000 final Iq publication = new Iq(Iq.Type.SET);
4001 publication.setTo(account.getJid().asBareJid());
4002 publication.addChild(vcard);
4003 sendIqPacket(
4004 account,
4005 publication,
4006 (publicationResponse) -> {
4007 if (publicationResponse.getType() == Iq.Type.RESULT) {
4008 Log.d(
4009 Config.LOGTAG,
4010 account.getJid().asBareJid()
4011 + ": successfully deleted vcard avatar");
4012 runnable.run();
4013 } else {
4014 Log.d(
4015 Config.LOGTAG,
4016 "failed to publish vcard "
4017 + publicationResponse.getErrorCondition());
4018 }
4019 });
4020 });
4021 }
4022
4023 private boolean hasEnabledAccounts() {
4024 if (this.accounts == null) {
4025 return false;
4026 }
4027 for (final Account account : this.accounts) {
4028 if (account.isConnectionEnabled()) {
4029 return true;
4030 }
4031 }
4032 return false;
4033 }
4034
4035 public void getAttachments(
4036 final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
4037 getAttachments(
4038 conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
4039 }
4040
4041 public void getAttachments(
4042 final Account account,
4043 final Jid jid,
4044 final int limit,
4045 final OnMediaLoaded onMediaLoaded) {
4046 getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
4047 }
4048
4049 public void getAttachments(
4050 final String account,
4051 final Jid jid,
4052 final int limit,
4053 final OnMediaLoaded onMediaLoaded) {
4054 new Thread(
4055 () ->
4056 onMediaLoaded.onMediaLoaded(
4057 fileBackend.convertToAttachments(
4058 databaseBackend.getRelativeFilePaths(
4059 account, jid, limit))))
4060 .start();
4061 }
4062
4063 public void persistSelfNick(final MucOptions.User self, final boolean modified) {
4064 final Conversation conversation = self.getConversation();
4065 final Account account = conversation.getAccount();
4066 final Jid full = self.getFullJid();
4067 if (!full.equals(conversation.getJid())) {
4068 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persisting full jid " + full);
4069 conversation.setContactJid(full);
4070 databaseBackend.updateConversation(conversation);
4071 }
4072
4073 final Bookmark bookmark = conversation.getBookmark();
4074 if (bookmark == null || !modified) {
4075 return;
4076 }
4077 final var nick = full.getResource();
4078 final String defaultNick = MucOptions.defaultNick(account);
4079 if (nick.equals(defaultNick) || nick.equals(bookmark.getNick())) {
4080 return;
4081 }
4082 Log.d(
4083 Config.LOGTAG,
4084 account.getJid().asBareJid()
4085 + ": persist nick '"
4086 + full.getResource()
4087 + "' into bookmark for "
4088 + conversation.getJid().asBareJid());
4089 bookmark.setNick(nick);
4090 createBookmark(bookmark.getAccount(), bookmark);
4091 }
4092
4093 public boolean renameInMuc(
4094 final Conversation conversation,
4095 final String nick,
4096 final UiCallback<Conversation> callback) {
4097 final Account account = conversation.getAccount();
4098 final Bookmark bookmark = conversation.getBookmark();
4099 final MucOptions options = conversation.getMucOptions();
4100 final Jid joinJid = options.createJoinJid(nick);
4101 if (joinJid == null) {
4102 return false;
4103 }
4104 if (options.online()) {
4105 options.setOnRenameListener(
4106 new OnRenameListener() {
4107
4108 @Override
4109 public void onSuccess() {
4110 callback.success(conversation);
4111 }
4112
4113 @Override
4114 public void onFailure() {
4115 callback.error(R.string.nick_in_use, conversation);
4116 }
4117 });
4118
4119 final var packet =
4120 mPresenceGenerator.selfPresence(
4121 account,
4122 im.conversations.android.xmpp.model.stanza.Presence.Availability.ONLINE,
4123 options.nonanonymous());
4124 packet.setTo(joinJid);
4125 sendPresencePacket(account, packet);
4126 if (nick.equals(MucOptions.defaultNick(account))
4127 && bookmark != null
4128 && bookmark.getNick() != null) {
4129 Log.d(
4130 Config.LOGTAG,
4131 account.getJid().asBareJid()
4132 + ": removing nick from bookmark for "
4133 + bookmark.getJid());
4134 bookmark.setNick(null);
4135 createBookmark(account, bookmark);
4136 }
4137 } else {
4138 conversation.setContactJid(joinJid);
4139 databaseBackend.updateConversation(conversation);
4140 if (account.getStatus() == Account.State.ONLINE) {
4141 if (bookmark != null) {
4142 bookmark.setNick(nick);
4143 createBookmark(account, bookmark);
4144 }
4145 joinMuc(conversation);
4146 }
4147 }
4148 return true;
4149 }
4150
4151 public void checkMucRequiresRename() {
4152 synchronized (this.conversations) {
4153 for (final Conversation conversation : this.conversations) {
4154 if (conversation.getMode() == Conversational.MODE_MULTI) {
4155 checkMucRequiresRename(conversation);
4156 }
4157 }
4158 }
4159 }
4160
4161 private void checkMucRequiresRename(final Conversation conversation) {
4162 final var options = conversation.getMucOptions();
4163 if (!options.online()) {
4164 return;
4165 }
4166 final var account = conversation.getAccount();
4167 final String current = options.getActualNick();
4168 final String proposed = options.getProposedNickPure();
4169 if (current == null || current.equals(proposed)) {
4170 return;
4171 }
4172 final Jid joinJid = options.createJoinJid(proposed);
4173 Log.d(
4174 Config.LOGTAG,
4175 String.format(
4176 "%s: muc rename required %s (was: %s)",
4177 account.getJid().asBareJid(), joinJid, current));
4178 final var packet =
4179 mPresenceGenerator.selfPresence(
4180 account,
4181 im.conversations.android.xmpp.model.stanza.Presence.Availability.ONLINE,
4182 options.nonanonymous());
4183 packet.setTo(joinJid);
4184 sendPresencePacket(account, packet);
4185 }
4186
4187 public void leaveMuc(Conversation conversation) {
4188 leaveMuc(conversation, false);
4189 }
4190
4191 private void leaveMuc(Conversation conversation, boolean now) {
4192 final Account account = conversation.getAccount();
4193 synchronized (account.pendingConferenceJoins) {
4194 account.pendingConferenceJoins.remove(conversation);
4195 }
4196 synchronized (account.pendingConferenceLeaves) {
4197 account.pendingConferenceLeaves.remove(conversation);
4198 }
4199 if (account.getStatus() == Account.State.ONLINE || now) {
4200 sendPresencePacket(
4201 conversation.getAccount(),
4202 mPresenceGenerator.leave(conversation.getMucOptions()));
4203 conversation.getMucOptions().setOffline();
4204 Bookmark bookmark = conversation.getBookmark();
4205 if (bookmark != null) {
4206 bookmark.setConversation(null);
4207 }
4208 Log.d(
4209 Config.LOGTAG,
4210 conversation.getAccount().getJid().asBareJid()
4211 + ": leaving muc "
4212 + conversation.getJid());
4213 final var connection = account.getXmppConnection();
4214 if (connection != null) {
4215 connection.getManager(DiscoManager.class).clear(conversation.getJid().asBareJid());
4216 }
4217 } else {
4218 synchronized (account.pendingConferenceLeaves) {
4219 account.pendingConferenceLeaves.add(conversation);
4220 }
4221 }
4222 }
4223
4224 public String findConferenceServer(final Account account) {
4225 String server;
4226 if (account.getXmppConnection() != null) {
4227 server = account.getXmppConnection().getMucServer();
4228 if (server != null) {
4229 return server;
4230 }
4231 }
4232 for (Account other : getAccounts()) {
4233 if (other != account && other.getXmppConnection() != null) {
4234 server = other.getXmppConnection().getMucServer();
4235 if (server != null) {
4236 return server;
4237 }
4238 }
4239 }
4240 return null;
4241 }
4242
4243 public void createPublicChannel(
4244 final Account account,
4245 final String name,
4246 final Jid address,
4247 final UiCallback<Conversation> callback) {
4248 joinMuc(
4249 findOrCreateConversation(account, address, true, false, true),
4250 conversation -> {
4251 final Bundle configuration = IqGenerator.defaultChannelConfiguration();
4252 if (!TextUtils.isEmpty(name)) {
4253 configuration.putString("muc#roomconfig_roomname", name);
4254 }
4255 pushConferenceConfiguration(
4256 conversation,
4257 configuration,
4258 new OnConfigurationPushed() {
4259 @Override
4260 public void onPushSucceeded() {
4261 saveConversationAsBookmark(conversation, name);
4262 callback.success(conversation);
4263 }
4264
4265 @Override
4266 public void onPushFailed() {
4267 if (conversation
4268 .getMucOptions()
4269 .getSelf()
4270 .getAffiliation()
4271 .ranks(MucOptions.Affiliation.OWNER)) {
4272 callback.error(
4273 R.string.unable_to_set_channel_configuration,
4274 conversation);
4275 } else {
4276 callback.error(
4277 R.string.joined_an_existing_channel, conversation);
4278 }
4279 }
4280 });
4281 });
4282 }
4283
4284 public boolean createAdhocConference(
4285 final Account account,
4286 final String name,
4287 final Iterable<Jid> jids,
4288 final UiCallback<Conversation> callback) {
4289 Log.d(
4290 Config.LOGTAG,
4291 account.getJid().asBareJid().toString()
4292 + ": creating adhoc conference with "
4293 + jids.toString());
4294 if (account.getStatus() == Account.State.ONLINE) {
4295 try {
4296 String server = findConferenceServer(account);
4297 if (server == null) {
4298 if (callback != null) {
4299 callback.error(R.string.no_conference_server_found, null);
4300 }
4301 return false;
4302 }
4303 final Jid jid = Jid.of(CryptoHelper.pronounceable(), server, null);
4304 final Conversation conversation =
4305 findOrCreateConversation(account, jid, true, false, true);
4306 joinMuc(
4307 conversation,
4308 new OnConferenceJoined() {
4309 @Override
4310 public void onConferenceJoined(final Conversation conversation) {
4311 final Bundle configuration =
4312 IqGenerator.defaultGroupChatConfiguration();
4313 if (!TextUtils.isEmpty(name)) {
4314 configuration.putString("muc#roomconfig_roomname", name);
4315 }
4316 pushConferenceConfiguration(
4317 conversation,
4318 configuration,
4319 new OnConfigurationPushed() {
4320 @Override
4321 public void onPushSucceeded() {
4322 for (Jid invite : jids) {
4323 invite(conversation, invite);
4324 }
4325 for (String resource :
4326 account.getSelfContact()
4327 .getPresences()
4328 .toResourceArray()) {
4329 Jid other =
4330 account.getJid().withResource(resource);
4331 Log.d(
4332 Config.LOGTAG,
4333 account.getJid().asBareJid()
4334 + ": sending direct invite to "
4335 + other);
4336 directInvite(conversation, other);
4337 }
4338 saveConversationAsBookmark(conversation, name);
4339 if (callback != null) {
4340 callback.success(conversation);
4341 }
4342 }
4343
4344 @Override
4345 public void onPushFailed() {
4346 archiveConversation(conversation);
4347 if (callback != null) {
4348 callback.error(
4349 R.string.conference_creation_failed,
4350 conversation);
4351 }
4352 }
4353 });
4354 }
4355 });
4356 return true;
4357 } catch (IllegalArgumentException e) {
4358 if (callback != null) {
4359 callback.error(R.string.conference_creation_failed, null);
4360 }
4361 return false;
4362 }
4363 } else {
4364 if (callback != null) {
4365 callback.error(R.string.not_connected_try_again, null);
4366 }
4367 return false;
4368 }
4369 }
4370
4371 public void fetchConferenceConfiguration(final Conversation conversation) {
4372 fetchConferenceConfiguration(conversation, null);
4373 }
4374
4375 public void fetchConferenceConfiguration(
4376 final Conversation conversation, final OnConferenceConfigurationFetched callback) {
4377 final var account = conversation.getAccount();
4378 final var connection = account.getXmppConnection();
4379 if (connection == null) {
4380 return;
4381 }
4382 final var future =
4383 connection
4384 .getManager(DiscoManager.class)
4385 .info(Entity.discoItem(conversation.getJid().asBareJid()), null);
4386 Futures.addCallback(
4387 future,
4388 new FutureCallback<>() {
4389 @Override
4390 public void onSuccess(InfoQuery result) {
4391 final MucOptions mucOptions = conversation.getMucOptions();
4392 final Bookmark bookmark = conversation.getBookmark();
4393 final boolean sameBefore =
4394 StringUtils.equals(
4395 bookmark == null ? null : bookmark.getBookmarkName(),
4396 mucOptions.getName());
4397
4398 final var hadOccupantId = mucOptions.occupantId();
4399 if (mucOptions.updateConfiguration(result)) {
4400 Log.d(
4401 Config.LOGTAG,
4402 account.getJid().asBareJid()
4403 + ": muc configuration changed for "
4404 + conversation.getJid().asBareJid());
4405 updateConversation(conversation);
4406 }
4407
4408 final var hasOccupantId = mucOptions.occupantId();
4409
4410 if (!hadOccupantId && hasOccupantId && mucOptions.online()) {
4411 final var me = mucOptions.getSelf().getFullJid();
4412 Log.d(
4413 Config.LOGTAG,
4414 account.getJid().asBareJid()
4415 + ": gained support for occupant-id in "
4416 + me
4417 + ". resending presence");
4418 final var packet =
4419 mPresenceGenerator.selfPresence(
4420 account,
4421 im.conversations.android.xmpp.model.stanza.Presence
4422 .Availability.ONLINE,
4423 mucOptions.nonanonymous());
4424 packet.setTo(me);
4425 sendPresencePacket(account, packet);
4426 }
4427
4428 if (bookmark != null
4429 && (sameBefore || bookmark.getBookmarkName() == null)) {
4430 if (bookmark.setBookmarkName(
4431 StringUtils.nullOnEmpty(mucOptions.getName()))) {
4432 createBookmark(account, bookmark);
4433 }
4434 }
4435
4436 if (callback != null) {
4437 callback.onConferenceConfigurationFetched(conversation);
4438 }
4439
4440 updateConversationUi();
4441 }
4442
4443 @Override
4444 public void onFailure(@NonNull Throwable throwable) {
4445 if (throwable instanceof TimeoutException) {
4446 Log.d(
4447 Config.LOGTAG,
4448 account.getJid().asBareJid()
4449 + ": received timeout waiting for conference"
4450 + " configuration fetch");
4451 } else if (throwable
4452 instanceof IqErrorResponseException errorResponseException) {
4453 if (callback != null) {
4454 callback.onFetchFailed(
4455 conversation,
4456 errorResponseException.getResponse().getErrorCondition());
4457 }
4458 }
4459 }
4460 },
4461 MoreExecutors.directExecutor());
4462 }
4463
4464 public void pushNodeConfiguration(
4465 Account account,
4466 final String node,
4467 final Bundle options,
4468 final OnConfigurationPushed callback) {
4469 pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
4470 }
4471
4472 public void pushNodeConfiguration(
4473 Account account,
4474 final Jid jid,
4475 final String node,
4476 final Bundle options,
4477 final OnConfigurationPushed callback) {
4478 Log.d(Config.LOGTAG, "pushing node configuration");
4479 sendIqPacket(
4480 account,
4481 mIqGenerator.requestPubsubConfiguration(jid, node),
4482 responseToRequest -> {
4483 if (responseToRequest.getType() == Iq.Type.RESULT) {
4484 Element pubsub =
4485 responseToRequest.findChild(
4486 "pubsub", "http://jabber.org/protocol/pubsub#owner");
4487 Element configuration =
4488 pubsub == null ? null : pubsub.findChild("configure");
4489 Element x =
4490 configuration == null
4491 ? null
4492 : configuration.findChild("x", Namespace.DATA);
4493 if (x != null) {
4494 final Data data = Data.parse(x);
4495 data.submit(options);
4496 sendIqPacket(
4497 account,
4498 mIqGenerator.publishPubsubConfiguration(jid, node, data),
4499 responseToPublish -> {
4500 if (responseToPublish.getType() == Iq.Type.RESULT
4501 && callback != null) {
4502 Log.d(
4503 Config.LOGTAG,
4504 account.getJid().asBareJid()
4505 + ": successfully changed node"
4506 + " configuration for node "
4507 + node);
4508 callback.onPushSucceeded();
4509 } else if (responseToPublish.getType() == Iq.Type.ERROR
4510 && callback != null) {
4511 callback.onPushFailed();
4512 }
4513 });
4514 } else if (callback != null) {
4515 callback.onPushFailed();
4516 }
4517 } else if (responseToRequest.getType() == Iq.Type.ERROR && callback != null) {
4518 callback.onPushFailed();
4519 }
4520 });
4521 }
4522
4523 public void pushConferenceConfiguration(
4524 final Conversation conversation,
4525 final Bundle options,
4526 final OnConfigurationPushed callback) {
4527 if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
4528 conversation.setAttribute("accept_non_anonymous", true);
4529 updateConversation(conversation);
4530 }
4531 if (options.containsKey("muc#roomconfig_moderatedroom")) {
4532 final boolean moderated = "1".equals(options.getString("muc#roomconfig_moderatedroom"));
4533 options.putString("members_by_default", moderated ? "0" : "1");
4534 }
4535 if (options.containsKey("muc#roomconfig_allowpm")) {
4536 // ejabberd :-/
4537 final boolean allow = "anyone".equals(options.getString("muc#roomconfig_allowpm"));
4538 options.putString("allow_private_messages", allow ? "1" : "0");
4539 options.putString("allow_private_messages_from_visitors", allow ? "anyone" : "nobody");
4540 }
4541 final var account = conversation.getAccount();
4542 final Iq request = new Iq(Iq.Type.GET);
4543 request.setTo(conversation.getJid().asBareJid());
4544 request.query("http://jabber.org/protocol/muc#owner");
4545 sendIqPacket(
4546 account,
4547 request,
4548 response -> {
4549 if (response.getType() == Iq.Type.RESULT) {
4550 final Data data =
4551 Data.parse(response.query().findChild("x", Namespace.DATA));
4552 data.submit(options);
4553 final Iq set = new Iq(Iq.Type.SET);
4554 set.setTo(conversation.getJid().asBareJid());
4555 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
4556 sendIqPacket(
4557 account,
4558 set,
4559 packet -> {
4560 if (callback != null) {
4561 if (packet.getType() == Iq.Type.RESULT) {
4562 callback.onPushSucceeded();
4563 } else {
4564 Log.d(Config.LOGTAG, "failed: " + packet);
4565 callback.onPushFailed();
4566 }
4567 }
4568 });
4569 } else {
4570 if (callback != null) {
4571 callback.onPushFailed();
4572 }
4573 }
4574 });
4575 }
4576
4577 public void pushSubjectToConference(final Conversation conference, final String subject) {
4578 final var packet =
4579 this.getMessageGenerator()
4580 .conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
4581 this.sendMessagePacket(conference.getAccount(), packet);
4582 }
4583
4584 public void changeAffiliationInConference(
4585 final Conversation conference,
4586 Jid user,
4587 final MucOptions.Affiliation affiliation,
4588 final OnAffiliationChanged callback) {
4589 final Jid jid = user.asBareJid();
4590 final Iq request =
4591 this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
4592 sendIqPacket(
4593 conference.getAccount(),
4594 request,
4595 (response) -> {
4596 if (response.getType() == Iq.Type.RESULT) {
4597 final var mucOptions = conference.getMucOptions();
4598 mucOptions.changeAffiliation(jid, affiliation);
4599 getAvatarService().clear(mucOptions);
4600 if (callback != null) {
4601 callback.onAffiliationChangedSuccessful(jid);
4602 } else {
4603 Log.d(
4604 Config.LOGTAG,
4605 "changed affiliation of " + user + " to " + affiliation);
4606 }
4607 } else if (callback != null) {
4608 callback.onAffiliationChangeFailed(
4609 jid, R.string.could_not_change_affiliation);
4610 } else {
4611 Log.d(Config.LOGTAG, "unable to change affiliation");
4612 }
4613 });
4614 }
4615
4616 public void changeRoleInConference(
4617 final Conversation conference, final String nick, MucOptions.Role role) {
4618 final var account = conference.getAccount();
4619 final Iq request = this.mIqGenerator.changeRole(conference, nick, role.toString());
4620 sendIqPacket(
4621 account,
4622 request,
4623 (packet) -> {
4624 if (packet.getType() != Iq.Type.RESULT) {
4625 Log.d(
4626 Config.LOGTAG,
4627 account.getJid().asBareJid() + " unable to change role of " + nick);
4628 }
4629 });
4630 }
4631
4632 public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
4633 final Iq request = new Iq(Iq.Type.SET);
4634 request.setTo(conversation.getJid().asBareJid());
4635 request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
4636 sendIqPacket(
4637 conversation.getAccount(),
4638 request,
4639 response -> {
4640 if (response.getType() == Iq.Type.RESULT) {
4641 if (callback != null) {
4642 callback.onRoomDestroySucceeded();
4643 }
4644 } else if (response.getType() == Iq.Type.ERROR) {
4645 if (callback != null) {
4646 callback.onRoomDestroyFailed();
4647 }
4648 }
4649 });
4650 }
4651
4652 private void disconnect(final Account account, boolean force) {
4653 final XmppConnection connection = account.getXmppConnection();
4654 if (connection == null) {
4655 return;
4656 }
4657 if (!force) {
4658 final List<Conversation> conversations = getConversations();
4659 for (Conversation conversation : conversations) {
4660 if (conversation.getAccount() == account) {
4661 if (conversation.getMode() == Conversation.MODE_MULTI) {
4662 leaveMuc(conversation, true);
4663 }
4664 }
4665 }
4666 sendOfflinePresence(account);
4667 }
4668 connection.disconnect(force);
4669 }
4670
4671 @Override
4672 public IBinder onBind(Intent intent) {
4673 return mBinder;
4674 }
4675
4676 public void updateMessage(Message message) {
4677 updateMessage(message, true);
4678 }
4679
4680 public void updateMessage(Message message, boolean includeBody) {
4681 databaseBackend.updateMessage(message, includeBody);
4682 updateConversationUi();
4683 }
4684
4685 public void createMessageAsync(final Message message) {
4686 mDatabaseWriterExecutor.execute(() -> databaseBackend.createMessage(message));
4687 }
4688
4689 public void updateMessage(Message message, String uuid) {
4690 if (!databaseBackend.updateMessage(message, uuid)) {
4691 Log.e(Config.LOGTAG, "error updated message in DB after edit");
4692 }
4693 updateConversationUi();
4694 }
4695
4696 public void syncDirtyContacts(Account account) {
4697 for (Contact contact : account.getRoster().getContacts()) {
4698 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
4699 pushContactToServer(contact);
4700 }
4701 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
4702 deleteContactOnServer(contact);
4703 }
4704 }
4705 }
4706
4707 public void createContact(final Contact contact, final boolean autoGrant) {
4708 createContact(contact, autoGrant, null);
4709 }
4710
4711 public void createContact(
4712 final Contact contact, final boolean autoGrant, final String preAuth) {
4713 if (autoGrant) {
4714 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
4715 contact.setOption(Contact.Options.ASKING);
4716 }
4717 pushContactToServer(contact, preAuth);
4718 }
4719
4720 public void pushContactToServer(final Contact contact) {
4721 pushContactToServer(contact, null);
4722 }
4723
4724 private void pushContactToServer(final Contact contact, final String preAuth) {
4725 contact.resetOption(Contact.Options.DIRTY_DELETE);
4726 contact.setOption(Contact.Options.DIRTY_PUSH);
4727 final Account account = contact.getAccount();
4728 if (account.getStatus() == Account.State.ONLINE) {
4729 final boolean ask = contact.getOption(Contact.Options.ASKING);
4730 final boolean sendUpdates =
4731 contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
4732 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
4733 final Iq iq = new Iq(Iq.Type.SET);
4734 iq.query(Namespace.ROSTER).addChild(contact.asElement());
4735 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
4736 if (sendUpdates) {
4737 sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
4738 }
4739 if (ask) {
4740 sendPresencePacket(
4741 account, mPresenceGenerator.requestPresenceUpdatesFrom(contact, preAuth));
4742 }
4743 } else {
4744 syncRoster(contact.getAccount());
4745 }
4746 }
4747
4748 public void publishMucAvatar(
4749 final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
4750 new Thread(
4751 () -> {
4752 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
4753 final int size = Config.AVATAR_SIZE;
4754 final Avatar avatar =
4755 getFileBackend().getPepAvatar(image, size, format);
4756 if (avatar != null) {
4757 if (!getFileBackend().save(avatar)) {
4758 callback.onAvatarPublicationFailed(
4759 R.string.error_saving_avatar);
4760 return;
4761 }
4762 avatar.owner = conversation.getJid().asBareJid();
4763 publishMucAvatar(conversation, avatar, callback);
4764 } else {
4765 callback.onAvatarPublicationFailed(
4766 R.string.error_publish_avatar_converting);
4767 }
4768 })
4769 .start();
4770 }
4771
4772 public void publishAvatarAsync(
4773 final Account account,
4774 final Uri image,
4775 final boolean open,
4776 final OnAvatarPublication callback) {
4777 new Thread(() -> publishAvatar(account, image, open, callback)).start();
4778 }
4779
4780 private void publishAvatar(
4781 final Account account,
4782 final Uri image,
4783 final boolean open,
4784 final OnAvatarPublication callback) {
4785 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
4786 final int size = Config.AVATAR_SIZE;
4787 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
4788 if (avatar != null) {
4789 if (!getFileBackend().save(avatar)) {
4790 Log.d(Config.LOGTAG, "unable to save vcard");
4791 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
4792 return;
4793 }
4794 publishAvatar(account, avatar, open, callback);
4795 } else {
4796 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
4797 }
4798 }
4799
4800 private void publishMucAvatar(
4801 Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
4802 final var account = conversation.getAccount();
4803 final Iq retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
4804 sendIqPacket(
4805 account,
4806 retrieve,
4807 (response) -> {
4808 boolean itemNotFound =
4809 response.getType() == Iq.Type.ERROR
4810 && response.hasChild("error")
4811 && response.findChild("error").hasChild("item-not-found");
4812 if (response.getType() == Iq.Type.RESULT || itemNotFound) {
4813 Element vcard = response.findChild("vCard", "vcard-temp");
4814 if (vcard == null) {
4815 vcard = new Element("vCard", "vcard-temp");
4816 }
4817 Element photo = vcard.findChild("PHOTO");
4818 if (photo == null) {
4819 photo = vcard.addChild("PHOTO");
4820 }
4821 photo.clearChildren();
4822 photo.addChild("TYPE").setContent(avatar.type);
4823 photo.addChild("BINVAL").setContent(avatar.image);
4824 final Iq publication = new Iq(Iq.Type.SET);
4825 publication.setTo(conversation.getJid().asBareJid());
4826 publication.addChild(vcard);
4827 sendIqPacket(
4828 account,
4829 publication,
4830 (publicationResponse) -> {
4831 if (publicationResponse.getType() == Iq.Type.RESULT) {
4832 callback.onAvatarPublicationSucceeded();
4833 } else {
4834 Log.d(
4835 Config.LOGTAG,
4836 "failed to publish vcard "
4837 + publicationResponse.getErrorCondition());
4838 callback.onAvatarPublicationFailed(
4839 R.string.error_publish_avatar_server_reject);
4840 }
4841 });
4842 } else {
4843 Log.d(Config.LOGTAG, "failed to request vcard " + response);
4844 callback.onAvatarPublicationFailed(
4845 R.string.error_publish_avatar_no_server_support);
4846 }
4847 });
4848 }
4849
4850 public void publishAvatar(
4851 final Account account,
4852 final Avatar avatar,
4853 final boolean open,
4854 final OnAvatarPublication callback) {
4855 final Bundle options;
4856 if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
4857 options = open ? PublishOptions.openAccess() : PublishOptions.presenceAccess();
4858 } else {
4859 options = null;
4860 }
4861 publishAvatar(account, avatar, options, true, callback);
4862 }
4863
4864 public void publishAvatar(
4865 Account account,
4866 final Avatar avatar,
4867 final Bundle options,
4868 final boolean retry,
4869 final OnAvatarPublication callback) {
4870 Log.d(
4871 Config.LOGTAG,
4872 account.getJid().asBareJid() + ": publishing avatar. options=" + options);
4873 final Iq packet = this.mIqGenerator.publishAvatar(avatar, options);
4874 this.sendIqPacket(
4875 account,
4876 packet,
4877 result -> {
4878 if (result.getType() == Iq.Type.RESULT) {
4879 publishAvatarMetadata(account, avatar, options, true, callback);
4880 } else if (retry && PublishOptions.preconditionNotMet(result)) {
4881 pushNodeConfiguration(
4882 account,
4883 Namespace.AVATAR_DATA,
4884 options,
4885 new OnConfigurationPushed() {
4886 @Override
4887 public void onPushSucceeded() {
4888 Log.d(
4889 Config.LOGTAG,
4890 account.getJid().asBareJid()
4891 + ": changed node configuration for avatar"
4892 + " node");
4893 publishAvatar(account, avatar, options, false, callback);
4894 }
4895
4896 @Override
4897 public void onPushFailed() {
4898 Log.d(
4899 Config.LOGTAG,
4900 account.getJid().asBareJid()
4901 + ": unable to change node configuration"
4902 + " for avatar node");
4903 publishAvatar(account, avatar, null, false, callback);
4904 }
4905 });
4906 } else {
4907 Element error = result.findChild("error");
4908 Log.d(
4909 Config.LOGTAG,
4910 account.getJid().asBareJid()
4911 + ": server rejected avatar "
4912 + (avatar.size / 1024)
4913 + "KiB "
4914 + (error != null ? error.toString() : ""));
4915 if (callback != null) {
4916 callback.onAvatarPublicationFailed(
4917 R.string.error_publish_avatar_server_reject);
4918 }
4919 }
4920 });
4921 }
4922
4923 public void publishAvatarMetadata(
4924 Account account,
4925 final Avatar avatar,
4926 final Bundle options,
4927 final boolean retry,
4928 final OnAvatarPublication callback) {
4929 final Iq packet =
4930 XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
4931 sendIqPacket(
4932 account,
4933 packet,
4934 result -> {
4935 if (result.getType() == Iq.Type.RESULT) {
4936 if (account.setAvatar(avatar.getFilename())) {
4937 getAvatarService().clear(account);
4938 databaseBackend.updateAccount(account);
4939 notifyAccountAvatarHasChanged(account);
4940 }
4941 Log.d(
4942 Config.LOGTAG,
4943 account.getJid().asBareJid()
4944 + ": published avatar "
4945 + (avatar.size / 1024)
4946 + "KiB");
4947 if (callback != null) {
4948 callback.onAvatarPublicationSucceeded();
4949 }
4950 } else if (retry && PublishOptions.preconditionNotMet(result)) {
4951 pushNodeConfiguration(
4952 account,
4953 Namespace.AVATAR_METADATA,
4954 options,
4955 new OnConfigurationPushed() {
4956 @Override
4957 public void onPushSucceeded() {
4958 Log.d(
4959 Config.LOGTAG,
4960 account.getJid().asBareJid()
4961 + ": changed node configuration for avatar"
4962 + " meta data node");
4963 publishAvatarMetadata(
4964 account, avatar, options, false, callback);
4965 }
4966
4967 @Override
4968 public void onPushFailed() {
4969 Log.d(
4970 Config.LOGTAG,
4971 account.getJid().asBareJid()
4972 + ": unable to change node configuration"
4973 + " for avatar meta data node");
4974 publishAvatarMetadata(
4975 account, avatar, null, false, callback);
4976 }
4977 });
4978 } else {
4979 if (callback != null) {
4980 callback.onAvatarPublicationFailed(
4981 R.string.error_publish_avatar_server_reject);
4982 }
4983 }
4984 });
4985 }
4986
4987 public void republishAvatarIfNeeded(final Account account) {
4988 if (account.getAxolotlService().isPepBroken()) {
4989 Log.d(
4990 Config.LOGTAG,
4991 account.getJid().asBareJid()
4992 + ": skipping republication of avatar because pep is broken");
4993 return;
4994 }
4995 final Iq packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4996 this.sendIqPacket(
4997 account,
4998 packet,
4999 new Consumer<Iq>() {
5000
5001 private Avatar parseAvatar(final Iq packet) {
5002 final var pubsub = packet.getExtension(PubSub.class);
5003 if (pubsub == null) {
5004 return null;
5005 }
5006 final var items = pubsub.getItems();
5007 if (items == null) {
5008 return null;
5009 }
5010 final var item = items.getFirstItemWithId(Metadata.class);
5011 if (item == null) {
5012 return null;
5013 }
5014 return Avatar.parseMetadata(item.getKey(), item.getValue());
5015 }
5016
5017 private boolean errorIsItemNotFound(Iq packet) {
5018 Element error = packet.findChild("error");
5019 return packet.getType() == Iq.Type.ERROR
5020 && error != null
5021 && error.hasChild("item-not-found");
5022 }
5023
5024 @Override
5025 public void accept(final Iq packet) {
5026 if (packet.getType() == Iq.Type.RESULT || errorIsItemNotFound(packet)) {
5027 final Avatar serverAvatar = parseAvatar(packet);
5028 if (serverAvatar == null && account.getAvatar() != null) {
5029 final Avatar avatar =
5030 fileBackend.getStoredPepAvatar(account.getAvatar());
5031 if (avatar != null) {
5032 Log.d(
5033 Config.LOGTAG,
5034 account.getJid().asBareJid()
5035 + ": avatar on server was null. republishing");
5036 // publishing as 'open' - old server (that requires
5037 // republication) likely doesn't support access models anyway
5038 publishAvatar(
5039 account,
5040 fileBackend.getStoredPepAvatar(account.getAvatar()),
5041 true,
5042 null);
5043 } else {
5044 Log.e(
5045 Config.LOGTAG,
5046 account.getJid().asBareJid()
5047 + ": error rereading avatar");
5048 }
5049 }
5050 }
5051 }
5052 });
5053 }
5054
5055 public void cancelAvatarFetches(final Account account) {
5056 synchronized (mInProgressAvatarFetches) {
5057 for (final Iterator<String> iterator = mInProgressAvatarFetches.iterator();
5058 iterator.hasNext(); ) {
5059 final String KEY = iterator.next();
5060 if (KEY.startsWith(account.getJid().asBareJid() + "_")) {
5061 iterator.remove();
5062 }
5063 }
5064 }
5065 }
5066
5067 public void fetchAvatar(Account account, Avatar avatar) {
5068 fetchAvatar(account, avatar, null);
5069 }
5070
5071 public void fetchAvatar(
5072 Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
5073 final String KEY = generateFetchKey(account, avatar);
5074 synchronized (this.mInProgressAvatarFetches) {
5075 if (mInProgressAvatarFetches.add(KEY)) {
5076 switch (avatar.origin) {
5077 case PEP:
5078 this.mInProgressAvatarFetches.add(KEY);
5079 fetchAvatarPep(account, avatar, callback);
5080 break;
5081 case VCARD:
5082 this.mInProgressAvatarFetches.add(KEY);
5083 fetchAvatarVcard(account, avatar, callback);
5084 break;
5085 }
5086 } else if (avatar.origin == Avatar.Origin.PEP) {
5087 mOmittedPepAvatarFetches.add(KEY);
5088 } else {
5089 Log.d(
5090 Config.LOGTAG,
5091 account.getJid().asBareJid()
5092 + ": already fetching "
5093 + avatar.origin
5094 + " avatar for "
5095 + avatar.owner);
5096 }
5097 }
5098 }
5099
5100 private void fetchAvatarPep(
5101 final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
5102 final Iq packet = this.mIqGenerator.retrievePepAvatar(avatar);
5103 sendIqPacket(
5104 account,
5105 packet,
5106 (result) -> {
5107 synchronized (mInProgressAvatarFetches) {
5108 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
5109 }
5110 final String ERROR =
5111 account.getJid().asBareJid()
5112 + ": fetching avatar for "
5113 + avatar.owner
5114 + " failed ";
5115 if (result.getType() == Iq.Type.RESULT) {
5116 avatar.image = IqParser.avatarData(result);
5117 if (avatar.image != null) {
5118 if (getFileBackend().save(avatar)) {
5119 if (account.getJid().asBareJid().equals(avatar.owner)) {
5120 if (account.setAvatar(avatar.getFilename())) {
5121 databaseBackend.updateAccount(account);
5122 }
5123 getAvatarService().clear(account);
5124 updateConversationUi();
5125 updateAccountUi();
5126 } else {
5127 final Contact contact =
5128 account.getRoster().getContact(avatar.owner);
5129 contact.setAvatar(avatar);
5130 syncRoster(account);
5131 getAvatarService().clear(contact);
5132 updateConversationUi();
5133 updateRosterUi();
5134 }
5135 if (callback != null) {
5136 callback.success(avatar);
5137 }
5138 Log.d(
5139 Config.LOGTAG,
5140 account.getJid().asBareJid()
5141 + ": successfully fetched pep avatar for "
5142 + avatar.owner);
5143 return;
5144 }
5145 } else {
5146
5147 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
5148 }
5149 } else {
5150 Element error = result.findChild("error");
5151 if (error == null) {
5152 Log.d(Config.LOGTAG, ERROR + "(server error)");
5153 } else {
5154 Log.d(Config.LOGTAG, ERROR + error);
5155 }
5156 }
5157 if (callback != null) {
5158 callback.error(0, null);
5159 }
5160 });
5161 }
5162
5163 private void fetchAvatarVcard(
5164 final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
5165 final Iq packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
5166 this.sendIqPacket(
5167 account,
5168 packet,
5169 response -> {
5170 final boolean previouslyOmittedPepFetch;
5171 synchronized (mInProgressAvatarFetches) {
5172 final String KEY = generateFetchKey(account, avatar);
5173 mInProgressAvatarFetches.remove(KEY);
5174 previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
5175 }
5176 if (response.getType() == Iq.Type.RESULT) {
5177 Element vCard = response.findChild("vCard", "vcard-temp");
5178 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
5179 String image = photo != null ? photo.findChildContent("BINVAL") : null;
5180 if (image != null) {
5181 avatar.image = image;
5182 if (getFileBackend().save(avatar)) {
5183 Log.d(
5184 Config.LOGTAG,
5185 account.getJid().asBareJid()
5186 + ": successfully fetched vCard avatar for "
5187 + avatar.owner
5188 + " omittedPep="
5189 + previouslyOmittedPepFetch);
5190 if (avatar.owner.isBareJid()) {
5191 if (account.getJid().asBareJid().equals(avatar.owner)
5192 && account.getAvatar() == null) {
5193 Log.d(
5194 Config.LOGTAG,
5195 account.getJid().asBareJid()
5196 + ": had no avatar. replacing with vcard");
5197 account.setAvatar(avatar.getFilename());
5198 databaseBackend.updateAccount(account);
5199 getAvatarService().clear(account);
5200 updateAccountUi();
5201 } else {
5202 final Contact contact =
5203 account.getRoster().getContact(avatar.owner);
5204 contact.setAvatar(avatar, previouslyOmittedPepFetch);
5205 syncRoster(account);
5206 getAvatarService().clear(contact);
5207 updateRosterUi();
5208 }
5209 updateConversationUi();
5210 } else {
5211 Conversation conversation =
5212 find(account, avatar.owner.asBareJid());
5213 if (conversation != null
5214 && conversation.getMode() == Conversation.MODE_MULTI) {
5215 MucOptions.User user =
5216 conversation
5217 .getMucOptions()
5218 .findUserByFullJid(avatar.owner);
5219 if (user != null) {
5220 if (user.setAvatar(avatar)) {
5221 getAvatarService().clear(user);
5222 updateConversationUi();
5223 updateMucRosterUi();
5224 }
5225 if (user.getRealJid() != null) {
5226 Contact contact =
5227 account.getRoster()
5228 .getContact(user.getRealJid());
5229 contact.setAvatar(avatar);
5230 syncRoster(account);
5231 getAvatarService().clear(contact);
5232 updateRosterUi();
5233 }
5234 }
5235 }
5236 }
5237 }
5238 }
5239 }
5240 });
5241 }
5242
5243 public void checkForAvatar(final Account account, final UiCallback<Avatar> callback) {
5244 final Iq packet = this.mIqGenerator.retrieveAvatarMetaData(null);
5245 this.sendIqPacket(
5246 account,
5247 packet,
5248 response -> {
5249 if (response.getType() != Iq.Type.RESULT) {
5250 callback.error(0, null);
5251 }
5252 final var pubsub = packet.getExtension(PubSub.class);
5253 if (pubsub == null) {
5254 callback.error(0, null);
5255 return;
5256 }
5257 final var items = pubsub.getItems();
5258 if (items == null) {
5259 callback.error(0, null);
5260 return;
5261 }
5262 final var item = items.getFirstItemWithId(Metadata.class);
5263 if (item == null) {
5264 callback.error(0, null);
5265 return;
5266 }
5267 final var avatar = Avatar.parseMetadata(item.getKey(), item.getValue());
5268 if (avatar == null) {
5269 callback.error(0, null);
5270 return;
5271 }
5272 avatar.owner = account.getJid().asBareJid();
5273 if (fileBackend.isAvatarCached(avatar)) {
5274 if (account.setAvatar(avatar.getFilename())) {
5275 databaseBackend.updateAccount(account);
5276 }
5277 getAvatarService().clear(account);
5278 callback.success(avatar);
5279 } else {
5280 fetchAvatarPep(account, avatar, callback);
5281 }
5282 });
5283 }
5284
5285 public void notifyAccountAvatarHasChanged(final Account account) {
5286 final XmppConnection connection = account.getXmppConnection();
5287 if (connection != null && connection.getFeatures().bookmarksConversion()) {
5288 Log.d(
5289 Config.LOGTAG,
5290 account.getJid().asBareJid()
5291 + ": avatar changed. resending presence to online group chats");
5292 for (Conversation conversation : conversations) {
5293 if (conversation.getAccount() == account
5294 && conversation.getMode() == Conversational.MODE_MULTI) {
5295 final MucOptions mucOptions = conversation.getMucOptions();
5296 if (mucOptions.online()) {
5297 final var packet =
5298 mPresenceGenerator.selfPresence(
5299 account,
5300 im.conversations.android.xmpp.model.stanza.Presence
5301 .Availability.ONLINE,
5302 mucOptions.nonanonymous());
5303 packet.setTo(mucOptions.getSelf().getFullJid());
5304 connection.sendPresencePacket(packet);
5305 }
5306 }
5307 }
5308 }
5309 }
5310
5311 public void deleteContactOnServer(Contact contact) {
5312 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
5313 contact.resetOption(Contact.Options.DIRTY_PUSH);
5314 contact.setOption(Contact.Options.DIRTY_DELETE);
5315 Account account = contact.getAccount();
5316 if (account.getStatus() == Account.State.ONLINE) {
5317 final Iq iq = new Iq(Iq.Type.SET);
5318 Element item = iq.query(Namespace.ROSTER).addChild("item");
5319 item.setAttribute("jid", contact.getJid());
5320 item.setAttribute("subscription", "remove");
5321 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
5322 }
5323 }
5324
5325 public void updateConversation(final Conversation conversation) {
5326 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
5327 }
5328
5329 private void reconnectAccount(
5330 final Account account, final boolean force, final boolean interactive) {
5331 synchronized (account) {
5332 final XmppConnection existingConnection = account.getXmppConnection();
5333 final XmppConnection connection;
5334 if (existingConnection != null) {
5335 connection = existingConnection;
5336 } else if (account.isConnectionEnabled()) {
5337 connection = createConnection(account);
5338 account.setXmppConnection(connection);
5339 } else {
5340 return;
5341 }
5342 final boolean hasInternet = hasInternetConnection();
5343 if (account.isConnectionEnabled() && hasInternet) {
5344 if (!force) {
5345 disconnect(account, false);
5346 }
5347 Thread thread = new Thread(connection);
5348 connection.setInteractive(interactive);
5349 connection.prepareNewConnection();
5350 connection.interrupt();
5351 thread.start();
5352 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
5353 } else {
5354 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
5355 account.getRoster().clearPresences();
5356 connection.resetEverything();
5357 final AxolotlService axolotlService = account.getAxolotlService();
5358 if (axolotlService != null) {
5359 axolotlService.resetBrokenness();
5360 }
5361 if (!hasInternet) {
5362 account.setStatus(Account.State.NO_INTERNET);
5363 }
5364 }
5365 }
5366 }
5367
5368 public void reconnectAccountInBackground(final Account account) {
5369 new Thread(() -> reconnectAccount(account, false, true)).start();
5370 }
5371
5372 public void invite(final Conversation conversation, final Jid contact) {
5373 Log.d(
5374 Config.LOGTAG,
5375 conversation.getAccount().getJid().asBareJid()
5376 + ": inviting "
5377 + contact
5378 + " to "
5379 + conversation.getJid().asBareJid());
5380 final MucOptions.User user =
5381 conversation.getMucOptions().findUserByRealJid(contact.asBareJid());
5382 if (user == null || user.getAffiliation() == MucOptions.Affiliation.OUTCAST) {
5383 changeAffiliationInConference(conversation, contact, MucOptions.Affiliation.NONE, null);
5384 }
5385 final var packet = mMessageGenerator.invite(conversation, contact);
5386 sendMessagePacket(conversation.getAccount(), packet);
5387 }
5388
5389 public void directInvite(Conversation conversation, Jid jid) {
5390 final var packet = mMessageGenerator.directInvite(conversation, jid);
5391 sendMessagePacket(conversation.getAccount(), packet);
5392 }
5393
5394 public void resetSendingToWaiting(Account account) {
5395 for (Conversation conversation : getConversations()) {
5396 if (conversation.getAccount() == account) {
5397 conversation.findUnsentTextMessages(
5398 message -> markMessage(message, Message.STATUS_WAITING));
5399 }
5400 }
5401 }
5402
5403 public Message markMessage(
5404 final Account account, final Jid recipient, final String uuid, final int status) {
5405 return markMessage(account, recipient, uuid, status, null);
5406 }
5407
5408 public Message markMessage(
5409 final Account account,
5410 final Jid recipient,
5411 final String uuid,
5412 final int status,
5413 String errorMessage) {
5414 if (uuid == null) {
5415 return null;
5416 }
5417 for (Conversation conversation : getConversations()) {
5418 if (conversation.getJid().asBareJid().equals(recipient)
5419 && conversation.getAccount() == account) {
5420 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
5421 if (message != null) {
5422 markMessage(message, status, errorMessage);
5423 }
5424 return message;
5425 }
5426 }
5427 return null;
5428 }
5429
5430 public boolean markMessage(
5431 final Conversation conversation,
5432 final String uuid,
5433 final int status,
5434 final String serverMessageId) {
5435 return markMessage(conversation, uuid, status, serverMessageId, null);
5436 }
5437
5438 public boolean markMessage(
5439 final Conversation conversation,
5440 final String uuid,
5441 final int status,
5442 final String serverMessageId,
5443 final LocalizedContent body) {
5444 if (uuid == null) {
5445 return false;
5446 } else {
5447 final Message message = conversation.findSentMessageWithUuid(uuid);
5448 if (message != null) {
5449 if (message.getServerMsgId() == null) {
5450 message.setServerMsgId(serverMessageId);
5451 }
5452 if (message.getEncryption() == Message.ENCRYPTION_NONE
5453 && message.isTypeText()
5454 && isBodyModified(message, body)) {
5455 message.setBody(body.content);
5456 if (body.count > 1) {
5457 message.setBodyLanguage(body.language);
5458 }
5459 markMessage(message, status, null, true);
5460 } else {
5461 markMessage(message, status);
5462 }
5463 return true;
5464 } else {
5465 return false;
5466 }
5467 }
5468 }
5469
5470 private static boolean isBodyModified(final Message message, final LocalizedContent body) {
5471 if (body == null || body.content == null) {
5472 return false;
5473 }
5474 return !body.content.equals(message.getBody());
5475 }
5476
5477 public void markMessage(Message message, int status) {
5478 markMessage(message, status, null);
5479 }
5480
5481 public void markMessage(final Message message, final int status, final String errorMessage) {
5482 markMessage(message, status, errorMessage, false);
5483 }
5484
5485 public void markMessage(
5486 final Message message,
5487 final int status,
5488 final String errorMessage,
5489 final boolean includeBody) {
5490 final int oldStatus = message.getStatus();
5491 if (status == Message.STATUS_SEND_FAILED
5492 && (oldStatus == Message.STATUS_SEND_RECEIVED
5493 || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
5494 return;
5495 }
5496 if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
5497 return;
5498 }
5499 message.setErrorMessage(errorMessage);
5500 message.setStatus(status);
5501 databaseBackend.updateMessage(message, includeBody);
5502 updateConversationUi();
5503 if (oldStatus != status && status == Message.STATUS_SEND_FAILED) {
5504 mNotificationService.pushFailedDelivery(message);
5505 }
5506 }
5507
5508 private SharedPreferences getPreferences() {
5509 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
5510 }
5511
5512 public long getAutomaticMessageDeletionDate() {
5513 final long timeout =
5514 getLongPreference(
5515 AppSettings.AUTOMATIC_MESSAGE_DELETION,
5516 R.integer.automatic_message_deletion);
5517 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
5518 }
5519
5520 public long getLongPreference(String name, @IntegerRes int res) {
5521 long defaultValue = getResources().getInteger(res);
5522 try {
5523 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
5524 } catch (NumberFormatException e) {
5525 return defaultValue;
5526 }
5527 }
5528
5529 public boolean getBooleanPreference(String name, @BoolRes int res) {
5530 return getPreferences().getBoolean(name, getResources().getBoolean(res));
5531 }
5532
5533 public boolean confirmMessages() {
5534 return appSettings.isConfirmMessages();
5535 }
5536
5537 public boolean allowMessageCorrection() {
5538 return appSettings.isAllowMessageCorrection();
5539 }
5540
5541 public boolean sendChatStates() {
5542 return getBooleanPreference("chat_states", R.bool.chat_states);
5543 }
5544
5545 public boolean useTorToConnect() {
5546 return appSettings.isUseTor();
5547 }
5548
5549 public boolean broadcastLastActivity() {
5550 return appSettings.isBroadcastLastActivity();
5551 }
5552
5553 public int unreadCount() {
5554 int count = 0;
5555 for (Conversation conversation : getConversations()) {
5556 count += conversation.unreadCount();
5557 }
5558 return count;
5559 }
5560
5561 private <T> List<T> threadSafeList(Set<T> set) {
5562 synchronized (LISTENER_LOCK) {
5563 return set.isEmpty() ? Collections.emptyList() : new ArrayList<>(set);
5564 }
5565 }
5566
5567 public void showErrorToastInUi(int resId) {
5568 for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
5569 listener.onShowErrorToast(resId);
5570 }
5571 }
5572
5573 public void updateConversationUi() {
5574 for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
5575 listener.onConversationUpdate();
5576 }
5577 }
5578
5579 public void notifyJingleRtpConnectionUpdate(
5580 final Account account,
5581 final Jid with,
5582 final String sessionId,
5583 final RtpEndUserState state) {
5584 for (OnJingleRtpConnectionUpdate listener :
5585 threadSafeList(this.onJingleRtpConnectionUpdate)) {
5586 listener.onJingleRtpConnectionUpdate(account, with, sessionId, state);
5587 }
5588 }
5589
5590 public void notifyJingleRtpConnectionUpdate(
5591 CallIntegration.AudioDevice selectedAudioDevice,
5592 Set<CallIntegration.AudioDevice> availableAudioDevices) {
5593 for (OnJingleRtpConnectionUpdate listener :
5594 threadSafeList(this.onJingleRtpConnectionUpdate)) {
5595 listener.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
5596 }
5597 }
5598
5599 public void updateAccountUi() {
5600 for (final OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
5601 listener.onAccountUpdate();
5602 }
5603 }
5604
5605 public void updateRosterUi() {
5606 for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
5607 listener.onRosterUpdate();
5608 }
5609 }
5610
5611 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
5612 if (mOnCaptchaRequested.size() > 0) {
5613 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
5614 Bitmap scaled =
5615 Bitmap.createScaledBitmap(
5616 captcha,
5617 (int) (captcha.getWidth() * metrics.scaledDensity),
5618 (int) (captcha.getHeight() * metrics.scaledDensity),
5619 false);
5620 for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
5621 listener.onCaptchaRequested(account, id, data, scaled);
5622 }
5623 return true;
5624 }
5625 return false;
5626 }
5627
5628 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
5629 for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
5630 listener.OnUpdateBlocklist(status);
5631 }
5632 }
5633
5634 public void updateMucRosterUi() {
5635 for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
5636 listener.onMucRosterUpdate();
5637 }
5638 }
5639
5640 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
5641 for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
5642 listener.onKeyStatusUpdated(report);
5643 }
5644 }
5645
5646 public Account findAccountByJid(final Jid jid) {
5647 for (final Account account : this.accounts) {
5648 if (account.getJid().asBareJid().equals(jid.asBareJid())) {
5649 return account;
5650 }
5651 }
5652 return null;
5653 }
5654
5655 public Account findAccountByUuid(final String uuid) {
5656 for (Account account : this.accounts) {
5657 if (account.getUuid().equals(uuid)) {
5658 return account;
5659 }
5660 }
5661 return null;
5662 }
5663
5664 public Conversation findConversationByUuid(String uuid) {
5665 for (Conversation conversation : getConversations()) {
5666 if (conversation.getUuid().equals(uuid)) {
5667 return conversation;
5668 }
5669 }
5670 return null;
5671 }
5672
5673 public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
5674 List<Conversation> findings = new ArrayList<>();
5675 for (Conversation c : getConversations()) {
5676 if (c.getAccount().isEnabled()
5677 && c.getJid().asBareJid().equals(xmppUri.getJid())
5678 && ((c.getMode() == Conversational.MODE_MULTI)
5679 == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
5680 findings.add(c);
5681 }
5682 }
5683 return findings.size() == 1 ? findings.get(0) : null;
5684 }
5685
5686 public boolean markRead(final Conversation conversation, boolean dismiss) {
5687 return markRead(conversation, null, dismiss).size() > 0;
5688 }
5689
5690 public void markRead(final Conversation conversation) {
5691 markRead(conversation, null, true);
5692 }
5693
5694 public List<Message> markRead(
5695 final Conversation conversation, String upToUuid, boolean dismiss) {
5696 if (dismiss) {
5697 mNotificationService.clear(conversation);
5698 }
5699 final List<Message> readMessages = conversation.markRead(upToUuid);
5700 if (readMessages.size() > 0) {
5701 Runnable runnable =
5702 () -> {
5703 for (Message message : readMessages) {
5704 databaseBackend.updateMessage(message, false);
5705 }
5706 };
5707 mDatabaseWriterExecutor.execute(runnable);
5708 updateConversationUi();
5709 updateUnreadCountBadge();
5710 return readMessages;
5711 } else {
5712 return readMessages;
5713 }
5714 }
5715
5716 public synchronized void updateUnreadCountBadge() {
5717 int count = unreadCount();
5718 if (unreadCount != count) {
5719 Log.d(Config.LOGTAG, "update unread count to " + count);
5720 if (count > 0) {
5721 ShortcutBadger.applyCount(getApplicationContext(), count);
5722 } else {
5723 ShortcutBadger.removeCount(getApplicationContext());
5724 }
5725 unreadCount = count;
5726 }
5727 }
5728
5729 public void sendReadMarker(final Conversation conversation, final String upToUuid) {
5730 final boolean isPrivateAndNonAnonymousMuc =
5731 conversation.getMode() == Conversation.MODE_MULTI
5732 && conversation.isPrivateAndNonAnonymous();
5733 final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
5734 if (readMessages.isEmpty()) {
5735 return;
5736 }
5737 final var account = conversation.getAccount();
5738 final var connection = account.getXmppConnection();
5739 updateConversationUi();
5740 final var last =
5741 Iterables.getLast(
5742 Collections2.filter(
5743 readMessages,
5744 m ->
5745 !m.isPrivateMessage()
5746 && m.getStatus() == Message.STATUS_RECEIVED),
5747 null);
5748 if (last == null) {
5749 return;
5750 }
5751
5752 final boolean sendDisplayedMarker =
5753 confirmMessages()
5754 && (last.trusted() || isPrivateAndNonAnonymousMuc)
5755 && last.getRemoteMsgId() != null
5756 && (last.markable || isPrivateAndNonAnonymousMuc);
5757 final boolean serverAssist =
5758 connection != null && connection.getFeatures().mdsServerAssist();
5759
5760 final String stanzaId = last.getServerMsgId();
5761
5762 if (sendDisplayedMarker && serverAssist) {
5763 final var mdsDisplayed = mIqGenerator.mdsDisplayed(stanzaId, conversation);
5764 final var packet = mMessageGenerator.confirm(last);
5765 packet.addChild(mdsDisplayed);
5766 if (!last.isPrivateMessage()) {
5767 packet.setTo(packet.getTo().asBareJid());
5768 }
5769 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server assisted " + packet);
5770 this.sendMessagePacket(account, packet);
5771 } else {
5772 publishMds(last);
5773 // read markers will be sent after MDS to flush the CSI stanza queue
5774 if (sendDisplayedMarker) {
5775 Log.d(
5776 Config.LOGTAG,
5777 conversation.getAccount().getJid().asBareJid()
5778 + ": sending displayed marker to "
5779 + last.getCounterpart().toString());
5780 final var packet = mMessageGenerator.confirm(last);
5781 this.sendMessagePacket(account, packet);
5782 }
5783 }
5784 }
5785
5786 private void publishMds(@Nullable final Message message) {
5787 final String stanzaId = message == null ? null : message.getServerMsgId();
5788 if (Strings.isNullOrEmpty(stanzaId)) {
5789 return;
5790 }
5791 final Conversation conversation;
5792 final var conversational = message.getConversation();
5793 if (conversational instanceof Conversation c) {
5794 conversation = c;
5795 } else {
5796 return;
5797 }
5798 final var account = conversation.getAccount();
5799 final var connection = account.getXmppConnection();
5800 if (connection == null || !connection.getFeatures().mds()) {
5801 return;
5802 }
5803 final Jid itemId;
5804 if (message.isPrivateMessage()) {
5805 itemId = message.getCounterpart();
5806 } else {
5807 itemId = conversation.getJid().asBareJid();
5808 }
5809 Log.d(Config.LOGTAG, "publishing mds for " + itemId + "/" + stanzaId);
5810 publishMds(account, itemId, stanzaId, conversation);
5811 }
5812
5813 private void publishMds(
5814 final Account account,
5815 final Jid itemId,
5816 final String stanzaId,
5817 final Conversation conversation) {
5818 final var item = mIqGenerator.mdsDisplayed(stanzaId, conversation);
5819 pushNodeAndEnforcePublishOptions(
5820 account,
5821 Namespace.MDS_DISPLAYED,
5822 item,
5823 itemId.toString(),
5824 PublishOptions.persistentWhitelistAccessMaxItems());
5825 }
5826
5827 public boolean sendReactions(final Message message, final Collection<String> reactions) {
5828 if (message.getConversation() instanceof Conversation conversation) {
5829 final var isPrivateMessage = message.isPrivateMessage();
5830 final Jid reactTo;
5831 final boolean typeGroupChat;
5832 final String reactToId;
5833 final Collection<Reaction> combinedReactions;
5834 if (conversation.getMode() == Conversational.MODE_MULTI && !isPrivateMessage) {
5835 final var mucOptions = conversation.getMucOptions();
5836 if (!mucOptions.participating()) {
5837 Log.e(Config.LOGTAG, "not participating in MUC");
5838 return false;
5839 }
5840 final var self = mucOptions.getSelf();
5841 final String occupantId = self.getOccupantId();
5842 if (Strings.isNullOrEmpty(occupantId)) {
5843 Log.e(Config.LOGTAG, "occupant id not found for reaction in MUC");
5844 return false;
5845 }
5846 final var existingRaw =
5847 ImmutableSet.copyOf(
5848 Collections2.transform(message.getReactions(), r -> r.reaction));
5849 final var reactionsAsExistingVariants =
5850 ImmutableSet.copyOf(
5851 Collections2.transform(
5852 reactions, r -> Emoticons.existingVariant(r, existingRaw)));
5853 if (!reactions.equals(reactionsAsExistingVariants)) {
5854 Log.d(Config.LOGTAG, "modified reactions to existing variants");
5855 }
5856 reactToId = message.getServerMsgId();
5857 reactTo = conversation.getJid().asBareJid();
5858 typeGroupChat = true;
5859 combinedReactions =
5860 Reaction.withOccupantId(
5861 message.getReactions(),
5862 reactionsAsExistingVariants,
5863 false,
5864 self.getFullJid(),
5865 conversation.getAccount().getJid(),
5866 occupantId);
5867 } else {
5868 if (message.isCarbon() || message.getStatus() == Message.STATUS_RECEIVED) {
5869 reactToId = message.getRemoteMsgId();
5870 } else {
5871 reactToId = message.getUuid();
5872 }
5873 typeGroupChat = false;
5874 if (isPrivateMessage) {
5875 reactTo = message.getCounterpart();
5876 } else {
5877 reactTo = conversation.getJid().asBareJid();
5878 }
5879 combinedReactions =
5880 Reaction.withFrom(
5881 message.getReactions(),
5882 reactions,
5883 false,
5884 conversation.getAccount().getJid());
5885 }
5886 if (reactTo == null || Strings.isNullOrEmpty(reactToId)) {
5887 Log.e(Config.LOGTAG, "could not find id to react to");
5888 return false;
5889 }
5890 final var reactionMessage =
5891 mMessageGenerator.reaction(reactTo, typeGroupChat, reactToId, reactions);
5892 sendMessagePacket(conversation.getAccount(), reactionMessage);
5893 message.setReactions(combinedReactions);
5894 updateMessage(message, false);
5895 return true;
5896 } else {
5897 return false;
5898 }
5899 }
5900
5901 public MemorizingTrustManager getMemorizingTrustManager() {
5902 return this.mMemorizingTrustManager;
5903 }
5904
5905 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
5906 this.mMemorizingTrustManager = trustManager;
5907 }
5908
5909 public void updateMemorizingTrustManager() {
5910 final MemorizingTrustManager trustManager;
5911 if (appSettings.isTrustSystemCAStore()) {
5912 trustManager = new MemorizingTrustManager(getApplicationContext());
5913 } else {
5914 trustManager = new MemorizingTrustManager(getApplicationContext(), null);
5915 }
5916 setMemorizingTrustManager(trustManager);
5917 }
5918
5919 public LruCache<String, Bitmap> getBitmapCache() {
5920 return this.mBitmapCache;
5921 }
5922
5923 public Collection<String> getKnownHosts() {
5924 final Set<String> hosts = new HashSet<>();
5925 for (final Account account : getAccounts()) {
5926 hosts.add(account.getServer());
5927 for (final Contact contact : account.getRoster().getContacts()) {
5928 if (contact.showInRoster()) {
5929 final String server = contact.getServer();
5930 if (server != null) {
5931 hosts.add(server);
5932 }
5933 }
5934 }
5935 }
5936 if (Config.QUICKSY_DOMAIN != null) {
5937 hosts.remove(
5938 Config.QUICKSY_DOMAIN
5939 .toString()); // we only want to show this when we type a e164
5940 // number
5941 }
5942 if (Config.MAGIC_CREATE_DOMAIN != null) {
5943 hosts.add(Config.MAGIC_CREATE_DOMAIN);
5944 }
5945 return hosts;
5946 }
5947
5948 public Collection<String> getKnownConferenceHosts() {
5949 final Set<String> mucServers = new HashSet<>();
5950 for (final Account account : accounts) {
5951 if (account.getXmppConnection() != null) {
5952 mucServers.addAll(account.getXmppConnection().getMucServers());
5953 for (final Bookmark bookmark : account.getBookmarks()) {
5954 final Jid jid = bookmark.getJid();
5955 final String s = jid == null ? null : jid.getDomain().toString();
5956 if (s != null) {
5957 mucServers.add(s);
5958 }
5959 }
5960 }
5961 }
5962 return mucServers;
5963 }
5964
5965 public void sendMessagePacket(
5966 final Account account,
5967 final im.conversations.android.xmpp.model.stanza.Message packet) {
5968 final XmppConnection connection = account.getXmppConnection();
5969 if (connection != null) {
5970 connection.sendMessagePacket(packet);
5971 }
5972 }
5973
5974 public void sendPresencePacket(
5975 final Account account,
5976 final im.conversations.android.xmpp.model.stanza.Presence packet) {
5977 final XmppConnection connection = account.getXmppConnection();
5978 if (connection != null) {
5979 connection.sendPresencePacket(packet);
5980 }
5981 }
5982
5983 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
5984 final XmppConnection connection = account.getXmppConnection();
5985 if (connection == null) {
5986 return;
5987 }
5988 connection.sendCreateAccountWithCaptchaPacket(id, data);
5989 }
5990
5991 public ListenableFuture<Iq> sendIqPacket(final Account account, final Iq request) {
5992 final XmppConnection connection = account.getXmppConnection();
5993 if (connection == null) {
5994 return Futures.immediateFailedFuture(new TimeoutException());
5995 }
5996 return connection.sendIqPacket(request);
5997 }
5998
5999 public void sendIqPacket(final Account account, final Iq packet, final Consumer<Iq> callback) {
6000 final XmppConnection connection = account.getXmppConnection();
6001 if (connection != null) {
6002 connection.sendIqPacket(packet, callback);
6003 } else if (callback != null) {
6004 callback.accept(Iq.TIMEOUT);
6005 }
6006 }
6007
6008 public void sendPresence(final Account account) {
6009 sendPresence(account, checkListeners() && broadcastLastActivity());
6010 }
6011
6012 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
6013 final im.conversations.android.xmpp.model.stanza.Presence.Availability status;
6014 if (manuallyChangePresence()) {
6015 status = account.getPresenceStatus();
6016 } else {
6017 status = getTargetPresence();
6018 }
6019 final var packet = mPresenceGenerator.selfPresence(account, status);
6020 if (mLastActivity > 0 && includeIdleTimestamp) {
6021 long since =
6022 Math.min(mLastActivity, System.currentTimeMillis()); // don't send future dates
6023 packet.addChild("idle", Namespace.IDLE)
6024 .setAttribute("since", AbstractGenerator.getTimestamp(since));
6025 }
6026 sendPresencePacket(account, packet);
6027 }
6028
6029 private void deactivateGracePeriod() {
6030 for (Account account : getAccounts()) {
6031 account.deactivateGracePeriod();
6032 }
6033 }
6034
6035 public void refreshAllPresences() {
6036 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
6037 for (Account account : getAccounts()) {
6038 if (account.isConnectionEnabled()) {
6039 sendPresence(account, includeIdleTimestamp);
6040 }
6041 }
6042 }
6043
6044 private void refreshAllFcmTokens() {
6045 for (Account account : getAccounts()) {
6046 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
6047 mPushManagementService.registerPushTokenOnServer(account);
6048 }
6049 }
6050 }
6051
6052 private void sendOfflinePresence(final Account account) {
6053 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
6054 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
6055 }
6056
6057 public MessageGenerator getMessageGenerator() {
6058 return this.mMessageGenerator;
6059 }
6060
6061 public PresenceGenerator getPresenceGenerator() {
6062 return this.mPresenceGenerator;
6063 }
6064
6065 public IqGenerator getIqGenerator() {
6066 return this.mIqGenerator;
6067 }
6068
6069 public JingleConnectionManager getJingleConnectionManager() {
6070 return this.mJingleConnectionManager;
6071 }
6072
6073 private boolean hasJingleRtpConnection(final Account account) {
6074 return this.mJingleConnectionManager.hasJingleRtpConnection(account);
6075 }
6076
6077 public MessageArchiveService getMessageArchiveService() {
6078 return this.mMessageArchiveService;
6079 }
6080
6081 public QuickConversationsService getQuickConversationsService() {
6082 return this.mQuickConversationsService;
6083 }
6084
6085 public List<Contact> findContacts(Jid jid, String accountJid) {
6086 ArrayList<Contact> contacts = new ArrayList<>();
6087 for (Account account : getAccounts()) {
6088 if ((account.isEnabled() || accountJid != null)
6089 && (accountJid == null
6090 || accountJid.equals(account.getJid().asBareJid().toString()))) {
6091 Contact contact = account.getRoster().getContactFromContactList(jid);
6092 if (contact != null) {
6093 contacts.add(contact);
6094 }
6095 }
6096 }
6097 return contacts;
6098 }
6099
6100 public Conversation findFirstMuc(Jid jid) {
6101 for (Conversation conversation : getConversations()) {
6102 if (conversation.getAccount().isEnabled()
6103 && conversation.getJid().asBareJid().equals(jid.asBareJid())
6104 && conversation.getMode() == Conversation.MODE_MULTI) {
6105 return conversation;
6106 }
6107 }
6108 return null;
6109 }
6110
6111 public NotificationService getNotificationService() {
6112 return this.mNotificationService;
6113 }
6114
6115 public HttpConnectionManager getHttpConnectionManager() {
6116 return this.mHttpConnectionManager;
6117 }
6118
6119 public void resendFailedMessages(final Message message, final boolean forceP2P) {
6120 message.setTime(System.currentTimeMillis());
6121 markMessage(message, Message.STATUS_WAITING);
6122 this.sendMessage(message, true, false, forceP2P);
6123 if (message.getConversation() instanceof Conversation c) {
6124 c.sort();
6125 }
6126 updateConversationUi();
6127 }
6128
6129 public void clearConversationHistory(final Conversation conversation) {
6130 final long clearDate;
6131 final String reference;
6132 if (conversation.countMessages() > 0) {
6133 Message latestMessage = conversation.getLatestMessage();
6134 clearDate = latestMessage.getTimeSent() + 1000;
6135 reference = latestMessage.getServerMsgId();
6136 } else {
6137 clearDate = System.currentTimeMillis();
6138 reference = null;
6139 }
6140 conversation.clearMessages();
6141 conversation.setHasMessagesLeftOnServer(false); // avoid messages getting loaded through mam
6142 conversation.setLastClearHistory(clearDate, reference);
6143 Runnable runnable =
6144 () -> {
6145 databaseBackend.deleteMessagesInConversation(conversation);
6146 databaseBackend.updateConversation(conversation);
6147 };
6148 mDatabaseWriterExecutor.execute(runnable);
6149 }
6150
6151 public boolean sendBlockRequest(
6152 final Blockable blockable, final boolean reportSpam, final String serverMsgId) {
6153 if (blockable != null && blockable.getBlockedJid() != null) {
6154 final var account = blockable.getAccount();
6155 final Jid jid = blockable.getBlockedJid();
6156 this.sendIqPacket(
6157 account,
6158 getIqGenerator().generateSetBlockRequest(jid, reportSpam, serverMsgId),
6159 (response) -> {
6160 if (response.getType() == Iq.Type.RESULT) {
6161 account.getBlocklist().add(jid);
6162 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
6163 }
6164 });
6165 if (blockable.getBlockedJid().isFullJid()) {
6166 return false;
6167 } else if (removeBlockedConversations(blockable.getAccount(), jid)) {
6168 updateConversationUi();
6169 return true;
6170 } else {
6171 return false;
6172 }
6173 } else {
6174 return false;
6175 }
6176 }
6177
6178 public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
6179 boolean removed = false;
6180 synchronized (this.conversations) {
6181 boolean domainJid = blockedJid.getLocal() == null;
6182 for (Conversation conversation : this.conversations) {
6183 boolean jidMatches =
6184 (domainJid
6185 && blockedJid
6186 .getDomain()
6187 .equals(conversation.getJid().getDomain()))
6188 || blockedJid.equals(conversation.getJid().asBareJid());
6189 if (conversation.getAccount() == account
6190 && conversation.getMode() == Conversation.MODE_SINGLE
6191 && jidMatches) {
6192 this.conversations.remove(conversation);
6193 markRead(conversation);
6194 conversation.setStatus(Conversation.STATUS_ARCHIVED);
6195 Log.d(
6196 Config.LOGTAG,
6197 account.getJid().asBareJid()
6198 + ": archiving conversation "
6199 + conversation.getJid().asBareJid()
6200 + " because jid was blocked");
6201 updateConversation(conversation);
6202 removed = true;
6203 }
6204 }
6205 }
6206 return removed;
6207 }
6208
6209 public void sendUnblockRequest(final Blockable blockable) {
6210 if (blockable != null && blockable.getJid() != null) {
6211 final var account = blockable.getAccount();
6212 final Jid jid = blockable.getBlockedJid();
6213 this.sendIqPacket(
6214 account,
6215 getIqGenerator().generateSetUnblockRequest(jid),
6216 response -> {
6217 if (response.getType() == Iq.Type.RESULT) {
6218 account.getBlocklist().remove(jid);
6219 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
6220 }
6221 });
6222 }
6223 }
6224
6225 public void publishDisplayName(final Account account) {
6226 String displayName = account.getDisplayName();
6227 final Iq request;
6228 if (TextUtils.isEmpty(displayName)) {
6229 request = mIqGenerator.deleteNode(Namespace.NICK);
6230 } else {
6231 request = mIqGenerator.publishNick(displayName);
6232 }
6233 mAvatarService.clear(account);
6234 sendIqPacket(
6235 account,
6236 request,
6237 (packet) -> {
6238 if (packet.getType() == Iq.Type.ERROR) {
6239 Log.d(
6240 Config.LOGTAG,
6241 account.getJid().asBareJid()
6242 + ": unable to modify nick name "
6243 + packet);
6244 }
6245 });
6246 }
6247
6248 public void fetchMamPreferences(final Account account, final OnMamPreferencesFetched callback) {
6249 final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
6250 final Iq request = new Iq(Iq.Type.GET);
6251 request.addChild("prefs", version.namespace);
6252 sendIqPacket(
6253 account,
6254 request,
6255 (packet) -> {
6256 final Element prefs = packet.findChild("prefs", version.namespace);
6257 if (packet.getType() == Iq.Type.RESULT && prefs != null) {
6258 callback.onPreferencesFetched(prefs);
6259 } else {
6260 callback.onPreferencesFetchFailed();
6261 }
6262 });
6263 }
6264
6265 public PushManagementService getPushManagementService() {
6266 return mPushManagementService;
6267 }
6268
6269 public void changeStatus(Account account, PresenceTemplate template, String signature) {
6270 if (!template.getStatusMessage().isEmpty()) {
6271 databaseBackend.insertPresenceTemplate(template);
6272 }
6273 account.setPgpSignature(signature);
6274 account.setPresenceStatus(template.getStatus());
6275 account.setPresenceStatusMessage(template.getStatusMessage());
6276 databaseBackend.updateAccount(account);
6277 sendPresence(account);
6278 }
6279
6280 public List<PresenceTemplate> getPresenceTemplates(Account account) {
6281 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
6282 for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
6283 if (!templates.contains(template)) {
6284 templates.add(0, template);
6285 }
6286 }
6287 return templates;
6288 }
6289
6290 public void saveConversationAsBookmark(final Conversation conversation, final String name) {
6291 final Account account = conversation.getAccount();
6292 final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
6293 final String nick = conversation.getJid().getResource();
6294 if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
6295 bookmark.setNick(nick);
6296 }
6297 if (!TextUtils.isEmpty(name)) {
6298 bookmark.setBookmarkName(name);
6299 }
6300 bookmark.setAutojoin(true);
6301 createBookmark(account, bookmark);
6302 bookmark.setConversation(conversation);
6303 }
6304
6305 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
6306 boolean performedVerification = false;
6307 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
6308 for (XmppUri.Fingerprint fp : fingerprints) {
6309 if (fp.type == XmppUri.FingerprintType.OMEMO) {
6310 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
6311 FingerprintStatus fingerprintStatus =
6312 axolotlService.getFingerprintTrust(fingerprint);
6313 if (fingerprintStatus != null) {
6314 if (!fingerprintStatus.isVerified()) {
6315 performedVerification = true;
6316 axolotlService.setFingerprintTrust(
6317 fingerprint, fingerprintStatus.toVerified());
6318 }
6319 } else {
6320 axolotlService.preVerifyFingerprint(contact, fingerprint);
6321 }
6322 }
6323 }
6324 return performedVerification;
6325 }
6326
6327 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
6328 final AxolotlService axolotlService = account.getAxolotlService();
6329 boolean verifiedSomething = false;
6330 for (XmppUri.Fingerprint fp : fingerprints) {
6331 if (fp.type == XmppUri.FingerprintType.OMEMO) {
6332 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
6333 Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
6334 FingerprintStatus fingerprintStatus =
6335 axolotlService.getFingerprintTrust(fingerprint);
6336 if (fingerprintStatus != null) {
6337 if (!fingerprintStatus.isVerified()) {
6338 axolotlService.setFingerprintTrust(
6339 fingerprint, fingerprintStatus.toVerified());
6340 verifiedSomething = true;
6341 }
6342 } else {
6343 axolotlService.preVerifyFingerprint(account, fingerprint);
6344 verifiedSomething = true;
6345 }
6346 }
6347 }
6348 return verifiedSomething;
6349 }
6350
6351 public ShortcutService getShortcutService() {
6352 return mShortcutService;
6353 }
6354
6355 public void pushMamPreferences(Account account, Element prefs) {
6356 final Iq set = new Iq(Iq.Type.SET);
6357 set.addChild(prefs);
6358 sendIqPacket(account, set, null);
6359 }
6360
6361 public void evictPreview(String uuid) {
6362 if (mBitmapCache.remove(uuid) != null) {
6363 Log.d(Config.LOGTAG, "deleted cached preview");
6364 }
6365 }
6366
6367 public interface OnMamPreferencesFetched {
6368 void onPreferencesFetched(Element prefs);
6369
6370 void onPreferencesFetchFailed();
6371 }
6372
6373 public interface OnAccountCreated {
6374 void onAccountCreated(Account account);
6375
6376 void informUser(int r);
6377 }
6378
6379 public interface OnMoreMessagesLoaded {
6380 void onMoreMessagesLoaded(int count, Conversation conversation);
6381
6382 void informUser(int r);
6383 }
6384
6385 public interface OnAccountPasswordChanged {
6386 void onPasswordChangeSucceeded();
6387
6388 void onPasswordChangeFailed();
6389 }
6390
6391 public interface OnRoomDestroy {
6392 void onRoomDestroySucceeded();
6393
6394 void onRoomDestroyFailed();
6395 }
6396
6397 public interface OnAffiliationChanged {
6398 void onAffiliationChangedSuccessful(Jid jid);
6399
6400 void onAffiliationChangeFailed(Jid jid, int resId);
6401 }
6402
6403 public interface OnConversationUpdate {
6404 void onConversationUpdate();
6405 }
6406
6407 public interface OnJingleRtpConnectionUpdate {
6408 void onJingleRtpConnectionUpdate(
6409 final Account account,
6410 final Jid with,
6411 final String sessionId,
6412 final RtpEndUserState state);
6413
6414 void onAudioDeviceChanged(
6415 CallIntegration.AudioDevice selectedAudioDevice,
6416 Set<CallIntegration.AudioDevice> availableAudioDevices);
6417 }
6418
6419 public interface OnAccountUpdate {
6420 void onAccountUpdate();
6421 }
6422
6423 public interface OnCaptchaRequested {
6424 void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
6425 }
6426
6427 public interface OnRosterUpdate {
6428 void onRosterUpdate();
6429 }
6430
6431 public interface OnMucRosterUpdate {
6432 void onMucRosterUpdate();
6433 }
6434
6435 public interface OnConferenceConfigurationFetched {
6436 void onConferenceConfigurationFetched(Conversation conversation);
6437
6438 void onFetchFailed(Conversation conversation, String errorCondition);
6439 }
6440
6441 public interface OnConferenceJoined {
6442 void onConferenceJoined(Conversation conversation);
6443 }
6444
6445 public interface OnConfigurationPushed {
6446 void onPushSucceeded();
6447
6448 void onPushFailed();
6449 }
6450
6451 public interface OnShowErrorToast {
6452 void onShowErrorToast(int resId);
6453 }
6454
6455 public class XmppConnectionBinder extends Binder {
6456 public XmppConnectionService getService() {
6457 return XmppConnectionService.this;
6458 }
6459 }
6460
6461 private class InternalEventReceiver extends BroadcastReceiver {
6462
6463 @Override
6464 public void onReceive(final Context context, final Intent intent) {
6465 onStartCommand(intent, 0, 0);
6466 }
6467 }
6468
6469 private class RestrictedEventReceiver extends BroadcastReceiver {
6470
6471 private final Collection<String> allowedActions;
6472
6473 private RestrictedEventReceiver(final Collection<String> allowedActions) {
6474 this.allowedActions = allowedActions;
6475 }
6476
6477 @Override
6478 public void onReceive(final Context context, final Intent intent) {
6479 final String action = intent == null ? null : intent.getAction();
6480 if (allowedActions.contains(action)) {
6481 onStartCommand(intent, 0, 0);
6482 } else {
6483 Log.e(Config.LOGTAG, "restricting broadcast of event " + action);
6484 }
6485 }
6486 }
6487
6488 public static class OngoingCall {
6489 public final AbstractJingleConnection.Id id;
6490 public final Set<Media> media;
6491 public final boolean reconnecting;
6492
6493 public OngoingCall(
6494 AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
6495 this.id = id;
6496 this.media = media;
6497 this.reconnecting = reconnecting;
6498 }
6499
6500 @Override
6501 public boolean equals(Object o) {
6502 if (this == o) return true;
6503 if (o == null || getClass() != o.getClass()) return false;
6504 OngoingCall that = (OngoingCall) o;
6505 return reconnecting == that.reconnecting
6506 && Objects.equal(id, that.id)
6507 && Objects.equal(media, that.media);
6508 }
6509
6510 @Override
6511 public int hashCode() {
6512 return Objects.hashCode(id, media, reconnecting);
6513 }
6514 }
6515
6516 public static void toggleForegroundService(final XmppConnectionService service) {
6517 if (service == null) {
6518 return;
6519 }
6520 service.toggleForegroundService();
6521 }
6522
6523 public static void toggleForegroundService(final ConversationsActivity activity) {
6524 if (activity == null) {
6525 return;
6526 }
6527 toggleForegroundService(activity.xmppConnectionService);
6528 }
6529}