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