XmppConnectionService.java

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