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