XmppConnectionService.java

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