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.io.BaseEncoding;
  61import com.google.common.util.concurrent.FutureCallback;
  62import com.google.common.util.concurrent.Futures;
  63import com.google.common.util.concurrent.ListenableFuture;
  64import com.google.common.util.concurrent.MoreExecutors;
  65import eu.siacs.conversations.AppSettings;
  66import eu.siacs.conversations.Config;
  67import eu.siacs.conversations.R;
  68import eu.siacs.conversations.android.JabberIdContact;
  69import eu.siacs.conversations.crypto.OmemoSetting;
  70import eu.siacs.conversations.crypto.PgpDecryptionService;
  71import eu.siacs.conversations.crypto.PgpEngine;
  72import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  73import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  74import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
  75import eu.siacs.conversations.entities.Account;
  76import eu.siacs.conversations.entities.Blockable;
  77import eu.siacs.conversations.entities.Bookmark;
  78import eu.siacs.conversations.entities.Contact;
  79import eu.siacs.conversations.entities.Conversation;
  80import eu.siacs.conversations.entities.Conversational;
  81import eu.siacs.conversations.entities.Message;
  82import eu.siacs.conversations.entities.MucOptions;
  83import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
  84import eu.siacs.conversations.entities.PresenceTemplate;
  85import eu.siacs.conversations.entities.Reaction;
  86import eu.siacs.conversations.generator.AbstractGenerator;
  87import eu.siacs.conversations.generator.IqGenerator;
  88import eu.siacs.conversations.generator.MessageGenerator;
  89import eu.siacs.conversations.generator.PresenceGenerator;
  90import eu.siacs.conversations.http.HttpConnectionManager;
  91import eu.siacs.conversations.http.ServiceOutageStatus;
  92import eu.siacs.conversations.parser.AbstractParser;
  93import eu.siacs.conversations.parser.IqParser;
  94import eu.siacs.conversations.persistance.DatabaseBackend;
  95import eu.siacs.conversations.persistance.FileBackend;
  96import eu.siacs.conversations.persistance.UnifiedPushDatabase;
  97import eu.siacs.conversations.receiver.SystemEventReceiver;
  98import eu.siacs.conversations.ui.ChooseAccountForProfilePictureActivity;
  99import eu.siacs.conversations.ui.ConversationsActivity;
 100import eu.siacs.conversations.ui.RtpSessionActivity;
 101import eu.siacs.conversations.ui.UiCallback;
 102import eu.siacs.conversations.ui.interfaces.OnAvatarPublication;
 103import eu.siacs.conversations.ui.interfaces.OnMediaLoaded;
 104import eu.siacs.conversations.ui.interfaces.OnSearchResultsAvailable;
 105import eu.siacs.conversations.utils.AccountUtils;
 106import eu.siacs.conversations.utils.Compatibility;
 107import eu.siacs.conversations.utils.ConversationsFileObserver;
 108import eu.siacs.conversations.utils.CryptoHelper;
 109import eu.siacs.conversations.utils.EasyOnboardingInvite;
 110import eu.siacs.conversations.utils.Emoticons;
 111import eu.siacs.conversations.utils.MimeUtils;
 112import eu.siacs.conversations.utils.PhoneHelper;
 113import eu.siacs.conversations.utils.QuickLoader;
 114import eu.siacs.conversations.utils.ReplacingSerialSingleThreadExecutor;
 115import eu.siacs.conversations.utils.Resolver;
 116import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
 117import eu.siacs.conversations.utils.StringUtils;
 118import eu.siacs.conversations.utils.TorServiceUtils;
 119import eu.siacs.conversations.utils.WakeLockHelper;
 120import eu.siacs.conversations.utils.XmppUri;
 121import eu.siacs.conversations.xml.Element;
 122import eu.siacs.conversations.xml.LocalizedContent;
 123import eu.siacs.conversations.xml.Namespace;
 124import eu.siacs.conversations.xmpp.Jid;
 125import eu.siacs.conversations.xmpp.OnContactStatusChanged;
 126import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
 127import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 128import eu.siacs.conversations.xmpp.XmppConnection;
 129import eu.siacs.conversations.xmpp.chatstate.ChatState;
 130import eu.siacs.conversations.xmpp.forms.Data;
 131import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
 132import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
 133import eu.siacs.conversations.xmpp.jingle.Media;
 134import eu.siacs.conversations.xmpp.jingle.RtpEndUserState;
 135import eu.siacs.conversations.xmpp.mam.MamReference;
 136import eu.siacs.conversations.xmpp.manager.AvatarManager;
 137import eu.siacs.conversations.xmpp.manager.BlockingManager;
 138import eu.siacs.conversations.xmpp.manager.BookmarkManager;
 139import eu.siacs.conversations.xmpp.manager.DiscoManager;
 140import eu.siacs.conversations.xmpp.manager.LegacyBookmarkManager;
 141import eu.siacs.conversations.xmpp.manager.MessageDisplayedSynchronizationManager;
 142import eu.siacs.conversations.xmpp.manager.NickManager;
 143import eu.siacs.conversations.xmpp.manager.PresenceManager;
 144import eu.siacs.conversations.xmpp.manager.PrivateStorageManager;
 145import eu.siacs.conversations.xmpp.manager.RosterManager;
 146import eu.siacs.conversations.xmpp.manager.VCardManager;
 147import eu.siacs.conversations.xmpp.pep.Avatar;
 148import im.conversations.android.xmpp.Entity;
 149import im.conversations.android.xmpp.IqErrorException;
 150import im.conversations.android.xmpp.model.avatar.Metadata;
 151import im.conversations.android.xmpp.model.disco.info.InfoQuery;
 152import im.conversations.android.xmpp.model.pubsub.PubSub;
 153import im.conversations.android.xmpp.model.stanza.Iq;
 154import im.conversations.android.xmpp.model.up.Push;
 155import java.io.File;
 156import java.security.Security;
 157import java.security.cert.CertificateException;
 158import java.security.cert.X509Certificate;
 159import java.util.ArrayList;
 160import java.util.Arrays;
 161import java.util.Collection;
 162import java.util.Collections;
 163import java.util.HashSet;
 164import java.util.Iterator;
 165import java.util.List;
 166import java.util.ListIterator;
 167import java.util.Map;
 168import java.util.Set;
 169import java.util.WeakHashMap;
 170import java.util.concurrent.CopyOnWriteArrayList;
 171import java.util.concurrent.CountDownLatch;
 172import java.util.concurrent.Executor;
 173import java.util.concurrent.Executors;
 174import java.util.concurrent.RejectedExecutionException;
 175import java.util.concurrent.ScheduledExecutorService;
 176import java.util.concurrent.TimeUnit;
 177import java.util.concurrent.TimeoutException;
 178import java.util.concurrent.atomic.AtomicBoolean;
 179import java.util.concurrent.atomic.AtomicLong;
 180import java.util.concurrent.atomic.AtomicReference;
 181import java.util.function.Consumer;
 182import me.leolin.shortcutbadger.ShortcutBadger;
 183import okhttp3.HttpUrl;
 184import org.conscrypt.Conscrypt;
 185import org.jxmpp.stringprep.libidn.LibIdnXmppStringprep;
 186import org.openintents.openpgp.IOpenPgpService2;
 187import org.openintents.openpgp.util.OpenPgpApi;
 188import org.openintents.openpgp.util.OpenPgpServiceConnection;
 189
 190public class XmppConnectionService extends Service {
 191
 192    public static final String ACTION_REPLY_TO_CONVERSATION = "reply_to_conversations";
 193    public static final String ACTION_MARK_AS_READ = "mark_as_read";
 194    public static final String ACTION_SNOOZE = "snooze";
 195    public static final String ACTION_CLEAR_MESSAGE_NOTIFICATION = "clear_message_notification";
 196    public static final String ACTION_CLEAR_MISSED_CALL_NOTIFICATION =
 197            "clear_missed_call_notification";
 198    public static final String ACTION_DISMISS_ERROR_NOTIFICATIONS = "dismiss_error";
 199    public static final String ACTION_TRY_AGAIN = "try_again";
 200
 201    public static final String ACTION_TEMPORARILY_DISABLE = "temporarily_disable";
 202    public static final String ACTION_PING = "ping";
 203    public static final String ACTION_IDLE_PING = "idle_ping";
 204    public static final String ACTION_INTERNAL_PING = "internal_ping";
 205    public static final String ACTION_FCM_TOKEN_REFRESH = "fcm_token_refresh";
 206    public static final String ACTION_FCM_MESSAGE_RECEIVED = "fcm_message_received";
 207    public static final String ACTION_DISMISS_CALL = "dismiss_call";
 208    public static final String ACTION_END_CALL = "end_call";
 209    public static final String ACTION_PROVISION_ACCOUNT = "provision_account";
 210    public static final String ACTION_CALL_INTEGRATION_SERVICE_STARTED =
 211            "call_integration_service_started";
 212    private static final String ACTION_POST_CONNECTIVITY_CHANGE =
 213            "eu.siacs.conversations.POST_CONNECTIVITY_CHANGE";
 214    public static final String ACTION_RENEW_UNIFIED_PUSH_ENDPOINTS =
 215            "eu.siacs.conversations.UNIFIED_PUSH_RENEW";
 216    public static final String ACTION_QUICK_LOG = "eu.siacs.conversations.QUICK_LOG";
 217
 218    private static final String SETTING_LAST_ACTIVITY_TS = "last_activity_timestamp";
 219
 220    public final CountDownLatch restoredFromDatabaseLatch = new CountDownLatch(1);
 221    private static final Executor FILE_OBSERVER_EXECUTOR = Executors.newSingleThreadExecutor();
 222    public static final Executor FILE_ATTACHMENT_EXECUTOR = Executors.newSingleThreadExecutor();
 223
 224    public final ScheduledExecutorService internalPingExecutor =
 225            Executors.newSingleThreadScheduledExecutor();
 226    private static final SerialSingleThreadExecutor VIDEO_COMPRESSION_EXECUTOR =
 227            new SerialSingleThreadExecutor("VideoCompression");
 228    private final SerialSingleThreadExecutor mDatabaseWriterExecutor =
 229            new SerialSingleThreadExecutor("DatabaseWriter");
 230    private final SerialSingleThreadExecutor mDatabaseReaderExecutor =
 231            new SerialSingleThreadExecutor("DatabaseReader");
 232    private final SerialSingleThreadExecutor mNotificationExecutor =
 233            new SerialSingleThreadExecutor("NotificationExecutor");
 234    private final IBinder mBinder = new XmppConnectionBinder();
 235    private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
 236    private final IqGenerator mIqGenerator = new IqGenerator(this);
 237    private final Set<String> mInProgressAvatarFetches = new HashSet<>();
 238    private final Set<String> mOmittedPepAvatarFetches = new HashSet<>();
 239    public final HashSet<Jid> mLowPingTimeoutMode = new HashSet<>();
 240    public DatabaseBackend databaseBackend;
 241    private final ReplacingSerialSingleThreadExecutor mContactMergerExecutor =
 242            new ReplacingSerialSingleThreadExecutor("ContactMerger");
 243    private long mLastActivity = 0;
 244
 245    private final AppSettings appSettings = new AppSettings(this);
 246    private final FileBackend fileBackend = new FileBackend(this);
 247    private MemorizingTrustManager mMemorizingTrustManager;
 248    private final NotificationService mNotificationService = new NotificationService(this);
 249    private final UnifiedPushBroker unifiedPushBroker = new UnifiedPushBroker(this);
 250    private final ChannelDiscoveryService mChannelDiscoveryService =
 251            new ChannelDiscoveryService(this);
 252    private final ShortcutService mShortcutService = new ShortcutService(this);
 253    private final AtomicBoolean mInitialAddressbookSyncCompleted = new AtomicBoolean(false);
 254    private final AtomicBoolean mOngoingVideoTranscoding = new AtomicBoolean(false);
 255    private final AtomicBoolean mForceDuringOnCreate = new AtomicBoolean(false);
 256    private final AtomicReference<OngoingCall> ongoingCall = new AtomicReference<>();
 257    private final MessageGenerator mMessageGenerator = new MessageGenerator(this);
 258    public OnContactStatusChanged onContactStatusChanged =
 259            (contact, online) -> {
 260                final var conversation = find(contact);
 261                if (conversation == null) {
 262                    return;
 263                }
 264                if (online) {
 265                    if (contact.getPresences().size() == 1) {
 266                        sendUnsentMessages(conversation);
 267                    }
 268                }
 269            };
 270    private final PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
 271    private List<Account> accounts;
 272    private final JingleConnectionManager mJingleConnectionManager =
 273            new JingleConnectionManager(this);
 274    private final HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(this);
 275    private final AvatarService mAvatarService = new AvatarService(this);
 276    private final MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
 277    private final PushManagementService mPushManagementService = new PushManagementService(this);
 278    private final QuickConversationsService mQuickConversationsService =
 279            new QuickConversationsService(this);
 280    private final ConversationsFileObserver fileObserver =
 281            new ConversationsFileObserver(
 282                    Environment.getExternalStorageDirectory().getAbsolutePath()) {
 283                @Override
 284                public void onEvent(final int event, final File file) {
 285                    markFileDeleted(file);
 286                }
 287            };
 288    private boolean destroyed = false;
 289
 290    private int unreadCount = -1;
 291
 292    // Ui callback listeners
 293    private final Set<OnConversationUpdate> mOnConversationUpdates =
 294            Collections.newSetFromMap(new WeakHashMap<OnConversationUpdate, Boolean>());
 295    private final Set<OnShowErrorToast> mOnShowErrorToasts =
 296            Collections.newSetFromMap(new WeakHashMap<OnShowErrorToast, Boolean>());
 297    private final Set<OnAccountUpdate> mOnAccountUpdates =
 298            Collections.newSetFromMap(new WeakHashMap<OnAccountUpdate, Boolean>());
 299    private final Set<OnCaptchaRequested> mOnCaptchaRequested =
 300            Collections.newSetFromMap(new WeakHashMap<OnCaptchaRequested, Boolean>());
 301    private final Set<OnRosterUpdate> mOnRosterUpdates =
 302            Collections.newSetFromMap(new WeakHashMap<OnRosterUpdate, Boolean>());
 303    private final Set<OnUpdateBlocklist> mOnUpdateBlocklist =
 304            Collections.newSetFromMap(new WeakHashMap<OnUpdateBlocklist, Boolean>());
 305    private final Set<OnMucRosterUpdate> mOnMucRosterUpdate =
 306            Collections.newSetFromMap(new WeakHashMap<OnMucRosterUpdate, Boolean>());
 307    private final Set<OnKeyStatusUpdated> mOnKeyStatusUpdated =
 308            Collections.newSetFromMap(new WeakHashMap<OnKeyStatusUpdated, Boolean>());
 309    private final Set<OnJingleRtpConnectionUpdate> onJingleRtpConnectionUpdate =
 310            Collections.newSetFromMap(new WeakHashMap<OnJingleRtpConnectionUpdate, Boolean>());
 311
 312    private final Object LISTENER_LOCK = new Object();
 313
 314    public final Set<String> FILENAMES_TO_IGNORE_DELETION = new HashSet<>();
 315
 316    private final AtomicLong mLastExpiryRun = new AtomicLong(0);
 317
 318    private OpenPgpServiceConnection pgpServiceConnection;
 319    private PgpEngine mPgpEngine = null;
 320    private WakeLock wakeLock;
 321    private LruCache<String, Bitmap> mBitmapCache;
 322    private final BroadcastReceiver mInternalEventReceiver = new InternalEventReceiver();
 323    private final BroadcastReceiver mInternalRestrictedEventReceiver =
 324            new RestrictedEventReceiver(List.of(TorServiceUtils.ACTION_STATUS));
 325    private final BroadcastReceiver mInternalScreenEventReceiver = new InternalEventReceiver();
 326
 327    private static String generateFetchKey(Account account, final Avatar avatar) {
 328        return account.getJid().asBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum;
 329    }
 330
 331    public boolean isInLowPingTimeoutMode(Account account) {
 332        synchronized (mLowPingTimeoutMode) {
 333            return mLowPingTimeoutMode.contains(account.getJid().asBareJid());
 334        }
 335    }
 336
 337    public void startOngoingVideoTranscodingForegroundNotification() {
 338        mOngoingVideoTranscoding.set(true);
 339        toggleForegroundService();
 340    }
 341
 342    public void stopOngoingVideoTranscodingForegroundNotification() {
 343        mOngoingVideoTranscoding.set(false);
 344        toggleForegroundService();
 345    }
 346
 347    public boolean areMessagesInitialized() {
 348        return this.restoredFromDatabaseLatch.getCount() == 0;
 349    }
 350
 351    public PgpEngine getPgpEngine() {
 352        if (!Config.supportOpenPgp()) {
 353            return null;
 354        } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
 355            if (this.mPgpEngine == null) {
 356                this.mPgpEngine =
 357                        new PgpEngine(
 358                                new OpenPgpApi(
 359                                        getApplicationContext(), pgpServiceConnection.getService()),
 360                                this);
 361            }
 362            return mPgpEngine;
 363        } else {
 364            return null;
 365        }
 366    }
 367
 368    public OpenPgpApi getOpenPgpApi() {
 369        if (!Config.supportOpenPgp()) {
 370            return null;
 371        } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
 372            return new OpenPgpApi(this, pgpServiceConnection.getService());
 373        } else {
 374            return null;
 375        }
 376    }
 377
 378    public AppSettings getAppSettings() {
 379        return this.appSettings;
 380    }
 381
 382    public FileBackend getFileBackend() {
 383        return this.fileBackend;
 384    }
 385
 386    public AvatarService getAvatarService() {
 387        return this.mAvatarService;
 388    }
 389
 390    public void attachLocationToConversation(
 391            final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
 392        int encryption = conversation.getNextEncryption();
 393        if (encryption == Message.ENCRYPTION_PGP) {
 394            encryption = Message.ENCRYPTION_DECRYPTED;
 395        }
 396        Message message = new Message(conversation, uri.toString(), encryption);
 397        Message.configurePrivateMessage(message);
 398        if (encryption == Message.ENCRYPTION_DECRYPTED) {
 399            getPgpEngine().encrypt(message, callback);
 400        } else {
 401            sendMessage(message);
 402            callback.success(message);
 403        }
 404    }
 405
 406    public void attachFileToConversation(
 407            final Conversation conversation,
 408            final Uri uri,
 409            final String type,
 410            final UiCallback<Message> callback) {
 411        final Message message;
 412        if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 413            message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
 414        } else {
 415            message = new Message(conversation, "", conversation.getNextEncryption());
 416        }
 417        if (!Message.configurePrivateFileMessage(message)) {
 418            message.setCounterpart(conversation.getNextCounterpart());
 419            message.setType(Message.TYPE_FILE);
 420        }
 421        Log.d(Config.LOGTAG, "attachFile: type=" + message.getType());
 422        Log.d(Config.LOGTAG, "counterpart=" + message.getCounterpart());
 423        final AttachFileToConversationRunnable runnable =
 424                new AttachFileToConversationRunnable(this, uri, type, message, callback);
 425        if (runnable.isVideoMessage()) {
 426            VIDEO_COMPRESSION_EXECUTOR.execute(runnable);
 427        } else {
 428            FILE_ATTACHMENT_EXECUTOR.execute(runnable);
 429        }
 430    }
 431
 432    public void attachImageToConversation(
 433            final Conversation conversation,
 434            final Uri uri,
 435            final String type,
 436            final UiCallback<Message> callback) {
 437        final String mimeType = MimeUtils.guessMimeTypeFromUriAndMime(this, uri, type);
 438        final String compressPictures = getCompressPicturesPreference();
 439
 440        if ("never".equals(compressPictures)
 441                || ("auto".equals(compressPictures) && getFileBackend().useImageAsIs(uri))
 442                || (mimeType != null && mimeType.endsWith("/gif"))
 443                || getFileBackend().unusualBounds(uri)) {
 444            Log.d(
 445                    Config.LOGTAG,
 446                    conversation.getAccount().getJid().asBareJid()
 447                            + ": not compressing picture. sending as file");
 448            attachFileToConversation(conversation, uri, mimeType, callback);
 449            return;
 450        }
 451        final Message message;
 452        if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 453            message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
 454        } else {
 455            message = new Message(conversation, "", conversation.getNextEncryption());
 456        }
 457        if (!Message.configurePrivateFileMessage(message)) {
 458            message.setCounterpart(conversation.getNextCounterpart());
 459            message.setType(Message.TYPE_IMAGE);
 460        }
 461        Log.d(Config.LOGTAG, "attachImage: type=" + message.getType());
 462        FILE_ATTACHMENT_EXECUTOR.execute(
 463                () -> {
 464                    try {
 465                        getFileBackend().copyImageToPrivateStorage(message, uri);
 466                    } catch (FileBackend.ImageCompressionException e) {
 467                        Log.d(
 468                                Config.LOGTAG,
 469                                "unable to compress image. fall back to file transfer",
 470                                e);
 471                        attachFileToConversation(conversation, uri, mimeType, callback);
 472                        return;
 473                    } catch (final FileBackend.FileCopyException e) {
 474                        callback.error(e.getResId(), message);
 475                        return;
 476                    }
 477                    if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 478                        final PgpEngine pgpEngine = getPgpEngine();
 479                        if (pgpEngine != null) {
 480                            pgpEngine.encrypt(message, callback);
 481                        } else if (callback != null) {
 482                            callback.error(R.string.unable_to_connect_to_keychain, null);
 483                        }
 484                    } else {
 485                        sendMessage(message);
 486                        callback.success(message);
 487                    }
 488                });
 489    }
 490
 491    public Conversation find(Bookmark bookmark) {
 492        return find(bookmark.getAccount(), bookmark.getJid());
 493    }
 494
 495    public Conversation find(final Account account, final Jid jid) {
 496        return find(getConversations(), account, jid);
 497    }
 498
 499    public boolean isMuc(final Account account, final Jid jid) {
 500        final Conversation c = find(account, jid);
 501        return c != null && c.getMode() == Conversational.MODE_MULTI;
 502    }
 503
 504    public void search(
 505            final List<String> term,
 506            final String uuid,
 507            final OnSearchResultsAvailable onSearchResultsAvailable) {
 508        MessageSearchTask.search(this, term, uuid, onSearchResultsAvailable);
 509    }
 510
 511    @Override
 512    public int onStartCommand(final Intent intent, int flags, int startId) {
 513        final String action = Strings.nullToEmpty(intent == null ? null : intent.getAction());
 514        final boolean needsForegroundService =
 515                intent != null
 516                        && intent.getBooleanExtra(
 517                                SystemEventReceiver.EXTRA_NEEDS_FOREGROUND_SERVICE, false);
 518        if (needsForegroundService) {
 519            Log.d(
 520                    Config.LOGTAG,
 521                    "toggle forced foreground service after receiving event (action="
 522                            + action
 523                            + ")");
 524            toggleForegroundService(true);
 525        }
 526        final String uuid = intent == null ? null : intent.getStringExtra("uuid");
 527        switch (action) {
 528            case QuickConversationsService.SMS_RETRIEVED_ACTION:
 529                mQuickConversationsService.handleSmsReceived(intent);
 530                break;
 531            case ConnectivityManager.CONNECTIVITY_ACTION:
 532                if (hasInternetConnection()) {
 533                    if (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL > 0) {
 534                        schedulePostConnectivityChange();
 535                    }
 536                    if (Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
 537                        resetAllAttemptCounts(true, false);
 538                    }
 539                    Resolver.clearCache();
 540                }
 541                break;
 542            case Intent.ACTION_SHUTDOWN:
 543                logoutAndSave(true);
 544                return START_NOT_STICKY;
 545            case ACTION_CLEAR_MESSAGE_NOTIFICATION:
 546                mNotificationExecutor.execute(
 547                        () -> {
 548                            try {
 549                                final Conversation c = findConversationByUuid(uuid);
 550                                if (c != null) {
 551                                    mNotificationService.clearMessages(c);
 552                                } else {
 553                                    mNotificationService.clearMessages();
 554                                }
 555                                restoredFromDatabaseLatch.await();
 556
 557                            } catch (InterruptedException e) {
 558                                Log.d(
 559                                        Config.LOGTAG,
 560                                        "unable to process clear message notification");
 561                            }
 562                        });
 563                break;
 564            case ACTION_CLEAR_MISSED_CALL_NOTIFICATION:
 565                mNotificationExecutor.execute(
 566                        () -> {
 567                            try {
 568                                final Conversation c = findConversationByUuid(uuid);
 569                                if (c != null) {
 570                                    mNotificationService.clearMissedCalls(c);
 571                                } else {
 572                                    mNotificationService.clearMissedCalls();
 573                                }
 574                                restoredFromDatabaseLatch.await();
 575
 576                            } catch (InterruptedException e) {
 577                                Log.d(
 578                                        Config.LOGTAG,
 579                                        "unable to process clear missed call notification");
 580                            }
 581                        });
 582                break;
 583            case ACTION_DISMISS_CALL:
 584                {
 585                    if (intent == null) {
 586                        break;
 587                    }
 588                    final String sessionId =
 589                            intent.getStringExtra(RtpSessionActivity.EXTRA_SESSION_ID);
 590                    Log.d(
 591                            Config.LOGTAG,
 592                            "received intent to dismiss call with session id " + sessionId);
 593                    mJingleConnectionManager.rejectRtpSession(sessionId);
 594                    break;
 595                }
 596            case TorServiceUtils.ACTION_STATUS:
 597                final String status =
 598                        intent == null ? null : intent.getStringExtra(TorServiceUtils.EXTRA_STATUS);
 599                // TODO port and host are in 'extras' - but this may not be a reliable source?
 600                if ("ON".equals(status)) {
 601                    handleOrbotStartedEvent();
 602                    return START_STICKY;
 603                }
 604                break;
 605            case ACTION_END_CALL:
 606                {
 607                    if (intent == null) {
 608                        break;
 609                    }
 610                    final String sessionId =
 611                            intent.getStringExtra(RtpSessionActivity.EXTRA_SESSION_ID);
 612                    Log.d(
 613                            Config.LOGTAG,
 614                            "received intent to end call with session id " + sessionId);
 615                    mJingleConnectionManager.endRtpSession(sessionId);
 616                }
 617                break;
 618            case ACTION_PROVISION_ACCOUNT:
 619                {
 620                    if (intent == null) {
 621                        break;
 622                    }
 623                    final String address = intent.getStringExtra("address");
 624                    final String password = intent.getStringExtra("password");
 625                    if (QuickConversationsService.isQuicksy()
 626                            || Strings.isNullOrEmpty(address)
 627                            || Strings.isNullOrEmpty(password)) {
 628                        break;
 629                    }
 630                    provisionAccount(address, password);
 631                    break;
 632                }
 633            case ACTION_DISMISS_ERROR_NOTIFICATIONS:
 634                dismissErrorNotifications();
 635                break;
 636            case ACTION_TRY_AGAIN:
 637                resetAllAttemptCounts(false, true);
 638                break;
 639            case ACTION_REPLY_TO_CONVERSATION:
 640                final Bundle remoteInput =
 641                        intent == null ? null : RemoteInput.getResultsFromIntent(intent);
 642                if (remoteInput == null) {
 643                    break;
 644                }
 645                final CharSequence body = remoteInput.getCharSequence("text_reply");
 646                final boolean dismissNotification =
 647                        intent.getBooleanExtra("dismiss_notification", false);
 648                final String lastMessageUuid = intent.getStringExtra("last_message_uuid");
 649                if (body == null || body.length() <= 0) {
 650                    break;
 651                }
 652                mNotificationExecutor.execute(
 653                        () -> {
 654                            try {
 655                                restoredFromDatabaseLatch.await();
 656                                final Conversation c = findConversationByUuid(uuid);
 657                                if (c != null) {
 658                                    directReply(
 659                                            c,
 660                                            body.toString(),
 661                                            lastMessageUuid,
 662                                            dismissNotification);
 663                                }
 664                            } catch (InterruptedException e) {
 665                                Log.d(Config.LOGTAG, "unable to process direct reply");
 666                            }
 667                        });
 668                break;
 669            case ACTION_MARK_AS_READ:
 670                mNotificationExecutor.execute(
 671                        () -> {
 672                            final Conversation c = findConversationByUuid(uuid);
 673                            if (c == null) {
 674                                Log.d(
 675                                        Config.LOGTAG,
 676                                        "received mark read intent for unknown conversation ("
 677                                                + uuid
 678                                                + ")");
 679                                return;
 680                            }
 681                            try {
 682                                restoredFromDatabaseLatch.await();
 683                                sendReadMarker(c, null);
 684                            } catch (InterruptedException e) {
 685                                Log.d(
 686                                        Config.LOGTAG,
 687                                        "unable to process notification read marker for"
 688                                                + " conversation "
 689                                                + c.getName());
 690                            }
 691                        });
 692                break;
 693            case ACTION_SNOOZE:
 694                mNotificationExecutor.execute(
 695                        () -> {
 696                            final Conversation c = findConversationByUuid(uuid);
 697                            if (c == null) {
 698                                Log.d(
 699                                        Config.LOGTAG,
 700                                        "received snooze intent for unknown conversation ("
 701                                                + uuid
 702                                                + ")");
 703                                return;
 704                            }
 705                            c.setMutedTill(System.currentTimeMillis() + 30 * 60 * 1000);
 706                            mNotificationService.clearMessages(c);
 707                            updateConversation(c);
 708                        });
 709            case AudioManager.RINGER_MODE_CHANGED_ACTION:
 710            case NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED:
 711                if (dndOnSilentMode()) {
 712                    refreshAllPresences();
 713                }
 714                break;
 715            case Intent.ACTION_SCREEN_ON:
 716                deactivateGracePeriod();
 717            case Intent.ACTION_USER_PRESENT:
 718            case Intent.ACTION_SCREEN_OFF:
 719                if (awayWhenScreenLocked()) {
 720                    refreshAllPresences();
 721                }
 722                break;
 723            case ACTION_FCM_TOKEN_REFRESH:
 724                refreshAllFcmTokens();
 725                break;
 726            case ACTION_RENEW_UNIFIED_PUSH_ENDPOINTS:
 727                if (intent == null) {
 728                    break;
 729                }
 730                final String instance = intent.getStringExtra("instance");
 731                final String application = intent.getStringExtra("application");
 732                final Messenger messenger = intent.getParcelableExtra("messenger");
 733                final UnifiedPushBroker.PushTargetMessenger pushTargetMessenger;
 734                if (messenger != null && application != null && instance != null) {
 735                    pushTargetMessenger =
 736                            new UnifiedPushBroker.PushTargetMessenger(
 737                                    new UnifiedPushDatabase.PushTarget(application, instance),
 738                                    messenger);
 739                    Log.d(Config.LOGTAG, "found push target messenger");
 740                } else {
 741                    pushTargetMessenger = null;
 742                }
 743                final Optional<UnifiedPushBroker.Transport> transport =
 744                        renewUnifiedPushEndpoints(pushTargetMessenger);
 745                if (instance != null && transport.isPresent()) {
 746                    unifiedPushBroker.rebroadcastEndpoint(messenger, instance, transport.get());
 747                }
 748                break;
 749            case ACTION_IDLE_PING:
 750                scheduleNextIdlePing();
 751                break;
 752            case ACTION_FCM_MESSAGE_RECEIVED:
 753                Log.d(Config.LOGTAG, "push message arrived in service. account");
 754                break;
 755            case ACTION_QUICK_LOG:
 756                final String message = intent == null ? null : intent.getStringExtra("message");
 757                if (message != null && Config.QUICK_LOG) {
 758                    quickLog(message);
 759                }
 760                break;
 761            case Intent.ACTION_SEND:
 762                final Uri uri = intent == null ? null : intent.getData();
 763                if (uri != null) {
 764                    Log.d(Config.LOGTAG, "received uri permission for " + uri);
 765                }
 766                return START_STICKY;
 767            case ACTION_TEMPORARILY_DISABLE:
 768                toggleSoftDisabled(true);
 769                if (checkListeners()) {
 770                    stopSelf();
 771                }
 772                return START_NOT_STICKY;
 773        }
 774        final var extras = intent == null ? null : intent.getExtras();
 775        try {
 776            internalPingExecutor.execute(() -> manageAccountConnectionStates(action, extras));
 777        } catch (final RejectedExecutionException e) {
 778            Log.e(Config.LOGTAG, "can not schedule connection states manager");
 779        }
 780        if (SystemClock.elapsedRealtime() - mLastExpiryRun.get() >= Config.EXPIRY_INTERVAL) {
 781            expireOldMessages();
 782        }
 783        return START_STICKY;
 784    }
 785
 786    private void quickLog(final String message) {
 787        if (Strings.isNullOrEmpty(message)) {
 788            return;
 789        }
 790        final Account account = AccountUtils.getFirstEnabled(this);
 791        if (account == null) {
 792            return;
 793        }
 794        final Conversation conversation =
 795                findOrCreateConversation(account, Config.BUG_REPORTS, false, true);
 796        final Message report = new Message(conversation, message, Message.ENCRYPTION_NONE);
 797        report.setStatus(Message.STATUS_RECEIVED);
 798        conversation.add(report);
 799        databaseBackend.createMessage(report);
 800        updateConversationUi();
 801    }
 802
 803    public void manageAccountConnectionStatesInternal() {
 804        manageAccountConnectionStates(ACTION_INTERNAL_PING, null);
 805    }
 806
 807    private synchronized void manageAccountConnectionStates(
 808            final String action, final Bundle extras) {
 809        final String pushedAccountHash = extras == null ? null : extras.getString("account");
 810        final boolean interactive = java.util.Objects.equals(ACTION_TRY_AGAIN, action);
 811        WakeLockHelper.acquire(wakeLock);
 812        boolean pingNow =
 813                ConnectivityManager.CONNECTIVITY_ACTION.equals(action)
 814                        || (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL > 0
 815                                && ACTION_POST_CONNECTIVITY_CHANGE.equals(action));
 816        final HashSet<Account> pingCandidates = new HashSet<>();
 817        final String androidId = pushedAccountHash == null ? null : PhoneHelper.getAndroidId(this);
 818        for (final Account account : accounts) {
 819            final boolean pushWasMeantForThisAccount =
 820                    androidId != null
 821                            && CryptoHelper.getAccountFingerprint(account, androidId)
 822                                    .equals(pushedAccountHash);
 823            pingNow |=
 824                    processAccountState(
 825                            account,
 826                            interactive,
 827                            "ui".equals(action),
 828                            pushWasMeantForThisAccount,
 829                            pingCandidates);
 830        }
 831        if (pingNow) {
 832            for (final Account account : pingCandidates) {
 833                final var connection = account.getXmppConnection();
 834                final boolean lowTimeout = isInLowPingTimeoutMode(account);
 835                final var delta =
 836                        (SystemClock.elapsedRealtime() - connection.getLastPacketReceived())
 837                                / 1000L;
 838                connection.sendPing();
 839                Log.d(
 840                        Config.LOGTAG,
 841                        String.format(
 842                                "%s: send ping (action=%s,lowTimeout=%s,interval=%s)",
 843                                account.getJid().asBareJid(), action, lowTimeout, delta));
 844                scheduleWakeUpCall(
 845                        lowTimeout ? Config.LOW_PING_TIMEOUT : Config.PING_TIMEOUT,
 846                        account.getUuid().hashCode());
 847            }
 848        }
 849        WakeLockHelper.release(wakeLock);
 850    }
 851
 852    private void handleOrbotStartedEvent() {
 853        for (final Account account : accounts) {
 854            if (account.getStatus() == Account.State.TOR_NOT_AVAILABLE) {
 855                reconnectAccount(account, true, false);
 856            }
 857        }
 858    }
 859
 860    private boolean processAccountState(
 861            final Account account,
 862            final boolean interactive,
 863            final boolean isUiAction,
 864            final boolean isAccountPushed,
 865            final HashSet<Account> pingCandidates) {
 866        final var connection = account.getXmppConnection();
 867        if (!account.getStatus().isAttemptReconnect()) {
 868            return false;
 869        }
 870        final var requestCode = account.getUuid().hashCode();
 871        if (!hasInternetConnection()) {
 872            connection.setStatusAndTriggerProcessor(Account.State.NO_INTERNET);
 873        } else {
 874            if (account.getStatus() == Account.State.NO_INTERNET) {
 875                connection.setStatusAndTriggerProcessor(Account.State.OFFLINE);
 876            }
 877            if (account.getStatus() == Account.State.ONLINE) {
 878                synchronized (mLowPingTimeoutMode) {
 879                    long lastReceived = account.getXmppConnection().getLastPacketReceived();
 880                    long lastSent = account.getXmppConnection().getLastPingSent();
 881                    long pingInterval =
 882                            isUiAction
 883                                    ? Config.PING_MIN_INTERVAL * 1000
 884                                    : Config.PING_MAX_INTERVAL * 1000;
 885                    long msToNextPing =
 886                            (Math.max(lastReceived, lastSent) + pingInterval)
 887                                    - SystemClock.elapsedRealtime();
 888                    int pingTimeout =
 889                            mLowPingTimeoutMode.contains(account.getJid().asBareJid())
 890                                    ? Config.LOW_PING_TIMEOUT * 1000
 891                                    : Config.PING_TIMEOUT * 1000;
 892                    long pingTimeoutIn = (lastSent + pingTimeout) - SystemClock.elapsedRealtime();
 893                    if (lastSent > lastReceived) {
 894                        if (pingTimeoutIn < 0) {
 895                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ping timeout");
 896                            this.reconnectAccount(account, true, interactive);
 897                        } else {
 898                            this.scheduleWakeUpCall(pingTimeoutIn, requestCode);
 899                        }
 900                    } else {
 901                        pingCandidates.add(account);
 902                        if (isAccountPushed) {
 903                            if (mLowPingTimeoutMode.add(account.getJid().asBareJid())) {
 904                                Log.d(
 905                                        Config.LOGTAG,
 906                                        account.getJid().asBareJid()
 907                                                + ": entering low ping timeout mode");
 908                            }
 909                            return true;
 910                        } else if (msToNextPing <= 0) {
 911                            return true;
 912                        } else {
 913                            this.scheduleWakeUpCall(msToNextPing, requestCode);
 914                            if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
 915                                Log.d(
 916                                        Config.LOGTAG,
 917                                        account.getJid().asBareJid()
 918                                                + ": leaving low ping timeout mode");
 919                            }
 920                        }
 921                    }
 922                }
 923            } else if (account.getStatus() == Account.State.OFFLINE) {
 924                reconnectAccount(account, true, interactive);
 925            } else if (account.getStatus() == Account.State.CONNECTING) {
 926                final var connectionDuration = connection.getConnectionDuration();
 927                final var discoDuration = connection.getDiscoDuration();
 928                final var connectionTimeout = Config.CONNECT_TIMEOUT * 1000L - connectionDuration;
 929                final var discoTimeout = Config.CONNECT_DISCO_TIMEOUT * 1000L - discoDuration;
 930                if (connectionTimeout < 0) {
 931                    connection.triggerConnectionTimeout();
 932                } else if (discoTimeout < 0) {
 933                    connection.sendDiscoTimeout();
 934                    scheduleWakeUpCall(discoTimeout, requestCode);
 935                } else {
 936                    scheduleWakeUpCall(Math.min(connectionTimeout, discoTimeout), requestCode);
 937                }
 938            } else {
 939                final boolean aggressive =
 940                        account.getStatus() == Account.State.SEE_OTHER_HOST
 941                                || hasJingleRtpConnection(account);
 942                if (connection.getTimeToNextAttempt(aggressive) <= 0) {
 943                    reconnectAccount(account, true, interactive);
 944                }
 945            }
 946        }
 947        return false;
 948    }
 949
 950    private void toggleSoftDisabled(final boolean softDisabled) {
 951        for (final Account account : this.accounts) {
 952            if (account.isEnabled()) {
 953                if (account.setOption(Account.OPTION_SOFT_DISABLED, softDisabled)) {
 954                    updateAccount(account);
 955                }
 956            }
 957        }
 958    }
 959
 960    public void fetchServiceOutageStatus(final Account account) {
 961        final var sosUrl = account.getKey(Account.KEY_SOS_URL);
 962        if (Strings.isNullOrEmpty(sosUrl)) {
 963            return;
 964        }
 965        final var url = HttpUrl.parse(sosUrl);
 966        if (url == null) {
 967            return;
 968        }
 969        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching service outage " + url);
 970        Futures.addCallback(
 971                ServiceOutageStatus.fetch(getApplicationContext(), url),
 972                new FutureCallback<>() {
 973                    @Override
 974                    public void onSuccess(final ServiceOutageStatus sos) {
 975                        Log.d(Config.LOGTAG, "fetched " + sos);
 976                        account.setServiceOutageStatus(sos);
 977                        updateAccountUi();
 978                    }
 979
 980                    @Override
 981                    public void onFailure(@NonNull Throwable throwable) {
 982                        Log.d(Config.LOGTAG, "error fetching sos", throwable);
 983                    }
 984                },
 985                MoreExecutors.directExecutor());
 986    }
 987
 988    public boolean processUnifiedPushMessage(
 989            final Account account, final Jid transport, final Push push) {
 990        return unifiedPushBroker.processPushMessage(account, transport, push);
 991    }
 992
 993    public void reinitializeMuclumbusService() {
 994        mChannelDiscoveryService.initializeMuclumbusService();
 995    }
 996
 997    public void discoverChannels(
 998            String query,
 999            ChannelDiscoveryService.Method method,
1000            ChannelDiscoveryService.OnChannelSearchResultsFound onChannelSearchResultsFound) {
1001        mChannelDiscoveryService.discover(
1002                Strings.nullToEmpty(query).trim(), method, onChannelSearchResultsFound);
1003    }
1004
1005    public boolean isDataSaverDisabled() {
1006        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
1007            return true;
1008        }
1009        final ConnectivityManager connectivityManager = getSystemService(ConnectivityManager.class);
1010        return !Compatibility.isActiveNetworkMetered(connectivityManager)
1011                || Compatibility.getRestrictBackgroundStatus(connectivityManager)
1012                        == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
1013    }
1014
1015    private void directReply(
1016            final Conversation conversation,
1017            final String body,
1018            final String lastMessageUuid,
1019            final boolean dismissAfterReply) {
1020        final Message inReplyTo =
1021                lastMessageUuid == null ? null : conversation.findMessageWithUuid(lastMessageUuid);
1022        final Message message = new Message(conversation, body, conversation.getNextEncryption());
1023        if (inReplyTo != null && inReplyTo.isPrivateMessage()) {
1024            Message.configurePrivateMessage(message, inReplyTo.getCounterpart());
1025        }
1026        message.markUnread();
1027        if (message.getEncryption() == Message.ENCRYPTION_PGP) {
1028            getPgpEngine()
1029                    .encrypt(
1030                            message,
1031                            new UiCallback<Message>() {
1032                                @Override
1033                                public void success(Message message) {
1034                                    if (dismissAfterReply) {
1035                                        markRead((Conversation) message.getConversation(), true);
1036                                    } else {
1037                                        mNotificationService.pushFromDirectReply(message);
1038                                    }
1039                                }
1040
1041                                @Override
1042                                public void error(int errorCode, Message object) {}
1043
1044                                @Override
1045                                public void userInputRequired(PendingIntent pi, Message object) {}
1046                            });
1047        } else {
1048            sendMessage(message);
1049            if (dismissAfterReply) {
1050                markRead(conversation, true);
1051            } else {
1052                mNotificationService.pushFromDirectReply(message);
1053            }
1054        }
1055    }
1056
1057    private boolean dndOnSilentMode() {
1058        return getBooleanPreference(AppSettings.DND_ON_SILENT_MODE, R.bool.dnd_on_silent_mode);
1059    }
1060
1061    private boolean manuallyChangePresence() {
1062        return getBooleanPreference(
1063                AppSettings.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
1064    }
1065
1066    private boolean treatVibrateAsSilent() {
1067        return getBooleanPreference(
1068                AppSettings.TREAT_VIBRATE_AS_SILENT, R.bool.treat_vibrate_as_silent);
1069    }
1070
1071    private boolean awayWhenScreenLocked() {
1072        return getBooleanPreference(
1073                AppSettings.AWAY_WHEN_SCREEN_IS_OFF, R.bool.away_when_screen_off);
1074    }
1075
1076    private String getCompressPicturesPreference() {
1077        return getPreferences()
1078                .getString(
1079                        "picture_compression",
1080                        getResources().getString(R.string.picture_compression));
1081    }
1082
1083    private im.conversations.android.xmpp.model.stanza.Presence.Availability getTargetPresence() {
1084        if (dndOnSilentMode() && isPhoneSilenced()) {
1085            return im.conversations.android.xmpp.model.stanza.Presence.Availability.DND;
1086        } else if (awayWhenScreenLocked() && isScreenLocked()) {
1087            return im.conversations.android.xmpp.model.stanza.Presence.Availability.AWAY;
1088        } else {
1089            return im.conversations.android.xmpp.model.stanza.Presence.Availability.ONLINE;
1090        }
1091    }
1092
1093    public boolean isScreenLocked() {
1094        final KeyguardManager keyguardManager = getSystemService(KeyguardManager.class);
1095        final PowerManager powerManager = getSystemService(PowerManager.class);
1096        final boolean locked = keyguardManager != null && keyguardManager.isKeyguardLocked();
1097        final boolean interactive;
1098        try {
1099            interactive = powerManager != null && powerManager.isInteractive();
1100        } catch (final Exception e) {
1101            return false;
1102        }
1103        return locked || !interactive;
1104    }
1105
1106    private boolean isPhoneSilenced() {
1107        final NotificationManager notificationManager = getSystemService(NotificationManager.class);
1108        final int filter =
1109                notificationManager == null
1110                        ? NotificationManager.INTERRUPTION_FILTER_UNKNOWN
1111                        : notificationManager.getCurrentInterruptionFilter();
1112        final boolean notificationDnd = filter >= NotificationManager.INTERRUPTION_FILTER_PRIORITY;
1113        final AudioManager audioManager = getSystemService(AudioManager.class);
1114        final int ringerMode =
1115                audioManager == null
1116                        ? AudioManager.RINGER_MODE_NORMAL
1117                        : audioManager.getRingerMode();
1118        try {
1119            if (treatVibrateAsSilent()) {
1120                return notificationDnd || ringerMode != AudioManager.RINGER_MODE_NORMAL;
1121            } else {
1122                return notificationDnd || ringerMode == AudioManager.RINGER_MODE_SILENT;
1123            }
1124        } catch (final Throwable throwable) {
1125            Log.d(
1126                    Config.LOGTAG,
1127                    "platform bug in isPhoneSilenced (" + throwable.getMessage() + ")");
1128            return notificationDnd;
1129        }
1130    }
1131
1132    private void resetAllAttemptCounts(boolean reallyAll, boolean retryImmediately) {
1133        Log.d(Config.LOGTAG, "resetting all attempt counts");
1134        for (Account account : accounts) {
1135            if (account.hasErrorStatus() || reallyAll) {
1136                final XmppConnection connection = account.getXmppConnection();
1137                if (connection != null) {
1138                    connection.resetAttemptCount(retryImmediately);
1139                }
1140            }
1141            if (account.setShowErrorNotification(true)) {
1142                mDatabaseWriterExecutor.execute(() -> databaseBackend.updateAccount(account));
1143            }
1144        }
1145        mNotificationService.updateErrorNotification();
1146    }
1147
1148    private void dismissErrorNotifications() {
1149        for (final Account account : this.accounts) {
1150            if (account.hasErrorStatus()) {
1151                Log.d(
1152                        Config.LOGTAG,
1153                        account.getJid().asBareJid() + ": dismissing error notification");
1154                if (account.setShowErrorNotification(false)) {
1155                    mDatabaseWriterExecutor.execute(() -> databaseBackend.updateAccount(account));
1156                }
1157            }
1158        }
1159    }
1160
1161    private void expireOldMessages() {
1162        expireOldMessages(false);
1163    }
1164
1165    public void expireOldMessages(final boolean resetHasMessagesLeftOnServer) {
1166        mLastExpiryRun.set(SystemClock.elapsedRealtime());
1167        mDatabaseWriterExecutor.execute(
1168                () -> {
1169                    long timestamp = getAutomaticMessageDeletionDate();
1170                    if (timestamp > 0) {
1171                        databaseBackend.expireOldMessages(timestamp);
1172                        synchronized (XmppConnectionService.this.conversations) {
1173                            for (Conversation conversation :
1174                                    XmppConnectionService.this.conversations) {
1175                                conversation.expireOldMessages(timestamp);
1176                                if (resetHasMessagesLeftOnServer) {
1177                                    conversation.messagesLoaded.set(true);
1178                                    conversation.setHasMessagesLeftOnServer(true);
1179                                }
1180                            }
1181                        }
1182                        updateConversationUi();
1183                    }
1184                });
1185    }
1186
1187    public boolean hasInternetConnection() {
1188        final ConnectivityManager cm =
1189                ContextCompat.getSystemService(this, ConnectivityManager.class);
1190        if (cm == null) {
1191            return true; // if internet connection can not be checked it is probably best to just
1192            // try
1193        }
1194        try {
1195            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
1196                final Network activeNetwork = cm.getActiveNetwork();
1197                final NetworkCapabilities capabilities =
1198                        activeNetwork == null ? null : cm.getNetworkCapabilities(activeNetwork);
1199                return capabilities != null
1200                        && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1201            } else {
1202                final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
1203                return networkInfo != null
1204                        && (networkInfo.isConnected()
1205                                || networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET);
1206            }
1207        } catch (final RuntimeException e) {
1208            Log.d(Config.LOGTAG, "unable to check for internet connection", e);
1209            return true; // if internet connection can not be checked it is probably best to just
1210            // try
1211        }
1212    }
1213
1214    @SuppressLint("TrulyRandom")
1215    @Override
1216    public void onCreate() {
1217        LibIdnXmppStringprep.setup();
1218        if (Compatibility.twentySix()) {
1219            mNotificationService.initializeChannels();
1220        }
1221        mChannelDiscoveryService.initializeMuclumbusService();
1222        mForceDuringOnCreate.set(Compatibility.twentySix());
1223        toggleForegroundService();
1224        this.destroyed = false;
1225        OmemoSetting.load(this);
1226        try {
1227            Security.insertProviderAt(Conscrypt.newProvider(), 1);
1228        } catch (Throwable throwable) {
1229            Log.e(Config.LOGTAG, "unable to initialize security provider", throwable);
1230        }
1231        updateMemorizingTrustManager();
1232        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
1233        final int cacheSize = maxMemory / 8;
1234        this.mBitmapCache =
1235                new LruCache<String, Bitmap>(cacheSize) {
1236                    @Override
1237                    protected int sizeOf(final String key, final Bitmap bitmap) {
1238                        return bitmap.getByteCount() / 1024;
1239                    }
1240                };
1241        if (mLastActivity == 0) {
1242            mLastActivity =
1243                    getPreferences().getLong(SETTING_LAST_ACTIVITY_TS, System.currentTimeMillis());
1244        }
1245
1246        Log.d(Config.LOGTAG, "initializing database...");
1247        this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
1248        Log.d(Config.LOGTAG, "restoring accounts...");
1249        this.accounts = databaseBackend.getAccounts();
1250        for (final var account : this.accounts) {
1251            account.setXmppConnection(createConnection(account));
1252        }
1253        final SharedPreferences.Editor editor = getPreferences().edit();
1254        final boolean hasEnabledAccounts = hasEnabledAccounts();
1255        editor.putBoolean(SystemEventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
1256        editor.apply();
1257        toggleSetProfilePictureActivity(hasEnabledAccounts);
1258        reconfigurePushDistributor();
1259
1260        if (CallIntegration.hasSystemFeature(this)) {
1261            CallIntegrationConnectionService.togglePhoneAccountsAsync(this, this.accounts);
1262        }
1263
1264        restoreFromDatabase();
1265
1266        if (QuickConversationsService.isContactListIntegration(this)
1267                && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
1268                        == PackageManager.PERMISSION_GRANTED) {
1269            startContactObserver();
1270        }
1271        FILE_OBSERVER_EXECUTOR.execute(fileBackend::deleteHistoricAvatarPath);
1272        if (Compatibility.hasStoragePermission(this)) {
1273            Log.d(Config.LOGTAG, "starting file observer");
1274            FILE_OBSERVER_EXECUTOR.execute(this.fileObserver::startWatching);
1275            FILE_OBSERVER_EXECUTOR.execute(this::checkForDeletedFiles);
1276        }
1277        if (Config.supportOpenPgp()) {
1278            this.pgpServiceConnection =
1279                    new OpenPgpServiceConnection(
1280                            this,
1281                            "org.sufficientlysecure.keychain",
1282                            new OpenPgpServiceConnection.OnBound() {
1283                                @Override
1284                                public void onBound(final IOpenPgpService2 service) {
1285                                    for (Account account : accounts) {
1286                                        final PgpDecryptionService pgp =
1287                                                account.getPgpDecryptionService();
1288                                        if (pgp != null) {
1289                                            pgp.continueDecryption(true);
1290                                        }
1291                                    }
1292                                }
1293
1294                                @Override
1295                                public void onError(final Exception exception) {
1296                                    Log.e(
1297                                            Config.LOGTAG,
1298                                            "could not bind to OpenKeyChain",
1299                                            exception);
1300                                }
1301                            });
1302            this.pgpServiceConnection.bindToService();
1303        }
1304
1305        final PowerManager powerManager = getSystemService(PowerManager.class);
1306        if (powerManager != null) {
1307            this.wakeLock =
1308                    powerManager.newWakeLock(
1309                            PowerManager.PARTIAL_WAKE_LOCK, "Conversations:Service");
1310        }
1311
1312        toggleForegroundService();
1313        updateUnreadCountBadge();
1314        toggleScreenEventReceiver();
1315        final IntentFilter systemBroadcastFilter = new IntentFilter();
1316        scheduleNextIdlePing();
1317        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1318            systemBroadcastFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1319        }
1320        systemBroadcastFilter.addAction(NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED);
1321        ContextCompat.registerReceiver(
1322                this,
1323                this.mInternalEventReceiver,
1324                systemBroadcastFilter,
1325                ContextCompat.RECEIVER_NOT_EXPORTED);
1326        final IntentFilter exportedBroadcastFilter = new IntentFilter();
1327        exportedBroadcastFilter.addAction(TorServiceUtils.ACTION_STATUS);
1328        ContextCompat.registerReceiver(
1329                this,
1330                this.mInternalRestrictedEventReceiver,
1331                exportedBroadcastFilter,
1332                ContextCompat.RECEIVER_EXPORTED);
1333        mForceDuringOnCreate.set(false);
1334        toggleForegroundService();
1335        internalPingExecutor.scheduleWithFixedDelay(
1336                this::manageAccountConnectionStatesInternal, 10, 10, TimeUnit.SECONDS);
1337        final SharedPreferences sharedPreferences =
1338                androidx.preference.PreferenceManager.getDefaultSharedPreferences(this);
1339        sharedPreferences.registerOnSharedPreferenceChangeListener(
1340                new SharedPreferences.OnSharedPreferenceChangeListener() {
1341                    @Override
1342                    public void onSharedPreferenceChanged(
1343                            SharedPreferences sharedPreferences, @Nullable String key) {
1344                        Log.d(Config.LOGTAG, "preference '" + key + "' has changed");
1345                        if (AppSettings.KEEP_FOREGROUND_SERVICE.equals(key)) {
1346                            toggleForegroundService();
1347                        }
1348                    }
1349                });
1350    }
1351
1352    private void checkForDeletedFiles() {
1353        if (destroyed) {
1354            Log.d(
1355                    Config.LOGTAG,
1356                    "Do not check for deleted files because service has been destroyed");
1357            return;
1358        }
1359        final long start = SystemClock.elapsedRealtime();
1360        final List<DatabaseBackend.FilePathInfo> relativeFilePaths =
1361                databaseBackend.getFilePathInfo();
1362        final List<DatabaseBackend.FilePathInfo> changed = new ArrayList<>();
1363        for (final DatabaseBackend.FilePathInfo filePath : relativeFilePaths) {
1364            if (destroyed) {
1365                Log.d(
1366                        Config.LOGTAG,
1367                        "Stop checking for deleted files because service has been destroyed");
1368                return;
1369            }
1370            final File file = fileBackend.getFileForPath(filePath.path);
1371            if (filePath.setDeleted(!file.exists())) {
1372                changed.add(filePath);
1373            }
1374        }
1375        final long duration = SystemClock.elapsedRealtime() - start;
1376        Log.d(
1377                Config.LOGTAG,
1378                "found "
1379                        + changed.size()
1380                        + " changed files on start up. total="
1381                        + relativeFilePaths.size()
1382                        + ". ("
1383                        + duration
1384                        + "ms)");
1385        if (changed.size() > 0) {
1386            databaseBackend.markFilesAsChanged(changed);
1387            markChangedFiles(changed);
1388        }
1389    }
1390
1391    public void startContactObserver() {
1392        getContentResolver()
1393                .registerContentObserver(
1394                        ContactsContract.Contacts.CONTENT_URI,
1395                        true,
1396                        new ContentObserver(null) {
1397                            @Override
1398                            public void onChange(boolean selfChange) {
1399                                super.onChange(selfChange);
1400                                if (restoredFromDatabaseLatch.getCount() == 0) {
1401                                    loadPhoneContacts();
1402                                }
1403                            }
1404                        });
1405    }
1406
1407    @Override
1408    public void onTrimMemory(int level) {
1409        super.onTrimMemory(level);
1410        if (level >= TRIM_MEMORY_COMPLETE) {
1411            Log.d(Config.LOGTAG, "clear cache due to low memory");
1412            getBitmapCache().evictAll();
1413        }
1414    }
1415
1416    @Override
1417    public void onDestroy() {
1418        try {
1419            unregisterReceiver(this.mInternalEventReceiver);
1420            unregisterReceiver(this.mInternalRestrictedEventReceiver);
1421            unregisterReceiver(this.mInternalScreenEventReceiver);
1422        } catch (final IllegalArgumentException e) {
1423            // ignored
1424        }
1425        destroyed = false;
1426        fileObserver.stopWatching();
1427        internalPingExecutor.shutdown();
1428        super.onDestroy();
1429    }
1430
1431    public void restartFileObserver() {
1432        Log.d(Config.LOGTAG, "restarting file observer");
1433        FILE_OBSERVER_EXECUTOR.execute(this.fileObserver::restartWatching);
1434        FILE_OBSERVER_EXECUTOR.execute(this::checkForDeletedFiles);
1435    }
1436
1437    public void toggleScreenEventReceiver() {
1438        if (awayWhenScreenLocked() && !manuallyChangePresence()) {
1439            final IntentFilter filter = new IntentFilter();
1440            filter.addAction(Intent.ACTION_SCREEN_ON);
1441            filter.addAction(Intent.ACTION_SCREEN_OFF);
1442            filter.addAction(Intent.ACTION_USER_PRESENT);
1443            registerReceiver(this.mInternalScreenEventReceiver, filter);
1444        } else {
1445            try {
1446                unregisterReceiver(this.mInternalScreenEventReceiver);
1447            } catch (IllegalArgumentException e) {
1448                // ignored
1449            }
1450        }
1451    }
1452
1453    public void toggleForegroundService() {
1454        toggleForegroundService(false);
1455    }
1456
1457    public void setOngoingCall(
1458            AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
1459        ongoingCall.set(new OngoingCall(id, media, reconnecting));
1460        toggleForegroundService(false);
1461    }
1462
1463    public void removeOngoingCall() {
1464        ongoingCall.set(null);
1465        toggleForegroundService(false);
1466    }
1467
1468    private void toggleForegroundService(final boolean force) {
1469        final boolean status;
1470        final OngoingCall ongoing = ongoingCall.get();
1471        final boolean ongoingVideoTranscoding = mOngoingVideoTranscoding.get();
1472        final int id;
1473        if (force
1474                || mForceDuringOnCreate.get()
1475                || ongoingVideoTranscoding
1476                || ongoing != null
1477                || (appSettings.isKeepForegroundService() && hasEnabledAccounts())) {
1478            final Notification notification;
1479            if (ongoing != null) {
1480                notification = this.mNotificationService.getOngoingCallNotification(ongoing);
1481                id = NotificationService.ONGOING_CALL_NOTIFICATION_ID;
1482                startForegroundOrCatch(id, notification, true);
1483            } else if (ongoingVideoTranscoding) {
1484                notification = this.mNotificationService.getIndeterminateVideoTranscoding();
1485                id = NotificationService.ONGOING_VIDEO_TRANSCODING_NOTIFICATION_ID;
1486                startForegroundOrCatch(id, notification, false);
1487            } else {
1488                notification = this.mNotificationService.createForegroundNotification();
1489                id = NotificationService.FOREGROUND_NOTIFICATION_ID;
1490                startForegroundOrCatch(id, notification, false);
1491            }
1492            mNotificationService.notify(id, notification);
1493            status = true;
1494        } else {
1495            id = 0;
1496            stopForeground(true);
1497            status = false;
1498        }
1499
1500        for (final int toBeRemoved :
1501                Collections2.filter(
1502                        Arrays.asList(
1503                                NotificationService.FOREGROUND_NOTIFICATION_ID,
1504                                NotificationService.ONGOING_CALL_NOTIFICATION_ID,
1505                                NotificationService.ONGOING_VIDEO_TRANSCODING_NOTIFICATION_ID),
1506                        i -> i != id)) {
1507            mNotificationService.cancel(toBeRemoved);
1508        }
1509        Log.d(
1510                Config.LOGTAG,
1511                "ForegroundService: " + (status ? "on" : "off") + ", notification: " + id);
1512    }
1513
1514    private void startForegroundOrCatch(
1515            final int id, final Notification notification, final boolean requireMicrophone) {
1516        try {
1517            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
1518                final int foregroundServiceType;
1519                if (requireMicrophone
1520                        && ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
1521                                == PackageManager.PERMISSION_GRANTED) {
1522                    foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE;
1523                    Log.d(Config.LOGTAG, "defaulting to microphone foreground service type");
1524                } else if (getSystemService(PowerManager.class)
1525                        .isIgnoringBatteryOptimizations(getPackageName())) {
1526                    foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED;
1527                } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
1528                        == PackageManager.PERMISSION_GRANTED) {
1529                    foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE;
1530                } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
1531                        == PackageManager.PERMISSION_GRANTED) {
1532                    foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA;
1533                } else {
1534                    foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE;
1535                    Log.w(Config.LOGTAG, "falling back to special use foreground service type");
1536                }
1537                startForeground(id, notification, foregroundServiceType);
1538            } else {
1539                startForeground(id, notification);
1540            }
1541        } catch (final IllegalStateException | SecurityException e) {
1542            Log.e(Config.LOGTAG, "Could not start foreground service", e);
1543        }
1544    }
1545
1546    public boolean foregroundNotificationNeedsUpdatingWhenErrorStateChanges() {
1547        return !mOngoingVideoTranscoding.get()
1548                && ongoingCall.get() == null
1549                && appSettings.isKeepForegroundService()
1550                && hasEnabledAccounts();
1551    }
1552
1553    @Override
1554    public void onTaskRemoved(final Intent rootIntent) {
1555        super.onTaskRemoved(rootIntent);
1556        if ((appSettings.isKeepForegroundService() && hasEnabledAccounts())
1557                || mOngoingVideoTranscoding.get()
1558                || ongoingCall.get() != null) {
1559            Log.d(Config.LOGTAG, "ignoring onTaskRemoved because foreground service is activated");
1560        } else {
1561            this.logoutAndSave(false);
1562        }
1563    }
1564
1565    private void logoutAndSave(boolean stop) {
1566        int activeAccounts = 0;
1567        for (final Account account : accounts) {
1568            if (account.isConnectionEnabled()) {
1569                account.getXmppConnection().getManager(RosterManager.class).writeToDatabase();
1570                activeAccounts++;
1571            }
1572            if (account.getXmppConnection() != null) {
1573                new Thread(() -> disconnect(account, false)).start();
1574            }
1575        }
1576        if (stop || activeAccounts == 0) {
1577            Log.d(Config.LOGTAG, "good bye");
1578            stopSelf();
1579        }
1580    }
1581
1582    private void schedulePostConnectivityChange() {
1583        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1584        if (alarmManager == null) {
1585            return;
1586        }
1587        final long triggerAtMillis =
1588                SystemClock.elapsedRealtime()
1589                        + (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL * 1000);
1590        final Intent intent = new Intent(this, SystemEventReceiver.class);
1591        intent.setAction(ACTION_POST_CONNECTIVITY_CHANGE);
1592        try {
1593            final PendingIntent pendingIntent =
1594                    PendingIntent.getBroadcast(
1595                            this,
1596                            1,
1597                            intent,
1598                            s()
1599                                    ? PendingIntent.FLAG_IMMUTABLE
1600                                            | PendingIntent.FLAG_UPDATE_CURRENT
1601                                    : PendingIntent.FLAG_UPDATE_CURRENT);
1602            alarmManager.setAndAllowWhileIdle(
1603                    AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1604        } catch (RuntimeException e) {
1605            Log.e(Config.LOGTAG, "unable to schedule alarm for post connectivity change", e);
1606        }
1607    }
1608
1609    public void scheduleWakeUpCall(final int seconds, final int requestCode) {
1610        scheduleWakeUpCall((seconds < 0 ? 1 : seconds + 1) * 1000L, requestCode);
1611    }
1612
1613    public void scheduleWakeUpCall(final long milliSeconds, final int requestCode) {
1614        final var timeToWake = SystemClock.elapsedRealtime() + milliSeconds;
1615        final var alarmManager = getSystemService(AlarmManager.class);
1616        final Intent intent = new Intent(this, SystemEventReceiver.class);
1617        intent.setAction(ACTION_PING);
1618        try {
1619            final PendingIntent pendingIntent =
1620                    PendingIntent.getBroadcast(
1621                            this, requestCode, intent, PendingIntent.FLAG_IMMUTABLE);
1622            alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1623        } catch (final RuntimeException e) {
1624            Log.e(Config.LOGTAG, "unable to schedule alarm for ping", e);
1625        }
1626    }
1627
1628    private void scheduleNextIdlePing() {
1629        final long timeToWake = SystemClock.elapsedRealtime() + (Config.IDLE_PING_INTERVAL * 1000);
1630        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1631        if (alarmManager == null) {
1632            return;
1633        }
1634        final Intent intent = new Intent(this, SystemEventReceiver.class);
1635        intent.setAction(ACTION_IDLE_PING);
1636        try {
1637            final PendingIntent pendingIntent =
1638                    PendingIntent.getBroadcast(
1639                            this,
1640                            0,
1641                            intent,
1642                            s()
1643                                    ? PendingIntent.FLAG_IMMUTABLE
1644                                            | PendingIntent.FLAG_UPDATE_CURRENT
1645                                    : PendingIntent.FLAG_UPDATE_CURRENT);
1646            alarmManager.setAndAllowWhileIdle(
1647                    AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1648        } catch (RuntimeException e) {
1649            Log.d(Config.LOGTAG, "unable to schedule alarm for idle ping", e);
1650        }
1651    }
1652
1653    public XmppConnection createConnection(final Account account) {
1654        final XmppConnection connection = new XmppConnection(account, this);
1655        connection.setOnJinglePacketReceivedListener((mJingleConnectionManager::deliverPacket));
1656        connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
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        // TODO execute this via the respective Managers
3565        deleteVcardAvatar(account, onDeleted);
3566        deletePepNode(account, Namespace.AVATAR_DATA);
3567        deletePepNode(account, Namespace.AVATAR_METADATA, onDeleted);
3568    }
3569
3570    public void deletePepNode(final Account account, final String node) {
3571        deletePepNode(account, node, null);
3572    }
3573
3574    private void deletePepNode(final Account account, final String node, final Runnable runnable) {
3575        final Iq request = mIqGenerator.deleteNode(node);
3576        sendIqPacket(
3577                account,
3578                request,
3579                (packet) -> {
3580                    if (packet.getType() == Iq.Type.RESULT) {
3581                        Log.d(
3582                                Config.LOGTAG,
3583                                account.getJid().asBareJid()
3584                                        + ": successfully deleted pep node "
3585                                        + node);
3586                        if (runnable != null) {
3587                            runnable.run();
3588                        }
3589                    } else {
3590                        Log.d(
3591                                Config.LOGTAG,
3592                                account.getJid().asBareJid() + ": failed to delete " + packet);
3593                    }
3594                });
3595    }
3596
3597    private void deleteVcardAvatar(final Account account, @NonNull final Runnable runnable) {
3598        final Iq retrieveVcard = mIqGenerator.retrieveVcardAvatar(account.getJid().asBareJid());
3599        sendIqPacket(
3600                account,
3601                retrieveVcard,
3602                (response) -> {
3603                    if (response.getType() != Iq.Type.RESULT) {
3604                        Log.d(
3605                                Config.LOGTAG,
3606                                account.getJid().asBareJid() + ": no vCard set. nothing to do");
3607                        return;
3608                    }
3609                    final Element vcard = response.findChild("vCard", "vcard-temp");
3610                    if (vcard == null) {
3611                        Log.d(
3612                                Config.LOGTAG,
3613                                account.getJid().asBareJid() + ": no vCard set. nothing to do");
3614                        return;
3615                    }
3616                    Element photo = vcard.findChild("PHOTO");
3617                    if (photo == null) {
3618                        photo = vcard.addChild("PHOTO");
3619                    }
3620                    photo.clearChildren();
3621                    final Iq publication = new Iq(Iq.Type.SET);
3622                    publication.setTo(account.getJid().asBareJid());
3623                    publication.addChild(vcard);
3624                    sendIqPacket(
3625                            account,
3626                            publication,
3627                            (publicationResponse) -> {
3628                                if (publicationResponse.getType() == Iq.Type.RESULT) {
3629                                    Log.d(
3630                                            Config.LOGTAG,
3631                                            account.getJid().asBareJid()
3632                                                    + ": successfully deleted vcard avatar");
3633                                    runnable.run();
3634                                } else {
3635                                    Log.d(
3636                                            Config.LOGTAG,
3637                                            "failed to publish vcard "
3638                                                    + publicationResponse.getErrorCondition());
3639                                }
3640                            });
3641                });
3642    }
3643
3644    private boolean hasEnabledAccounts() {
3645        if (this.accounts == null) {
3646            return false;
3647        }
3648        for (final Account account : this.accounts) {
3649            if (account.isConnectionEnabled()) {
3650                return true;
3651            }
3652        }
3653        return false;
3654    }
3655
3656    public void getAttachments(
3657            final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
3658        getAttachments(
3659                conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
3660    }
3661
3662    public void getAttachments(
3663            final Account account,
3664            final Jid jid,
3665            final int limit,
3666            final OnMediaLoaded onMediaLoaded) {
3667        getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
3668    }
3669
3670    public void getAttachments(
3671            final String account,
3672            final Jid jid,
3673            final int limit,
3674            final OnMediaLoaded onMediaLoaded) {
3675        new Thread(
3676                        () ->
3677                                onMediaLoaded.onMediaLoaded(
3678                                        fileBackend.convertToAttachments(
3679                                                databaseBackend.getRelativeFilePaths(
3680                                                        account, jid, limit))))
3681                .start();
3682    }
3683
3684    public void persistSelfNick(final MucOptions.User self, final boolean modified) {
3685        final Conversation conversation = self.getConversation();
3686        final Account account = conversation.getAccount();
3687        final Jid full = self.getFullJid();
3688        if (!full.equals(conversation.getJid())) {
3689            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persisting full jid " + full);
3690            conversation.setContactJid(full);
3691            databaseBackend.updateConversation(conversation);
3692        }
3693
3694        final Bookmark bookmark = conversation.getBookmark();
3695        if (bookmark == null || !modified) {
3696            return;
3697        }
3698        final var nick = full.getResource();
3699        final String defaultNick = MucOptions.defaultNick(account);
3700        if (nick.equals(defaultNick) || nick.equals(bookmark.getNick())) {
3701            return;
3702        }
3703        Log.d(
3704                Config.LOGTAG,
3705                account.getJid().asBareJid()
3706                        + ": persist nick '"
3707                        + full.getResource()
3708                        + "' into bookmark for "
3709                        + conversation.getJid().asBareJid());
3710        bookmark.setNick(nick);
3711        createBookmark(bookmark.getAccount(), bookmark);
3712    }
3713
3714    public boolean renameInMuc(
3715            final Conversation conversation,
3716            final String nick,
3717            final UiCallback<Conversation> callback) {
3718        final Account account = conversation.getAccount();
3719        final Bookmark bookmark = conversation.getBookmark();
3720        final MucOptions options = conversation.getMucOptions();
3721        final Jid joinJid = options.createJoinJid(nick);
3722        if (joinJid == null) {
3723            return false;
3724        }
3725        if (options.online()) {
3726            options.setOnRenameListener(
3727                    new OnRenameListener() {
3728
3729                        @Override
3730                        public void onSuccess() {
3731                            callback.success(conversation);
3732                        }
3733
3734                        @Override
3735                        public void onFailure() {
3736                            callback.error(R.string.nick_in_use, conversation);
3737                        }
3738                    });
3739
3740            final var packet =
3741                    mPresenceGenerator.selfPresence(
3742                            account,
3743                            im.conversations.android.xmpp.model.stanza.Presence.Availability.ONLINE,
3744                            options.nonanonymous());
3745            packet.setTo(joinJid);
3746            sendPresencePacket(account, packet);
3747            if (nick.equals(MucOptions.defaultNick(account))
3748                    && bookmark != null
3749                    && bookmark.getNick() != null) {
3750                Log.d(
3751                        Config.LOGTAG,
3752                        account.getJid().asBareJid()
3753                                + ": removing nick from bookmark for "
3754                                + bookmark.getJid());
3755                bookmark.setNick(null);
3756                createBookmark(account, bookmark);
3757            }
3758        } else {
3759            conversation.setContactJid(joinJid);
3760            databaseBackend.updateConversation(conversation);
3761            if (account.getStatus() == Account.State.ONLINE) {
3762                if (bookmark != null) {
3763                    bookmark.setNick(nick);
3764                    createBookmark(account, bookmark);
3765                }
3766                joinMuc(conversation);
3767            }
3768        }
3769        return true;
3770    }
3771
3772    public void checkMucRequiresRename() {
3773        synchronized (this.conversations) {
3774            for (final Conversation conversation : this.conversations) {
3775                if (conversation.getMode() == Conversational.MODE_MULTI) {
3776                    checkMucRequiresRename(conversation);
3777                }
3778            }
3779        }
3780    }
3781
3782    private void checkMucRequiresRename(final Conversation conversation) {
3783        final var options = conversation.getMucOptions();
3784        if (!options.online()) {
3785            return;
3786        }
3787        final var account = conversation.getAccount();
3788        final String current = options.getActualNick();
3789        final String proposed = options.getProposedNickPure();
3790        if (current == null || current.equals(proposed)) {
3791            return;
3792        }
3793        final Jid joinJid = options.createJoinJid(proposed);
3794        Log.d(
3795                Config.LOGTAG,
3796                String.format(
3797                        "%s: muc rename required %s (was: %s)",
3798                        account.getJid().asBareJid(), joinJid, current));
3799        final var packet =
3800                mPresenceGenerator.selfPresence(
3801                        account,
3802                        im.conversations.android.xmpp.model.stanza.Presence.Availability.ONLINE,
3803                        options.nonanonymous());
3804        packet.setTo(joinJid);
3805        sendPresencePacket(account, packet);
3806    }
3807
3808    public void leaveMuc(Conversation conversation) {
3809        leaveMuc(conversation, false);
3810    }
3811
3812    private void leaveMuc(Conversation conversation, boolean now) {
3813        final Account account = conversation.getAccount();
3814        synchronized (account.pendingConferenceJoins) {
3815            account.pendingConferenceJoins.remove(conversation);
3816        }
3817        synchronized (account.pendingConferenceLeaves) {
3818            account.pendingConferenceLeaves.remove(conversation);
3819        }
3820        if (account.getStatus() == Account.State.ONLINE || now) {
3821            sendPresencePacket(
3822                    conversation.getAccount(),
3823                    mPresenceGenerator.leave(conversation.getMucOptions()));
3824            conversation.getMucOptions().setOffline();
3825            Bookmark bookmark = conversation.getBookmark();
3826            if (bookmark != null) {
3827                bookmark.setConversation(null);
3828            }
3829            Log.d(
3830                    Config.LOGTAG,
3831                    conversation.getAccount().getJid().asBareJid()
3832                            + ": leaving muc "
3833                            + conversation.getJid());
3834            final var connection = account.getXmppConnection();
3835            if (connection != null) {
3836                connection.getManager(DiscoManager.class).clear(conversation.getJid().asBareJid());
3837            }
3838        } else {
3839            synchronized (account.pendingConferenceLeaves) {
3840                account.pendingConferenceLeaves.add(conversation);
3841            }
3842        }
3843    }
3844
3845    public String findConferenceServer(final Account account) {
3846        String server;
3847        if (account.getXmppConnection() != null) {
3848            server = account.getXmppConnection().getMucServer();
3849            if (server != null) {
3850                return server;
3851            }
3852        }
3853        for (Account other : getAccounts()) {
3854            if (other != account && other.getXmppConnection() != null) {
3855                server = other.getXmppConnection().getMucServer();
3856                if (server != null) {
3857                    return server;
3858                }
3859            }
3860        }
3861        return null;
3862    }
3863
3864    public void createPublicChannel(
3865            final Account account,
3866            final String name,
3867            final Jid address,
3868            final UiCallback<Conversation> callback) {
3869        joinMuc(
3870                findOrCreateConversation(account, address, true, false, true),
3871                conversation -> {
3872                    final Bundle configuration = IqGenerator.defaultChannelConfiguration();
3873                    if (!TextUtils.isEmpty(name)) {
3874                        configuration.putString("muc#roomconfig_roomname", name);
3875                    }
3876                    pushConferenceConfiguration(
3877                            conversation,
3878                            configuration,
3879                            new OnConfigurationPushed() {
3880                                @Override
3881                                public void onPushSucceeded() {
3882                                    saveConversationAsBookmark(conversation, name);
3883                                    callback.success(conversation);
3884                                }
3885
3886                                @Override
3887                                public void onPushFailed() {
3888                                    if (conversation
3889                                            .getMucOptions()
3890                                            .getSelf()
3891                                            .getAffiliation()
3892                                            .ranks(MucOptions.Affiliation.OWNER)) {
3893                                        callback.error(
3894                                                R.string.unable_to_set_channel_configuration,
3895                                                conversation);
3896                                    } else {
3897                                        callback.error(
3898                                                R.string.joined_an_existing_channel, conversation);
3899                                    }
3900                                }
3901                            });
3902                });
3903    }
3904
3905    public boolean createAdhocConference(
3906            final Account account,
3907            final String name,
3908            final Iterable<Jid> jids,
3909            final UiCallback<Conversation> callback) {
3910        Log.d(
3911                Config.LOGTAG,
3912                account.getJid().asBareJid().toString()
3913                        + ": creating adhoc conference with "
3914                        + jids.toString());
3915        if (account.getStatus() == Account.State.ONLINE) {
3916            try {
3917                String server = findConferenceServer(account);
3918                if (server == null) {
3919                    if (callback != null) {
3920                        callback.error(R.string.no_conference_server_found, null);
3921                    }
3922                    return false;
3923                }
3924                final Jid jid = Jid.of(CryptoHelper.pronounceable(), server, null);
3925                final Conversation conversation =
3926                        findOrCreateConversation(account, jid, true, false, true);
3927                joinMuc(
3928                        conversation,
3929                        new OnConferenceJoined() {
3930                            @Override
3931                            public void onConferenceJoined(final Conversation conversation) {
3932                                final Bundle configuration =
3933                                        IqGenerator.defaultGroupChatConfiguration();
3934                                if (!TextUtils.isEmpty(name)) {
3935                                    configuration.putString("muc#roomconfig_roomname", name);
3936                                }
3937                                pushConferenceConfiguration(
3938                                        conversation,
3939                                        configuration,
3940                                        new OnConfigurationPushed() {
3941                                            @Override
3942                                            public void onPushSucceeded() {
3943                                                for (Jid invite : jids) {
3944                                                    invite(conversation, invite);
3945                                                }
3946                                                for (String resource :
3947                                                        account.getSelfContact()
3948                                                                .getPresences()
3949                                                                .toResourceArray()) {
3950                                                    Jid other =
3951                                                            account.getJid().withResource(resource);
3952                                                    Log.d(
3953                                                            Config.LOGTAG,
3954                                                            account.getJid().asBareJid()
3955                                                                    + ": sending direct invite to "
3956                                                                    + other);
3957                                                    directInvite(conversation, other);
3958                                                }
3959                                                saveConversationAsBookmark(conversation, name);
3960                                                if (callback != null) {
3961                                                    callback.success(conversation);
3962                                                }
3963                                            }
3964
3965                                            @Override
3966                                            public void onPushFailed() {
3967                                                archiveConversation(conversation);
3968                                                if (callback != null) {
3969                                                    callback.error(
3970                                                            R.string.conference_creation_failed,
3971                                                            conversation);
3972                                                }
3973                                            }
3974                                        });
3975                            }
3976                        });
3977                return true;
3978            } catch (IllegalArgumentException e) {
3979                if (callback != null) {
3980                    callback.error(R.string.conference_creation_failed, null);
3981                }
3982                return false;
3983            }
3984        } else {
3985            if (callback != null) {
3986                callback.error(R.string.not_connected_try_again, null);
3987            }
3988            return false;
3989        }
3990    }
3991
3992    public void fetchConferenceConfiguration(final Conversation conversation) {
3993        fetchConferenceConfiguration(conversation, null);
3994    }
3995
3996    public void fetchConferenceConfiguration(
3997            final Conversation conversation, final OnConferenceConfigurationFetched callback) {
3998        final var account = conversation.getAccount();
3999        final var connection = account.getXmppConnection();
4000        if (connection == null) {
4001            return;
4002        }
4003        final var future =
4004                connection
4005                        .getManager(DiscoManager.class)
4006                        .info(Entity.discoItem(conversation.getJid().asBareJid()), null);
4007        Futures.addCallback(
4008                future,
4009                new FutureCallback<>() {
4010                    @Override
4011                    public void onSuccess(InfoQuery result) {
4012                        final MucOptions mucOptions = conversation.getMucOptions();
4013                        final Bookmark bookmark = conversation.getBookmark();
4014                        final boolean sameBefore =
4015                                StringUtils.equals(
4016                                        bookmark == null ? null : bookmark.getBookmarkName(),
4017                                        mucOptions.getName());
4018
4019                        final var hadOccupantId = mucOptions.occupantId();
4020                        if (mucOptions.updateConfiguration(result)) {
4021                            Log.d(
4022                                    Config.LOGTAG,
4023                                    account.getJid().asBareJid()
4024                                            + ": muc configuration changed for "
4025                                            + conversation.getJid().asBareJid());
4026                            updateConversation(conversation);
4027                        }
4028
4029                        final var hasOccupantId = mucOptions.occupantId();
4030
4031                        if (!hadOccupantId && hasOccupantId && mucOptions.online()) {
4032                            final var me = mucOptions.getSelf().getFullJid();
4033                            Log.d(
4034                                    Config.LOGTAG,
4035                                    account.getJid().asBareJid()
4036                                            + ": gained support for occupant-id in "
4037                                            + me
4038                                            + ". resending presence");
4039                            final var packet =
4040                                    mPresenceGenerator.selfPresence(
4041                                            account,
4042                                            im.conversations.android.xmpp.model.stanza.Presence
4043                                                    .Availability.ONLINE,
4044                                            mucOptions.nonanonymous());
4045                            packet.setTo(me);
4046                            sendPresencePacket(account, packet);
4047                        }
4048
4049                        if (bookmark != null
4050                                && (sameBefore || bookmark.getBookmarkName() == null)) {
4051                            if (bookmark.setBookmarkName(
4052                                    StringUtils.nullOnEmpty(mucOptions.getName()))) {
4053                                createBookmark(account, bookmark);
4054                            }
4055                        }
4056
4057                        if (callback != null) {
4058                            callback.onConferenceConfigurationFetched(conversation);
4059                        }
4060
4061                        updateConversationUi();
4062                    }
4063
4064                    @Override
4065                    public void onFailure(@NonNull Throwable throwable) {
4066                        if (throwable instanceof TimeoutException) {
4067                            Log.d(
4068                                    Config.LOGTAG,
4069                                    account.getJid().asBareJid()
4070                                            + ": received timeout waiting for conference"
4071                                            + " configuration fetch");
4072                        } else if (throwable instanceof IqErrorException errorResponseException) {
4073                            if (callback != null) {
4074                                callback.onFetchFailed(
4075                                        conversation,
4076                                        errorResponseException.getResponse().getErrorCondition());
4077                            }
4078                        }
4079                    }
4080                },
4081                MoreExecutors.directExecutor());
4082    }
4083
4084    public void pushNodeConfiguration(
4085            Account account,
4086            final String node,
4087            final Bundle options,
4088            final OnConfigurationPushed callback) {
4089        pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
4090    }
4091
4092    public void pushNodeConfiguration(
4093            Account account,
4094            final Jid jid,
4095            final String node,
4096            final Bundle options,
4097            final OnConfigurationPushed callback) {
4098        Log.d(Config.LOGTAG, "pushing node configuration");
4099        sendIqPacket(
4100                account,
4101                mIqGenerator.requestPubsubConfiguration(jid, node),
4102                responseToRequest -> {
4103                    if (responseToRequest.getType() == Iq.Type.RESULT) {
4104                        Element pubsub =
4105                                responseToRequest.findChild(
4106                                        "pubsub", "http://jabber.org/protocol/pubsub#owner");
4107                        Element configuration =
4108                                pubsub == null ? null : pubsub.findChild("configure");
4109                        Element x =
4110                                configuration == null
4111                                        ? null
4112                                        : configuration.findChild("x", Namespace.DATA);
4113                        if (x != null) {
4114                            final Data data = Data.parse(x);
4115                            data.submit(options);
4116                            sendIqPacket(
4117                                    account,
4118                                    mIqGenerator.publishPubsubConfiguration(jid, node, data),
4119                                    responseToPublish -> {
4120                                        if (responseToPublish.getType() == Iq.Type.RESULT
4121                                                && callback != null) {
4122                                            Log.d(
4123                                                    Config.LOGTAG,
4124                                                    account.getJid().asBareJid()
4125                                                            + ": successfully changed node"
4126                                                            + " configuration for node "
4127                                                            + node);
4128                                            callback.onPushSucceeded();
4129                                        } else if (responseToPublish.getType() == Iq.Type.ERROR
4130                                                && callback != null) {
4131                                            callback.onPushFailed();
4132                                        }
4133                                    });
4134                        } else if (callback != null) {
4135                            callback.onPushFailed();
4136                        }
4137                    } else if (responseToRequest.getType() == Iq.Type.ERROR && callback != null) {
4138                        callback.onPushFailed();
4139                    }
4140                });
4141    }
4142
4143    public void pushConferenceConfiguration(
4144            final Conversation conversation,
4145            final Bundle options,
4146            final OnConfigurationPushed callback) {
4147        if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
4148            conversation.setAttribute("accept_non_anonymous", true);
4149            updateConversation(conversation);
4150        }
4151        if (options.containsKey("muc#roomconfig_moderatedroom")) {
4152            final boolean moderated = "1".equals(options.getString("muc#roomconfig_moderatedroom"));
4153            options.putString("members_by_default", moderated ? "0" : "1");
4154        }
4155        if (options.containsKey("muc#roomconfig_allowpm")) {
4156            // ejabberd :-/
4157            final boolean allow = "anyone".equals(options.getString("muc#roomconfig_allowpm"));
4158            options.putString("allow_private_messages", allow ? "1" : "0");
4159            options.putString("allow_private_messages_from_visitors", allow ? "anyone" : "nobody");
4160        }
4161        final var account = conversation.getAccount();
4162        final Iq request = new Iq(Iq.Type.GET);
4163        request.setTo(conversation.getJid().asBareJid());
4164        request.query("http://jabber.org/protocol/muc#owner");
4165        sendIqPacket(
4166                account,
4167                request,
4168                response -> {
4169                    if (response.getType() == Iq.Type.RESULT) {
4170                        final Data data =
4171                                Data.parse(response.query().findChild("x", Namespace.DATA));
4172                        data.submit(options);
4173                        final Iq set = new Iq(Iq.Type.SET);
4174                        set.setTo(conversation.getJid().asBareJid());
4175                        set.query("http://jabber.org/protocol/muc#owner").addChild(data);
4176                        sendIqPacket(
4177                                account,
4178                                set,
4179                                packet -> {
4180                                    if (callback != null) {
4181                                        if (packet.getType() == Iq.Type.RESULT) {
4182                                            callback.onPushSucceeded();
4183                                        } else {
4184                                            Log.d(Config.LOGTAG, "failed: " + packet);
4185                                            callback.onPushFailed();
4186                                        }
4187                                    }
4188                                });
4189                    } else {
4190                        if (callback != null) {
4191                            callback.onPushFailed();
4192                        }
4193                    }
4194                });
4195    }
4196
4197    public void pushSubjectToConference(final Conversation conference, final String subject) {
4198        final var packet =
4199                this.getMessageGenerator()
4200                        .conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
4201        this.sendMessagePacket(conference.getAccount(), packet);
4202    }
4203
4204    public void changeAffiliationInConference(
4205            final Conversation conference,
4206            Jid user,
4207            final MucOptions.Affiliation affiliation,
4208            final OnAffiliationChanged callback) {
4209        final Jid jid = user.asBareJid();
4210        final Iq request =
4211                this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
4212        sendIqPacket(
4213                conference.getAccount(),
4214                request,
4215                (response) -> {
4216                    if (response.getType() == Iq.Type.RESULT) {
4217                        final var mucOptions = conference.getMucOptions();
4218                        mucOptions.changeAffiliation(jid, affiliation);
4219                        getAvatarService().clear(mucOptions);
4220                        if (callback != null) {
4221                            callback.onAffiliationChangedSuccessful(jid);
4222                        } else {
4223                            Log.d(
4224                                    Config.LOGTAG,
4225                                    "changed affiliation of " + user + " to " + affiliation);
4226                        }
4227                    } else if (callback != null) {
4228                        callback.onAffiliationChangeFailed(
4229                                jid, R.string.could_not_change_affiliation);
4230                    } else {
4231                        Log.d(Config.LOGTAG, "unable to change affiliation");
4232                    }
4233                });
4234    }
4235
4236    public void changeRoleInConference(
4237            final Conversation conference, final String nick, MucOptions.Role role) {
4238        final var account = conference.getAccount();
4239        final Iq request = this.mIqGenerator.changeRole(conference, nick, role.toString());
4240        sendIqPacket(
4241                account,
4242                request,
4243                (packet) -> {
4244                    if (packet.getType() != Iq.Type.RESULT) {
4245                        Log.d(
4246                                Config.LOGTAG,
4247                                account.getJid().asBareJid() + " unable to change role of " + nick);
4248                    }
4249                });
4250    }
4251
4252    public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
4253        final Iq request = new Iq(Iq.Type.SET);
4254        request.setTo(conversation.getJid().asBareJid());
4255        request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
4256        sendIqPacket(
4257                conversation.getAccount(),
4258                request,
4259                response -> {
4260                    if (response.getType() == Iq.Type.RESULT) {
4261                        if (callback != null) {
4262                            callback.onRoomDestroySucceeded();
4263                        }
4264                    } else if (response.getType() == Iq.Type.ERROR) {
4265                        if (callback != null) {
4266                            callback.onRoomDestroyFailed();
4267                        }
4268                    }
4269                });
4270    }
4271
4272    private void disconnect(final Account account, boolean force) {
4273        final XmppConnection connection = account.getXmppConnection();
4274        if (connection == null) {
4275            return;
4276        }
4277        if (!force) {
4278            final List<Conversation> conversations = getConversations();
4279            for (Conversation conversation : conversations) {
4280                if (conversation.getAccount() == account) {
4281                    if (conversation.getMode() == Conversation.MODE_MULTI) {
4282                        leaveMuc(conversation, true);
4283                    }
4284                }
4285            }
4286            sendOfflinePresence(account);
4287        }
4288        connection.disconnect(force);
4289    }
4290
4291    @Override
4292    public IBinder onBind(Intent intent) {
4293        return mBinder;
4294    }
4295
4296    public void updateMessage(Message message) {
4297        updateMessage(message, true);
4298    }
4299
4300    public void updateMessage(Message message, boolean includeBody) {
4301        databaseBackend.updateMessage(message, includeBody);
4302        updateConversationUi();
4303    }
4304
4305    public void createMessageAsync(final Message message) {
4306        mDatabaseWriterExecutor.execute(() -> databaseBackend.createMessage(message));
4307    }
4308
4309    public void updateMessage(Message message, String uuid) {
4310        if (!databaseBackend.updateMessage(message, uuid)) {
4311            Log.e(Config.LOGTAG, "error updated message in DB after edit");
4312        }
4313        updateConversationUi();
4314    }
4315
4316    public void createContact(final Contact contact) {
4317        createContact(contact, null);
4318    }
4319
4320    public void createContact(final Contact contact, final String preAuth) {
4321        contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
4322        contact.setOption(Contact.Options.ASKING);
4323        final var connection = contact.getAccount().getXmppConnection();
4324        connection.getManager(RosterManager.class).addRosterItem(contact, preAuth);
4325    }
4326
4327    public void deleteContactOnServer(final Contact contact) {
4328        final var connection = contact.getAccount().getXmppConnection();
4329        connection.getManager(RosterManager.class).deleteRosterItem(contact);
4330    }
4331
4332    public void publishMucAvatar(
4333            final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
4334        new Thread(
4335                        () -> {
4336                            final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
4337                            final int size = Config.AVATAR_SIZE;
4338                            final Avatar avatar =
4339                                    getFileBackend().getPepAvatar(image, size, format);
4340                            if (avatar != null) {
4341                                if (!getFileBackend().save(avatar)) {
4342                                    callback.onAvatarPublicationFailed(
4343                                            R.string.error_saving_avatar);
4344                                    return;
4345                                }
4346                                avatar.owner = conversation.getJid().asBareJid();
4347                                publishMucAvatar(conversation, avatar, callback);
4348                            } else {
4349                                callback.onAvatarPublicationFailed(
4350                                        R.string.error_publish_avatar_converting);
4351                            }
4352                        })
4353                .start();
4354    }
4355
4356    public void publishAvatarAsync(
4357            final Account account,
4358            final Uri image,
4359            final boolean open,
4360            final OnAvatarPublication callback) {
4361        new Thread(() -> publishAvatar(account, image, open, callback)).start();
4362    }
4363
4364    private void publishAvatar(
4365            final Account account,
4366            final Uri image,
4367            final boolean open,
4368            final OnAvatarPublication callback) {
4369        final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
4370        final int size = Config.AVATAR_SIZE;
4371        final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
4372        if (avatar == null) {
4373            callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
4374            return;
4375        }
4376        if (fileBackend.save(avatar)) {
4377            final var connection = account.getXmppConnection();
4378            final var future = connection.getManager(AvatarManager.class).publish(avatar, open);
4379            Futures.addCallback(
4380                    future,
4381                    new FutureCallback<Void>() {
4382                        @Override
4383                        public void onSuccess(Void result) {
4384                            callback.onAvatarPublicationSucceeded();
4385                        }
4386
4387                        @Override
4388                        public void onFailure(@NonNull Throwable t) {
4389                            Log.d(
4390                                    Config.LOGTAG,
4391                                    account.getJid().asBareJid() + ": could not publish avatar",
4392                                    t);
4393                            callback.onAvatarPublicationFailed(
4394                                    R.string.error_publish_avatar_server_reject);
4395                        }
4396                    },
4397                    MoreExecutors.directExecutor());
4398
4399        } else {
4400            Log.d(Config.LOGTAG, "could not save avatar");
4401            callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
4402        }
4403    }
4404
4405    private void publishMucAvatar(
4406            Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
4407        final var account = conversation.getAccount();
4408        final Iq retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
4409        sendIqPacket(
4410                account,
4411                retrieve,
4412                (response) -> {
4413                    boolean itemNotFound =
4414                            response.getType() == Iq.Type.ERROR
4415                                    && response.hasChild("error")
4416                                    && response.findChild("error").hasChild("item-not-found");
4417                    if (response.getType() == Iq.Type.RESULT || itemNotFound) {
4418                        Element vcard = response.findChild("vCard", "vcard-temp");
4419                        if (vcard == null) {
4420                            vcard = new Element("vCard", "vcard-temp");
4421                        }
4422                        Element photo = vcard.findChild("PHOTO");
4423                        if (photo == null) {
4424                            photo = vcard.addChild("PHOTO");
4425                        }
4426                        photo.clearChildren();
4427                        photo.addChild("TYPE").setContent(avatar.type);
4428                        photo.addChild("BINVAL").setContent(avatar.image);
4429                        final Iq publication = new Iq(Iq.Type.SET);
4430                        publication.setTo(conversation.getJid().asBareJid());
4431                        publication.addChild(vcard);
4432                        sendIqPacket(
4433                                account,
4434                                publication,
4435                                (publicationResponse) -> {
4436                                    if (publicationResponse.getType() == Iq.Type.RESULT) {
4437                                        callback.onAvatarPublicationSucceeded();
4438                                    } else {
4439                                        Log.d(
4440                                                Config.LOGTAG,
4441                                                "failed to publish vcard "
4442                                                        + publicationResponse.getErrorCondition());
4443                                        callback.onAvatarPublicationFailed(
4444                                                R.string.error_publish_avatar_server_reject);
4445                                    }
4446                                });
4447                    } else {
4448                        Log.d(Config.LOGTAG, "failed to request vcard " + response);
4449                        callback.onAvatarPublicationFailed(
4450                                R.string.error_publish_avatar_no_server_support);
4451                    }
4452                });
4453    }
4454
4455    public void cancelAvatarFetches(final Account account) {
4456        synchronized (mInProgressAvatarFetches) {
4457            for (final Iterator<String> iterator = mInProgressAvatarFetches.iterator();
4458                    iterator.hasNext(); ) {
4459                final String KEY = iterator.next();
4460                if (KEY.startsWith(account.getJid().asBareJid() + "_")) {
4461                    iterator.remove();
4462                }
4463            }
4464        }
4465    }
4466
4467    public void fetchAvatar(Account account, final Avatar avatar) {
4468        final String KEY = generateFetchKey(account, avatar);
4469        synchronized (this.mInProgressAvatarFetches) {
4470            if (mInProgressAvatarFetches.add(KEY)) {
4471                switch (avatar.origin) {
4472                    case PEP:
4473                        this.mInProgressAvatarFetches.add(KEY);
4474                        fetchAvatarPep(account, avatar, null);
4475                        break;
4476                    case VCARD:
4477                        this.mInProgressAvatarFetches.add(KEY);
4478                        fetchAvatarVcard(account, avatar);
4479                        break;
4480                }
4481            } else if (avatar.origin == Avatar.Origin.PEP) {
4482                mOmittedPepAvatarFetches.add(KEY);
4483            } else {
4484                Log.d(
4485                        Config.LOGTAG,
4486                        account.getJid().asBareJid()
4487                                + ": already fetching "
4488                                + avatar.origin
4489                                + " avatar for "
4490                                + avatar.owner);
4491            }
4492        }
4493    }
4494
4495    private void fetchAvatarPep(
4496            final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4497        final Iq packet = this.mIqGenerator.retrievePepAvatar(avatar);
4498        sendIqPacket(
4499                account,
4500                packet,
4501                (result) -> {
4502                    synchronized (mInProgressAvatarFetches) {
4503                        mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
4504                    }
4505                    final String ERROR =
4506                            account.getJid().asBareJid()
4507                                    + ": fetching avatar for "
4508                                    + avatar.owner
4509                                    + " failed ";
4510                    if (result.getType() == Iq.Type.RESULT) {
4511                        avatar.image = IqParser.avatarData(result);
4512                        if (avatar.image != null) {
4513                            if (getFileBackend().save(avatar)) {
4514                                if (account.getJid().asBareJid().equals(avatar.owner)) {
4515                                    if (account.setAvatar(avatar.getFilename())) {
4516                                        databaseBackend.updateAccount(account);
4517                                    }
4518                                    getAvatarService().clear(account);
4519                                    updateConversationUi();
4520                                    updateAccountUi();
4521                                } else {
4522                                    final Contact contact =
4523                                            account.getRoster().getContact(avatar.owner);
4524                                    contact.setAvatar(avatar);
4525                                    account.getXmppConnection()
4526                                            .getManager(RosterManager.class)
4527                                            .writeToDatabaseAsync();
4528                                    getAvatarService().clear(contact);
4529                                    updateConversationUi();
4530                                    updateRosterUi();
4531                                }
4532                                if (callback != null) {
4533                                    callback.success(avatar);
4534                                }
4535                                Log.d(
4536                                        Config.LOGTAG,
4537                                        account.getJid().asBareJid()
4538                                                + ": successfully fetched pep avatar for "
4539                                                + avatar.owner);
4540                                return;
4541                            }
4542                        } else {
4543
4544                            Log.d(Config.LOGTAG, ERROR + "(parsing error)");
4545                        }
4546                    } else {
4547                        Element error = result.findChild("error");
4548                        if (error == null) {
4549                            Log.d(Config.LOGTAG, ERROR + "(server error)");
4550                        } else {
4551                            Log.d(Config.LOGTAG, ERROR + error);
4552                        }
4553                    }
4554                    if (callback != null) {
4555                        callback.error(0, null);
4556                    }
4557                });
4558    }
4559
4560    private void fetchAvatarVcard(final Account account, final Avatar avatar) {
4561        final var address = avatar.owner;
4562        final var connection = account.getXmppConnection();
4563        final var future = connection.getManager(VCardManager.class).retrievePhoto(address);
4564        Futures.addCallback(
4565                future,
4566                new FutureCallback<>() {
4567                    @Override
4568                    public void onSuccess(byte[] result) {
4569                        avatar.image = BaseEncoding.base64().encode(result);
4570                        if (fileBackend.save(avatar)) {
4571                            setVCardAvatar(account, avatar);
4572                        }
4573                    }
4574
4575                    @Override
4576                    public void onFailure(@NonNull Throwable t) {
4577                        Log.d(
4578                                Config.LOGTAG,
4579                                "could not retrieve avatar from "
4580                                        + address
4581                                        + " ("
4582                                        + avatar.sha1sum
4583                                        + ")",
4584                                t);
4585                    }
4586                },
4587                MoreExecutors.directExecutor());
4588    }
4589
4590    private void setVCardAvatar(final Account account, final Avatar avatar) {
4591        Log.d(
4592                Config.LOGTAG,
4593                account.getJid().asBareJid()
4594                        + ": successfully fetched vCard avatar for "
4595                        + avatar.owner);
4596        if (avatar.owner.isBareJid()) {
4597            if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
4598                Log.d(
4599                        Config.LOGTAG,
4600                        account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
4601                account.setAvatar(avatar.getFilename());
4602                databaseBackend.updateAccount(account);
4603                getAvatarService().clear(account);
4604                updateAccountUi();
4605            } else {
4606                final Contact contact = account.getRoster().getContact(avatar.owner);
4607                contact.setAvatar(avatar);
4608                account.getXmppConnection().getManager(RosterManager.class).writeToDatabaseAsync();
4609                getAvatarService().clear(contact);
4610                updateRosterUi();
4611            }
4612            updateConversationUi();
4613        } else {
4614            Conversation conversation = find(account, avatar.owner.asBareJid());
4615            if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
4616                MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
4617                if (user != null) {
4618                    if (user.setAvatar(avatar)) {
4619                        getAvatarService().clear(user);
4620                        updateConversationUi();
4621                        updateMucRosterUi();
4622                    }
4623                    if (user.getRealJid() != null) {
4624                        Contact contact = account.getRoster().getContact(user.getRealJid());
4625                        contact.setAvatar(avatar);
4626                        account.getXmppConnection()
4627                                .getManager(RosterManager.class)
4628                                .writeToDatabaseAsync();
4629                        getAvatarService().clear(contact);
4630                        updateRosterUi();
4631                    }
4632                }
4633            }
4634        }
4635    }
4636
4637    public void checkForAvatar(final Account account, final UiCallback<Avatar> callback) {
4638        final Iq packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4639        this.sendIqPacket(
4640                account,
4641                packet,
4642                response -> {
4643                    if (response.getType() != Iq.Type.RESULT) {
4644                        callback.error(0, null);
4645                    }
4646                    final var pubsub = packet.getExtension(PubSub.class);
4647                    if (pubsub == null) {
4648                        callback.error(0, null);
4649                        return;
4650                    }
4651                    final var items = pubsub.getItems();
4652                    if (items == null) {
4653                        callback.error(0, null);
4654                        return;
4655                    }
4656                    final var item = items.getFirstItemWithId(Metadata.class);
4657                    if (item == null) {
4658                        callback.error(0, null);
4659                        return;
4660                    }
4661                    final var avatar = Avatar.parseMetadata(item.getKey(), item.getValue());
4662                    if (avatar == null) {
4663                        callback.error(0, null);
4664                        return;
4665                    }
4666                    avatar.owner = account.getJid().asBareJid();
4667                    if (fileBackend.isAvatarCached(avatar)) {
4668                        if (account.setAvatar(avatar.getFilename())) {
4669                            databaseBackend.updateAccount(account);
4670                        }
4671                        getAvatarService().clear(account);
4672                        callback.success(avatar);
4673                    } else {
4674                        fetchAvatarPep(account, avatar, callback);
4675                    }
4676                });
4677    }
4678
4679    public void notifyAccountAvatarHasChanged(final Account account) {
4680        final XmppConnection connection = account.getXmppConnection();
4681        // this was bookmark conversion for a bit which doesn't make sense
4682        if (connection.getManager(AvatarManager.class).hasPepToVCardConversion()) {
4683            Log.d(
4684                    Config.LOGTAG,
4685                    account.getJid().asBareJid()
4686                            + ": avatar changed. resending presence to online group chats");
4687            for (Conversation conversation : conversations) {
4688                if (conversation.getAccount() == account
4689                        && conversation.getMode() == Conversational.MODE_MULTI) {
4690                    final MucOptions mucOptions = conversation.getMucOptions();
4691                    if (mucOptions.online()) {
4692                        final var packet =
4693                                mPresenceGenerator.selfPresence(
4694                                        account,
4695                                        im.conversations.android.xmpp.model.stanza.Presence
4696                                                .Availability.ONLINE,
4697                                        mucOptions.nonanonymous());
4698                        packet.setTo(mucOptions.getSelf().getFullJid());
4699                        connection.sendPresencePacket(packet);
4700                    }
4701                }
4702            }
4703        }
4704    }
4705
4706    public void updateConversation(final Conversation conversation) {
4707        mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
4708    }
4709
4710    public void reconnectAccount(
4711            final Account account, final boolean force, final boolean interactive) {
4712        synchronized (account) {
4713            final XmppConnection connection = account.getXmppConnection();
4714            final boolean hasInternet = hasInternetConnection();
4715            if (account.isConnectionEnabled() && hasInternet) {
4716                if (!force) {
4717                    disconnect(account, false);
4718                }
4719                Thread thread = new Thread(connection);
4720                connection.setInteractive(interactive);
4721                connection.prepareNewConnection();
4722                connection.interrupt();
4723                thread.start();
4724                scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
4725            } else {
4726                disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
4727                connection.getManager(RosterManager.class).clearPresences();
4728                connection.resetEverything();
4729                final AxolotlService axolotlService = account.getAxolotlService();
4730                if (axolotlService != null) {
4731                    axolotlService.resetBrokenness();
4732                }
4733                if (!hasInternet) {
4734                    // TODO should this go via XmppConnection.setStatusAndTriggerProcessor()?
4735                    account.setStatus(Account.State.NO_INTERNET);
4736                }
4737            }
4738        }
4739    }
4740
4741    public void reconnectAccountInBackground(final Account account) {
4742        new Thread(() -> reconnectAccount(account, false, true)).start();
4743    }
4744
4745    public void invite(final Conversation conversation, final Jid contact) {
4746        Log.d(
4747                Config.LOGTAG,
4748                conversation.getAccount().getJid().asBareJid()
4749                        + ": inviting "
4750                        + contact
4751                        + " to "
4752                        + conversation.getJid().asBareJid());
4753        final MucOptions.User user =
4754                conversation.getMucOptions().findUserByRealJid(contact.asBareJid());
4755        if (user == null || user.getAffiliation() == MucOptions.Affiliation.OUTCAST) {
4756            changeAffiliationInConference(conversation, contact, MucOptions.Affiliation.NONE, null);
4757        }
4758        final var packet = mMessageGenerator.invite(conversation, contact);
4759        sendMessagePacket(conversation.getAccount(), packet);
4760    }
4761
4762    public void directInvite(Conversation conversation, Jid jid) {
4763        final var packet = mMessageGenerator.directInvite(conversation, jid);
4764        sendMessagePacket(conversation.getAccount(), packet);
4765    }
4766
4767    public void resetSendingToWaiting(Account account) {
4768        for (Conversation conversation : getConversations()) {
4769            if (conversation.getAccount() == account) {
4770                conversation.findUnsentTextMessages(
4771                        message -> markMessage(message, Message.STATUS_WAITING));
4772            }
4773        }
4774    }
4775
4776    public Message markMessage(
4777            final Account account, final Jid recipient, final String uuid, final int status) {
4778        return markMessage(account, recipient, uuid, status, null);
4779    }
4780
4781    public Message markMessage(
4782            final Account account,
4783            final Jid recipient,
4784            final String uuid,
4785            final int status,
4786            String errorMessage) {
4787        if (uuid == null) {
4788            return null;
4789        }
4790        for (Conversation conversation : getConversations()) {
4791            if (conversation.getJid().asBareJid().equals(recipient)
4792                    && conversation.getAccount() == account) {
4793                final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
4794                if (message != null) {
4795                    markMessage(message, status, errorMessage);
4796                }
4797                return message;
4798            }
4799        }
4800        return null;
4801    }
4802
4803    public boolean markMessage(
4804            final Conversation conversation,
4805            final String uuid,
4806            final int status,
4807            final String serverMessageId) {
4808        return markMessage(conversation, uuid, status, serverMessageId, null);
4809    }
4810
4811    public boolean markMessage(
4812            final Conversation conversation,
4813            final String uuid,
4814            final int status,
4815            final String serverMessageId,
4816            final LocalizedContent body) {
4817        if (uuid == null) {
4818            return false;
4819        } else {
4820            final Message message = conversation.findSentMessageWithUuid(uuid);
4821            if (message != null) {
4822                if (message.getServerMsgId() == null) {
4823                    message.setServerMsgId(serverMessageId);
4824                }
4825                if (message.getEncryption() == Message.ENCRYPTION_NONE
4826                        && message.isTypeText()
4827                        && isBodyModified(message, body)) {
4828                    message.setBody(body.content);
4829                    if (body.count > 1) {
4830                        message.setBodyLanguage(body.language);
4831                    }
4832                    markMessage(message, status, null, true);
4833                } else {
4834                    markMessage(message, status);
4835                }
4836                return true;
4837            } else {
4838                return false;
4839            }
4840        }
4841    }
4842
4843    private static boolean isBodyModified(final Message message, final LocalizedContent body) {
4844        if (body == null || body.content == null) {
4845            return false;
4846        }
4847        return !body.content.equals(message.getBody());
4848    }
4849
4850    public void markMessage(Message message, int status) {
4851        markMessage(message, status, null);
4852    }
4853
4854    public void markMessage(final Message message, final int status, final String errorMessage) {
4855        markMessage(message, status, errorMessage, false);
4856    }
4857
4858    public void markMessage(
4859            final Message message,
4860            final int status,
4861            final String errorMessage,
4862            final boolean includeBody) {
4863        final int oldStatus = message.getStatus();
4864        if (status == Message.STATUS_SEND_FAILED
4865                && (oldStatus == Message.STATUS_SEND_RECEIVED
4866                        || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
4867            return;
4868        }
4869        if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
4870            return;
4871        }
4872        message.setErrorMessage(errorMessage);
4873        message.setStatus(status);
4874        databaseBackend.updateMessage(message, includeBody);
4875        updateConversationUi();
4876        if (oldStatus != status && status == Message.STATUS_SEND_FAILED) {
4877            mNotificationService.pushFailedDelivery(message);
4878        }
4879    }
4880
4881    private SharedPreferences getPreferences() {
4882        return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
4883    }
4884
4885    public long getAutomaticMessageDeletionDate() {
4886        final long timeout =
4887                getLongPreference(
4888                        AppSettings.AUTOMATIC_MESSAGE_DELETION,
4889                        R.integer.automatic_message_deletion);
4890        return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
4891    }
4892
4893    public long getLongPreference(String name, @IntegerRes int res) {
4894        long defaultValue = getResources().getInteger(res);
4895        try {
4896            return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
4897        } catch (NumberFormatException e) {
4898            return defaultValue;
4899        }
4900    }
4901
4902    public boolean getBooleanPreference(String name, @BoolRes int res) {
4903        return getPreferences().getBoolean(name, getResources().getBoolean(res));
4904    }
4905
4906    public boolean confirmMessages() {
4907        return appSettings.isConfirmMessages();
4908    }
4909
4910    public boolean allowMessageCorrection() {
4911        return appSettings.isAllowMessageCorrection();
4912    }
4913
4914    public boolean sendChatStates() {
4915        return getBooleanPreference("chat_states", R.bool.chat_states);
4916    }
4917
4918    public boolean useTorToConnect() {
4919        return appSettings.isUseTor();
4920    }
4921
4922    public boolean broadcastLastActivity() {
4923        return appSettings.isBroadcastLastActivity();
4924    }
4925
4926    public int unreadCount() {
4927        int count = 0;
4928        for (Conversation conversation : getConversations()) {
4929            count += conversation.unreadCount();
4930        }
4931        return count;
4932    }
4933
4934    private <T> List<T> threadSafeList(Set<T> set) {
4935        synchronized (LISTENER_LOCK) {
4936            return set.isEmpty() ? Collections.emptyList() : new ArrayList<>(set);
4937        }
4938    }
4939
4940    public void showErrorToastInUi(int resId) {
4941        for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
4942            listener.onShowErrorToast(resId);
4943        }
4944    }
4945
4946    public void updateConversationUi() {
4947        for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
4948            listener.onConversationUpdate();
4949        }
4950    }
4951
4952    public void notifyJingleRtpConnectionUpdate(
4953            final Account account,
4954            final Jid with,
4955            final String sessionId,
4956            final RtpEndUserState state) {
4957        for (OnJingleRtpConnectionUpdate listener :
4958                threadSafeList(this.onJingleRtpConnectionUpdate)) {
4959            listener.onJingleRtpConnectionUpdate(account, with, sessionId, state);
4960        }
4961    }
4962
4963    public void notifyJingleRtpConnectionUpdate(
4964            CallIntegration.AudioDevice selectedAudioDevice,
4965            Set<CallIntegration.AudioDevice> availableAudioDevices) {
4966        for (OnJingleRtpConnectionUpdate listener :
4967                threadSafeList(this.onJingleRtpConnectionUpdate)) {
4968            listener.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
4969        }
4970    }
4971
4972    public void updateAccountUi() {
4973        for (final OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
4974            listener.onAccountUpdate();
4975        }
4976    }
4977
4978    public void updateRosterUi() {
4979        for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
4980            listener.onRosterUpdate();
4981        }
4982    }
4983
4984    public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
4985        if (mOnCaptchaRequested.size() > 0) {
4986            DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
4987            Bitmap scaled =
4988                    Bitmap.createScaledBitmap(
4989                            captcha,
4990                            (int) (captcha.getWidth() * metrics.scaledDensity),
4991                            (int) (captcha.getHeight() * metrics.scaledDensity),
4992                            false);
4993            for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
4994                listener.onCaptchaRequested(account, id, data, scaled);
4995            }
4996            return true;
4997        }
4998        return false;
4999    }
5000
5001    public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
5002        for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
5003            listener.OnUpdateBlocklist(status);
5004        }
5005    }
5006
5007    public void updateMucRosterUi() {
5008        for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
5009            listener.onMucRosterUpdate();
5010        }
5011    }
5012
5013    public void keyStatusUpdated(AxolotlService.FetchStatus report) {
5014        for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
5015            listener.onKeyStatusUpdated(report);
5016        }
5017    }
5018
5019    public Account findAccountByJid(final Jid jid) {
5020        for (final Account account : this.accounts) {
5021            if (account.getJid().asBareJid().equals(jid.asBareJid())) {
5022                return account;
5023            }
5024        }
5025        return null;
5026    }
5027
5028    public Account findAccountByUuid(final String uuid) {
5029        for (Account account : this.accounts) {
5030            if (account.getUuid().equals(uuid)) {
5031                return account;
5032            }
5033        }
5034        return null;
5035    }
5036
5037    public Conversation findConversationByUuid(String uuid) {
5038        for (Conversation conversation : getConversations()) {
5039            if (conversation.getUuid().equals(uuid)) {
5040                return conversation;
5041            }
5042        }
5043        return null;
5044    }
5045
5046    public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
5047        List<Conversation> findings = new ArrayList<>();
5048        for (Conversation c : getConversations()) {
5049            if (c.getAccount().isEnabled()
5050                    && c.getJid().asBareJid().equals(xmppUri.getJid())
5051                    && ((c.getMode() == Conversational.MODE_MULTI)
5052                            == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
5053                findings.add(c);
5054            }
5055        }
5056        return findings.size() == 1 ? findings.get(0) : null;
5057    }
5058
5059    public boolean markRead(final Conversation conversation, boolean dismiss) {
5060        return markRead(conversation, null, dismiss).size() > 0;
5061    }
5062
5063    public void markRead(final Conversation conversation) {
5064        markRead(conversation, null, true);
5065    }
5066
5067    public List<Message> markRead(
5068            final Conversation conversation, String upToUuid, boolean dismiss) {
5069        if (dismiss) {
5070            mNotificationService.clear(conversation);
5071        }
5072        final List<Message> readMessages = conversation.markRead(upToUuid);
5073        if (readMessages.size() > 0) {
5074            Runnable runnable =
5075                    () -> {
5076                        for (Message message : readMessages) {
5077                            databaseBackend.updateMessage(message, false);
5078                        }
5079                    };
5080            mDatabaseWriterExecutor.execute(runnable);
5081            updateConversationUi();
5082            updateUnreadCountBadge();
5083            return readMessages;
5084        } else {
5085            return readMessages;
5086        }
5087    }
5088
5089    public synchronized void updateUnreadCountBadge() {
5090        int count = unreadCount();
5091        if (unreadCount != count) {
5092            Log.d(Config.LOGTAG, "update unread count to " + count);
5093            if (count > 0) {
5094                ShortcutBadger.applyCount(getApplicationContext(), count);
5095            } else {
5096                ShortcutBadger.removeCount(getApplicationContext());
5097            }
5098            unreadCount = count;
5099        }
5100    }
5101
5102    public void sendReadMarker(final Conversation conversation, final String upToUuid) {
5103        final boolean isPrivateAndNonAnonymousMuc =
5104                conversation.getMode() == Conversation.MODE_MULTI
5105                        && conversation.isPrivateAndNonAnonymous();
5106        final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
5107        if (readMessages.isEmpty()) {
5108            return;
5109        }
5110        final var account = conversation.getAccount();
5111        final var connection = account.getXmppConnection();
5112        updateConversationUi();
5113        final var last =
5114                Iterables.getLast(
5115                        Collections2.filter(
5116                                readMessages,
5117                                m ->
5118                                        !m.isPrivateMessage()
5119                                                && m.getStatus() == Message.STATUS_RECEIVED),
5120                        null);
5121        if (last == null) {
5122            return;
5123        }
5124
5125        final boolean sendDisplayedMarker =
5126                confirmMessages()
5127                        && (last.trusted() || isPrivateAndNonAnonymousMuc)
5128                        && last.getRemoteMsgId() != null
5129                        && (last.markable || isPrivateAndNonAnonymousMuc);
5130        final boolean serverAssist =
5131                connection != null && connection.getFeatures().mdsServerAssist();
5132
5133        final String stanzaId = last.getServerMsgId();
5134
5135        if (sendDisplayedMarker && serverAssist) {
5136            final var mdsDisplayed =
5137                    MessageDisplayedSynchronizationManager.displayed(stanzaId, conversation);
5138            final var packet = mMessageGenerator.confirm(last);
5139            packet.addChild(mdsDisplayed);
5140            if (!last.isPrivateMessage()) {
5141                packet.setTo(packet.getTo().asBareJid());
5142            }
5143            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server assisted " + packet);
5144            this.sendMessagePacket(account, packet);
5145        } else {
5146            publishMds(last);
5147            // read markers will be sent after MDS to flush the CSI stanza queue
5148            if (sendDisplayedMarker) {
5149                Log.d(
5150                        Config.LOGTAG,
5151                        conversation.getAccount().getJid().asBareJid()
5152                                + ": sending displayed marker to "
5153                                + last.getCounterpart().toString());
5154                final var packet = mMessageGenerator.confirm(last);
5155                this.sendMessagePacket(account, packet);
5156            }
5157        }
5158    }
5159
5160    private void publishMds(@Nullable final Message message) {
5161        final String stanzaId = message == null ? null : message.getServerMsgId();
5162        if (Strings.isNullOrEmpty(stanzaId)) {
5163            return;
5164        }
5165        final Conversation conversation;
5166        final var conversational = message.getConversation();
5167        if (conversational instanceof Conversation c) {
5168            conversation = c;
5169        } else {
5170            return;
5171        }
5172        final var account = conversation.getAccount();
5173        final var connection = account.getXmppConnection();
5174        if (connection == null || !connection.getFeatures().mds()) {
5175            return;
5176        }
5177        final Jid itemId;
5178        if (message.isPrivateMessage()) {
5179            itemId = message.getCounterpart();
5180        } else {
5181            itemId = conversation.getJid().asBareJid();
5182        }
5183        Log.d(Config.LOGTAG, "publishing mds for " + itemId + "/" + stanzaId);
5184        final var displayed =
5185                MessageDisplayedSynchronizationManager.displayed(stanzaId, conversation);
5186        connection
5187                .getManager(MessageDisplayedSynchronizationManager.class)
5188                .publish(itemId, displayed);
5189    }
5190
5191    public boolean sendReactions(final Message message, final Collection<String> reactions) {
5192        if (message.getConversation() instanceof Conversation conversation) {
5193            final var isPrivateMessage = message.isPrivateMessage();
5194            final Jid reactTo;
5195            final boolean typeGroupChat;
5196            final String reactToId;
5197            final Collection<Reaction> combinedReactions;
5198            if (conversation.getMode() == Conversational.MODE_MULTI && !isPrivateMessage) {
5199                final var mucOptions = conversation.getMucOptions();
5200                if (!mucOptions.participating()) {
5201                    Log.e(Config.LOGTAG, "not participating in MUC");
5202                    return false;
5203                }
5204                final var self = mucOptions.getSelf();
5205                final String occupantId = self.getOccupantId();
5206                if (Strings.isNullOrEmpty(occupantId)) {
5207                    Log.e(Config.LOGTAG, "occupant id not found for reaction in MUC");
5208                    return false;
5209                }
5210                final var existingRaw =
5211                        ImmutableSet.copyOf(
5212                                Collections2.transform(message.getReactions(), r -> r.reaction));
5213                final var reactionsAsExistingVariants =
5214                        ImmutableSet.copyOf(
5215                                Collections2.transform(
5216                                        reactions, r -> Emoticons.existingVariant(r, existingRaw)));
5217                if (!reactions.equals(reactionsAsExistingVariants)) {
5218                    Log.d(Config.LOGTAG, "modified reactions to existing variants");
5219                }
5220                reactToId = message.getServerMsgId();
5221                reactTo = conversation.getJid().asBareJid();
5222                typeGroupChat = true;
5223                combinedReactions =
5224                        Reaction.withOccupantId(
5225                                message.getReactions(),
5226                                reactionsAsExistingVariants,
5227                                false,
5228                                self.getFullJid(),
5229                                conversation.getAccount().getJid(),
5230                                occupantId);
5231            } else {
5232                if (message.isCarbon() || message.getStatus() == Message.STATUS_RECEIVED) {
5233                    reactToId = message.getRemoteMsgId();
5234                } else {
5235                    reactToId = message.getUuid();
5236                }
5237                typeGroupChat = false;
5238                if (isPrivateMessage) {
5239                    reactTo = message.getCounterpart();
5240                } else {
5241                    reactTo = conversation.getJid().asBareJid();
5242                }
5243                combinedReactions =
5244                        Reaction.withFrom(
5245                                message.getReactions(),
5246                                reactions,
5247                                false,
5248                                conversation.getAccount().getJid());
5249            }
5250            if (reactTo == null || Strings.isNullOrEmpty(reactToId)) {
5251                Log.e(Config.LOGTAG, "could not find id to react to");
5252                return false;
5253            }
5254            final var reactionMessage =
5255                    mMessageGenerator.reaction(reactTo, typeGroupChat, reactToId, reactions);
5256            sendMessagePacket(conversation.getAccount(), reactionMessage);
5257            message.setReactions(combinedReactions);
5258            updateMessage(message, false);
5259            return true;
5260        } else {
5261            return false;
5262        }
5263    }
5264
5265    public MemorizingTrustManager getMemorizingTrustManager() {
5266        return this.mMemorizingTrustManager;
5267    }
5268
5269    public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
5270        this.mMemorizingTrustManager = trustManager;
5271    }
5272
5273    public void updateMemorizingTrustManager() {
5274        final MemorizingTrustManager trustManager;
5275        if (appSettings.isTrustSystemCAStore()) {
5276            trustManager = new MemorizingTrustManager(getApplicationContext());
5277        } else {
5278            trustManager = new MemorizingTrustManager(getApplicationContext(), null);
5279        }
5280        setMemorizingTrustManager(trustManager);
5281    }
5282
5283    public LruCache<String, Bitmap> getBitmapCache() {
5284        return this.mBitmapCache;
5285    }
5286
5287    public Collection<String> getKnownHosts() {
5288        final Set<String> hosts = new HashSet<>();
5289        for (final Account account : getAccounts()) {
5290            hosts.add(account.getServer());
5291            for (final Contact contact : account.getRoster().getContacts()) {
5292                if (contact.showInRoster()) {
5293                    final String server = contact.getServer();
5294                    if (server != null) {
5295                        hosts.add(server);
5296                    }
5297                }
5298            }
5299        }
5300        if (Config.QUICKSY_DOMAIN != null) {
5301            hosts.remove(
5302                    Config.QUICKSY_DOMAIN
5303                            .toString()); // we only want to show this when we type a e164
5304            // number
5305        }
5306        if (Config.MAGIC_CREATE_DOMAIN != null) {
5307            hosts.add(Config.MAGIC_CREATE_DOMAIN);
5308        }
5309        return hosts;
5310    }
5311
5312    public Collection<String> getKnownConferenceHosts() {
5313        final Set<String> mucServers = new HashSet<>();
5314        for (final Account account : accounts) {
5315            if (account.getXmppConnection() != null) {
5316                mucServers.addAll(account.getXmppConnection().getMucServers());
5317                for (final Bookmark bookmark : account.getBookmarks()) {
5318                    final Jid jid = bookmark.getJid();
5319                    final String s = jid == null ? null : jid.getDomain().toString();
5320                    if (s != null) {
5321                        mucServers.add(s);
5322                    }
5323                }
5324            }
5325        }
5326        return mucServers;
5327    }
5328
5329    public void sendMessagePacket(
5330            final Account account,
5331            final im.conversations.android.xmpp.model.stanza.Message packet) {
5332        final XmppConnection connection = account.getXmppConnection();
5333        if (connection != null) {
5334            connection.sendMessagePacket(packet);
5335        }
5336    }
5337
5338    public void sendPresencePacket(
5339            final Account account,
5340            final im.conversations.android.xmpp.model.stanza.Presence packet) {
5341        final XmppConnection connection = account.getXmppConnection();
5342        if (connection != null) {
5343            connection.sendPresencePacket(packet);
5344        }
5345    }
5346
5347    public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
5348        final XmppConnection connection = account.getXmppConnection();
5349        if (connection == null) {
5350            return;
5351        }
5352        connection.sendCreateAccountWithCaptchaPacket(id, data);
5353    }
5354
5355    public ListenableFuture<Iq> sendIqPacket(final Account account, final Iq request) {
5356        final XmppConnection connection = account.getXmppConnection();
5357        if (connection == null) {
5358            return Futures.immediateFailedFuture(new TimeoutException());
5359        }
5360        return connection.sendIqPacket(request);
5361    }
5362
5363    public void sendIqPacket(final Account account, final Iq packet, final Consumer<Iq> callback) {
5364        final XmppConnection connection = account.getXmppConnection();
5365        if (connection != null) {
5366            connection.sendIqPacket(packet, callback);
5367        } else if (callback != null) {
5368            callback.accept(Iq.TIMEOUT);
5369        }
5370    }
5371
5372    public void sendPresence(final Account account) {
5373        sendPresence(account, checkListeners() && broadcastLastActivity());
5374    }
5375
5376    private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
5377        final im.conversations.android.xmpp.model.stanza.Presence.Availability status;
5378        if (manuallyChangePresence()) {
5379            status = account.getPresenceStatus();
5380        } else {
5381            status = getTargetPresence();
5382        }
5383        final var packet = mPresenceGenerator.selfPresence(account, status);
5384        if (mLastActivity > 0 && includeIdleTimestamp) {
5385            long since =
5386                    Math.min(mLastActivity, System.currentTimeMillis()); // don't send future dates
5387            packet.addChild("idle", Namespace.IDLE)
5388                    .setAttribute("since", AbstractGenerator.getTimestamp(since));
5389        }
5390        sendPresencePacket(account, packet);
5391    }
5392
5393    private void deactivateGracePeriod() {
5394        for (Account account : getAccounts()) {
5395            account.deactivateGracePeriod();
5396        }
5397    }
5398
5399    public void refreshAllPresences() {
5400        boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
5401        for (Account account : getAccounts()) {
5402            if (account.isConnectionEnabled()) {
5403                sendPresence(account, includeIdleTimestamp);
5404            }
5405        }
5406    }
5407
5408    private void refreshAllFcmTokens() {
5409        for (Account account : getAccounts()) {
5410            if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
5411                mPushManagementService.registerPushTokenOnServer(account);
5412            }
5413        }
5414    }
5415
5416    private void sendOfflinePresence(final Account account) {
5417        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
5418        sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
5419    }
5420
5421    public MessageGenerator getMessageGenerator() {
5422        return this.mMessageGenerator;
5423    }
5424
5425    public PresenceGenerator getPresenceGenerator() {
5426        return this.mPresenceGenerator;
5427    }
5428
5429    public IqGenerator getIqGenerator() {
5430        return this.mIqGenerator;
5431    }
5432
5433    public JingleConnectionManager getJingleConnectionManager() {
5434        return this.mJingleConnectionManager;
5435    }
5436
5437    public boolean hasJingleRtpConnection(final Account account) {
5438        return this.mJingleConnectionManager.hasJingleRtpConnection(account);
5439    }
5440
5441    public MessageArchiveService getMessageArchiveService() {
5442        return this.mMessageArchiveService;
5443    }
5444
5445    public QuickConversationsService getQuickConversationsService() {
5446        return this.mQuickConversationsService;
5447    }
5448
5449    public List<Contact> findContacts(Jid jid, String accountJid) {
5450        ArrayList<Contact> contacts = new ArrayList<>();
5451        for (Account account : getAccounts()) {
5452            if ((account.isEnabled() || accountJid != null)
5453                    && (accountJid == null
5454                            || accountJid.equals(account.getJid().asBareJid().toString()))) {
5455                Contact contact = account.getRoster().getContactFromContactList(jid);
5456                if (contact != null) {
5457                    contacts.add(contact);
5458                }
5459            }
5460        }
5461        return contacts;
5462    }
5463
5464    public Conversation findFirstMuc(Jid jid) {
5465        for (Conversation conversation : getConversations()) {
5466            if (conversation.getAccount().isEnabled()
5467                    && conversation.getJid().asBareJid().equals(jid.asBareJid())
5468                    && conversation.getMode() == Conversation.MODE_MULTI) {
5469                return conversation;
5470            }
5471        }
5472        return null;
5473    }
5474
5475    public NotificationService getNotificationService() {
5476        return this.mNotificationService;
5477    }
5478
5479    public HttpConnectionManager getHttpConnectionManager() {
5480        return this.mHttpConnectionManager;
5481    }
5482
5483    public void resendFailedMessages(final Message message, final boolean forceP2P) {
5484        message.setTime(System.currentTimeMillis());
5485        markMessage(message, Message.STATUS_WAITING);
5486        this.sendMessage(message, true, false, forceP2P);
5487        if (message.getConversation() instanceof Conversation c) {
5488            c.sort();
5489        }
5490        updateConversationUi();
5491    }
5492
5493    public void clearConversationHistory(final Conversation conversation) {
5494        final long clearDate;
5495        final String reference;
5496        if (conversation.countMessages() > 0) {
5497            Message latestMessage = conversation.getLatestMessage();
5498            clearDate = latestMessage.getTimeSent() + 1000;
5499            reference = latestMessage.getServerMsgId();
5500        } else {
5501            clearDate = System.currentTimeMillis();
5502            reference = null;
5503        }
5504        conversation.clearMessages();
5505        conversation.setHasMessagesLeftOnServer(false); // avoid messages getting loaded through mam
5506        conversation.setLastClearHistory(clearDate, reference);
5507        Runnable runnable =
5508                () -> {
5509                    databaseBackend.deleteMessagesInConversation(conversation);
5510                    databaseBackend.updateConversation(conversation);
5511                };
5512        mDatabaseWriterExecutor.execute(runnable);
5513    }
5514
5515    public boolean sendBlockRequest(
5516            final Blockable blockable, final boolean reportSpam, final String serverMsgId) {
5517        final var account = blockable.getAccount();
5518        final var connection = account.getXmppConnection();
5519        return connection
5520                .getManager(BlockingManager.class)
5521                .block(blockable, reportSpam, serverMsgId);
5522    }
5523
5524    public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
5525        boolean removed = false;
5526        synchronized (this.conversations) {
5527            boolean domainJid = blockedJid.getLocal() == null;
5528            for (Conversation conversation : this.conversations) {
5529                boolean jidMatches =
5530                        (domainJid
5531                                        && blockedJid
5532                                                .getDomain()
5533                                                .equals(conversation.getJid().getDomain()))
5534                                || blockedJid.equals(conversation.getJid().asBareJid());
5535                if (conversation.getAccount() == account
5536                        && conversation.getMode() == Conversation.MODE_SINGLE
5537                        && jidMatches) {
5538                    this.conversations.remove(conversation);
5539                    markRead(conversation);
5540                    conversation.setStatus(Conversation.STATUS_ARCHIVED);
5541                    Log.d(
5542                            Config.LOGTAG,
5543                            account.getJid().asBareJid()
5544                                    + ": archiving conversation "
5545                                    + conversation.getJid().asBareJid()
5546                                    + " because jid was blocked");
5547                    updateConversation(conversation);
5548                    removed = true;
5549                }
5550            }
5551        }
5552        return removed;
5553    }
5554
5555    public void sendUnblockRequest(final Blockable blockable) {
5556        final var account = blockable.getAccount();
5557        final var connection = account.getXmppConnection();
5558        connection.getManager(BlockingManager.class).unblock(blockable);
5559    }
5560
5561    public void publishDisplayName(final Account account) {
5562        final var connection = account.getXmppConnection();
5563        final String displayName = account.getDisplayName();
5564        mAvatarService.clear(account);
5565        final var future = connection.getManager(NickManager.class).publish(displayName);
5566        Futures.addCallback(
5567                future,
5568                new FutureCallback<Void>() {
5569                    @Override
5570                    public void onSuccess(Void result) {
5571                        Log.d(
5572                                Config.LOGTAG,
5573                                account.getJid().asBareJid() + ": published User Nick");
5574                    }
5575
5576                    @Override
5577                    public void onFailure(@NonNull Throwable t) {
5578                        Log.d(Config.LOGTAG, "could not publish User Nick", t);
5579                    }
5580                },
5581                MoreExecutors.directExecutor());
5582    }
5583
5584    public void fetchMamPreferences(final Account account, final OnMamPreferencesFetched callback) {
5585        final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
5586        final Iq request = new Iq(Iq.Type.GET);
5587        request.addChild("prefs", version.namespace);
5588        sendIqPacket(
5589                account,
5590                request,
5591                (packet) -> {
5592                    final Element prefs = packet.findChild("prefs", version.namespace);
5593                    if (packet.getType() == Iq.Type.RESULT && prefs != null) {
5594                        callback.onPreferencesFetched(prefs);
5595                    } else {
5596                        callback.onPreferencesFetchFailed();
5597                    }
5598                });
5599    }
5600
5601    public PushManagementService getPushManagementService() {
5602        return mPushManagementService;
5603    }
5604
5605    public void changeStatus(Account account, PresenceTemplate template, String signature) {
5606        if (!template.getStatusMessage().isEmpty()) {
5607            databaseBackend.insertPresenceTemplate(template);
5608        }
5609        account.setPgpSignature(signature);
5610        account.setPresenceStatus(template.getStatus());
5611        account.setPresenceStatusMessage(template.getStatusMessage());
5612        databaseBackend.updateAccount(account);
5613        sendPresence(account);
5614    }
5615
5616    public List<PresenceTemplate> getPresenceTemplates(Account account) {
5617        List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
5618        for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
5619            if (!templates.contains(template)) {
5620                templates.add(0, template);
5621            }
5622        }
5623        return templates;
5624    }
5625
5626    public void saveConversationAsBookmark(final Conversation conversation, final String name) {
5627        final Account account = conversation.getAccount();
5628        final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
5629        final String nick = conversation.getJid().getResource();
5630        if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
5631            bookmark.setNick(nick);
5632        }
5633        if (!TextUtils.isEmpty(name)) {
5634            bookmark.setBookmarkName(name);
5635        }
5636        bookmark.setAutojoin(true);
5637        createBookmark(account, bookmark);
5638        bookmark.setConversation(conversation);
5639    }
5640
5641    public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
5642        boolean performedVerification = false;
5643        final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
5644        for (XmppUri.Fingerprint fp : fingerprints) {
5645            if (fp.type == XmppUri.FingerprintType.OMEMO) {
5646                String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
5647                FingerprintStatus fingerprintStatus =
5648                        axolotlService.getFingerprintTrust(fingerprint);
5649                if (fingerprintStatus != null) {
5650                    if (!fingerprintStatus.isVerified()) {
5651                        performedVerification = true;
5652                        axolotlService.setFingerprintTrust(
5653                                fingerprint, fingerprintStatus.toVerified());
5654                    }
5655                } else {
5656                    axolotlService.preVerifyFingerprint(contact, fingerprint);
5657                }
5658            }
5659        }
5660        return performedVerification;
5661    }
5662
5663    public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
5664        final AxolotlService axolotlService = account.getAxolotlService();
5665        boolean verifiedSomething = false;
5666        for (XmppUri.Fingerprint fp : fingerprints) {
5667            if (fp.type == XmppUri.FingerprintType.OMEMO) {
5668                String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
5669                Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
5670                FingerprintStatus fingerprintStatus =
5671                        axolotlService.getFingerprintTrust(fingerprint);
5672                if (fingerprintStatus != null) {
5673                    if (!fingerprintStatus.isVerified()) {
5674                        axolotlService.setFingerprintTrust(
5675                                fingerprint, fingerprintStatus.toVerified());
5676                        verifiedSomething = true;
5677                    }
5678                } else {
5679                    axolotlService.preVerifyFingerprint(account, fingerprint);
5680                    verifiedSomething = true;
5681                }
5682            }
5683        }
5684        return verifiedSomething;
5685    }
5686
5687    public ShortcutService getShortcutService() {
5688        return mShortcutService;
5689    }
5690
5691    public void pushMamPreferences(Account account, Element prefs) {
5692        final Iq set = new Iq(Iq.Type.SET);
5693        set.addChild(prefs);
5694        sendIqPacket(account, set, null);
5695    }
5696
5697    public void evictPreview(String uuid) {
5698        if (mBitmapCache.remove(uuid) != null) {
5699            Log.d(Config.LOGTAG, "deleted cached preview");
5700        }
5701    }
5702
5703    public interface OnMamPreferencesFetched {
5704        void onPreferencesFetched(Element prefs);
5705
5706        void onPreferencesFetchFailed();
5707    }
5708
5709    public interface OnAccountCreated {
5710        void onAccountCreated(Account account);
5711
5712        void informUser(int r);
5713    }
5714
5715    public interface OnMoreMessagesLoaded {
5716        void onMoreMessagesLoaded(int count, Conversation conversation);
5717
5718        void informUser(int r);
5719    }
5720
5721    public interface OnAccountPasswordChanged {
5722        void onPasswordChangeSucceeded();
5723
5724        void onPasswordChangeFailed();
5725    }
5726
5727    public interface OnRoomDestroy {
5728        void onRoomDestroySucceeded();
5729
5730        void onRoomDestroyFailed();
5731    }
5732
5733    public interface OnAffiliationChanged {
5734        void onAffiliationChangedSuccessful(Jid jid);
5735
5736        void onAffiliationChangeFailed(Jid jid, int resId);
5737    }
5738
5739    public interface OnConversationUpdate {
5740        void onConversationUpdate();
5741    }
5742
5743    public interface OnJingleRtpConnectionUpdate {
5744        void onJingleRtpConnectionUpdate(
5745                final Account account,
5746                final Jid with,
5747                final String sessionId,
5748                final RtpEndUserState state);
5749
5750        void onAudioDeviceChanged(
5751                CallIntegration.AudioDevice selectedAudioDevice,
5752                Set<CallIntegration.AudioDevice> availableAudioDevices);
5753    }
5754
5755    public interface OnAccountUpdate {
5756        void onAccountUpdate();
5757    }
5758
5759    public interface OnCaptchaRequested {
5760        void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
5761    }
5762
5763    public interface OnRosterUpdate {
5764        void onRosterUpdate();
5765    }
5766
5767    public interface OnMucRosterUpdate {
5768        void onMucRosterUpdate();
5769    }
5770
5771    public interface OnConferenceConfigurationFetched {
5772        void onConferenceConfigurationFetched(Conversation conversation);
5773
5774        void onFetchFailed(Conversation conversation, String errorCondition);
5775    }
5776
5777    public interface OnConferenceJoined {
5778        void onConferenceJoined(Conversation conversation);
5779    }
5780
5781    public interface OnConfigurationPushed {
5782        void onPushSucceeded();
5783
5784        void onPushFailed();
5785    }
5786
5787    public interface OnShowErrorToast {
5788        void onShowErrorToast(int resId);
5789    }
5790
5791    public class XmppConnectionBinder extends Binder {
5792        public XmppConnectionService getService() {
5793            return XmppConnectionService.this;
5794        }
5795    }
5796
5797    private class InternalEventReceiver extends BroadcastReceiver {
5798
5799        @Override
5800        public void onReceive(final Context context, final Intent intent) {
5801            onStartCommand(intent, 0, 0);
5802        }
5803    }
5804
5805    private class RestrictedEventReceiver extends BroadcastReceiver {
5806
5807        private final Collection<String> allowedActions;
5808
5809        private RestrictedEventReceiver(final Collection<String> allowedActions) {
5810            this.allowedActions = allowedActions;
5811        }
5812
5813        @Override
5814        public void onReceive(final Context context, final Intent intent) {
5815            final String action = intent == null ? null : intent.getAction();
5816            if (allowedActions.contains(action)) {
5817                onStartCommand(intent, 0, 0);
5818            } else {
5819                Log.e(Config.LOGTAG, "restricting broadcast of event " + action);
5820            }
5821        }
5822    }
5823
5824    public static class OngoingCall {
5825        public final AbstractJingleConnection.Id id;
5826        public final Set<Media> media;
5827        public final boolean reconnecting;
5828
5829        public OngoingCall(
5830                AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
5831            this.id = id;
5832            this.media = media;
5833            this.reconnecting = reconnecting;
5834        }
5835
5836        @Override
5837        public boolean equals(Object o) {
5838            if (this == o) return true;
5839            if (o == null || getClass() != o.getClass()) return false;
5840            OngoingCall that = (OngoingCall) o;
5841            return reconnecting == that.reconnecting
5842                    && Objects.equal(id, that.id)
5843                    && Objects.equal(media, that.media);
5844        }
5845
5846        @Override
5847        public int hashCode() {
5848            return Objects.hashCode(id, media, reconnecting);
5849        }
5850    }
5851
5852    public static void toggleForegroundService(final XmppConnectionService service) {
5853        if (service == null) {
5854            return;
5855        }
5856        service.toggleForegroundService();
5857    }
5858
5859    public static void toggleForegroundService(final ConversationsActivity activity) {
5860        if (activity == null) {
5861            return;
5862        }
5863        toggleForegroundService(activity.xmppConnectionService);
5864    }
5865}