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