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.Jid;
 124import eu.siacs.conversations.xmpp.OnContactStatusChanged;
 125import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
 126import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
 127import eu.siacs.conversations.xmpp.OnStatusChanged;
 128import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 129import eu.siacs.conversations.xmpp.XmppConnection;
 130import eu.siacs.conversations.xmpp.chatstate.ChatState;
 131import eu.siacs.conversations.xmpp.forms.Data;
 132import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
 133import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
 134import eu.siacs.conversations.xmpp.jingle.JingleRtpConnection;
 135import eu.siacs.conversations.xmpp.jingle.Media;
 136import eu.siacs.conversations.xmpp.jingle.RtpEndUserState;
 137import eu.siacs.conversations.xmpp.mam.MamReference;
 138import eu.siacs.conversations.xmpp.pep.Avatar;
 139import eu.siacs.conversations.xmpp.pep.PublishOptions;
 140import im.conversations.android.xmpp.model.stanza.Iq;
 141import java.io.File;
 142import java.security.Security;
 143import java.security.cert.CertificateException;
 144import java.security.cert.X509Certificate;
 145import java.util.ArrayList;
 146import java.util.Arrays;
 147import java.util.Collection;
 148import java.util.Collections;
 149import java.util.HashSet;
 150import java.util.Iterator;
 151import java.util.List;
 152import java.util.ListIterator;
 153import java.util.Map;
 154import java.util.Set;
 155import java.util.WeakHashMap;
 156import java.util.concurrent.CopyOnWriteArrayList;
 157import java.util.concurrent.CountDownLatch;
 158import java.util.concurrent.Executor;
 159import java.util.concurrent.Executors;
 160import java.util.concurrent.RejectedExecutionException;
 161import java.util.concurrent.ScheduledExecutorService;
 162import java.util.concurrent.TimeUnit;
 163import java.util.concurrent.atomic.AtomicBoolean;
 164import java.util.concurrent.atomic.AtomicLong;
 165import java.util.concurrent.atomic.AtomicReference;
 166import java.util.function.Consumer;
 167import me.leolin.shortcutbadger.ShortcutBadger;
 168import org.conscrypt.Conscrypt;
 169import org.jxmpp.stringprep.libidn.LibIdnXmppStringprep;
 170import org.openintents.openpgp.IOpenPgpService2;
 171import org.openintents.openpgp.util.OpenPgpApi;
 172import org.openintents.openpgp.util.OpenPgpServiceConnection;
 173
 174public class XmppConnectionService extends Service {
 175
 176    public static final String ACTION_REPLY_TO_CONVERSATION = "reply_to_conversations";
 177    public static final String ACTION_MARK_AS_READ = "mark_as_read";
 178    public static final String ACTION_SNOOZE = "snooze";
 179    public static final String ACTION_CLEAR_MESSAGE_NOTIFICATION = "clear_message_notification";
 180    public static final String ACTION_CLEAR_MISSED_CALL_NOTIFICATION =
 181            "clear_missed_call_notification";
 182    public static final String ACTION_DISMISS_ERROR_NOTIFICATIONS = "dismiss_error";
 183    public static final String ACTION_TRY_AGAIN = "try_again";
 184
 185    public static final String ACTION_TEMPORARILY_DISABLE = "temporarily_disable";
 186    public static final String ACTION_PING = "ping";
 187    public static final String ACTION_IDLE_PING = "idle_ping";
 188    public static final String ACTION_INTERNAL_PING = "internal_ping";
 189    public static final String ACTION_FCM_TOKEN_REFRESH = "fcm_token_refresh";
 190    public static final String ACTION_FCM_MESSAGE_RECEIVED = "fcm_message_received";
 191    public static final String ACTION_DISMISS_CALL = "dismiss_call";
 192    public static final String ACTION_END_CALL = "end_call";
 193    public static final String ACTION_PROVISION_ACCOUNT = "provision_account";
 194    public static final String ACTION_CALL_INTEGRATION_SERVICE_STARTED =
 195            "call_integration_service_started";
 196    private static final String ACTION_POST_CONNECTIVITY_CHANGE =
 197            "eu.siacs.conversations.POST_CONNECTIVITY_CHANGE";
 198    public static final String ACTION_RENEW_UNIFIED_PUSH_ENDPOINTS =
 199            "eu.siacs.conversations.UNIFIED_PUSH_RENEW";
 200    public static final String ACTION_QUICK_LOG = "eu.siacs.conversations.QUICK_LOG";
 201
 202    private static final String SETTING_LAST_ACTIVITY_TS = "last_activity_timestamp";
 203
 204    public final CountDownLatch restoredFromDatabaseLatch = new CountDownLatch(1);
 205    private static final Executor FILE_OBSERVER_EXECUTOR = Executors.newSingleThreadExecutor();
 206    public static final Executor FILE_ATTACHMENT_EXECUTOR = Executors.newSingleThreadExecutor();
 207
 208    private final ScheduledExecutorService internalPingExecutor =
 209            Executors.newSingleThreadScheduledExecutor();
 210    private static final SerialSingleThreadExecutor VIDEO_COMPRESSION_EXECUTOR =
 211            new SerialSingleThreadExecutor("VideoCompression");
 212    private final SerialSingleThreadExecutor mDatabaseWriterExecutor =
 213            new SerialSingleThreadExecutor("DatabaseWriter");
 214    private final SerialSingleThreadExecutor mDatabaseReaderExecutor =
 215            new SerialSingleThreadExecutor("DatabaseReader");
 216    private final SerialSingleThreadExecutor mNotificationExecutor =
 217            new SerialSingleThreadExecutor("NotificationExecutor");
 218    private final ReplacingTaskManager mRosterSyncTaskManager = new ReplacingTaskManager();
 219    private final IBinder mBinder = new XmppConnectionBinder();
 220    private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
 221    private final IqGenerator mIqGenerator = new IqGenerator(this);
 222    private final Set<String> mInProgressAvatarFetches = new HashSet<>();
 223    private final Set<String> mOmittedPepAvatarFetches = new HashSet<>();
 224    private final HashSet<Jid> mLowPingTimeoutMode = new HashSet<>();
 225    private final Consumer<Iq> mDefaultIqHandler =
 226            (packet) -> {
 227                if (packet.getType() != Iq.Type.RESULT) {
 228                    final var error = packet.getError();
 229                    String text = error != null ? error.findChildContent("text") : null;
 230                    if (text != null) {
 231                        Log.d(Config.LOGTAG, "received iq error: " + text);
 232                    }
 233                }
 234            };
 235    public DatabaseBackend databaseBackend;
 236    private final ReplacingSerialSingleThreadExecutor mContactMergerExecutor =
 237            new ReplacingSerialSingleThreadExecutor("ContactMerger");
 238    private long mLastActivity = 0;
 239
 240    private final AppSettings appSettings = new AppSettings(this);
 241    private final FileBackend fileBackend = new FileBackend(this);
 242    private MemorizingTrustManager mMemorizingTrustManager;
 243    private final NotificationService mNotificationService = new NotificationService(this);
 244    private final UnifiedPushBroker unifiedPushBroker = new UnifiedPushBroker(this);
 245    private final ChannelDiscoveryService mChannelDiscoveryService =
 246            new ChannelDiscoveryService(this);
 247    private final ShortcutService mShortcutService = new ShortcutService(this);
 248    private final AtomicBoolean mInitialAddressbookSyncCompleted = new AtomicBoolean(false);
 249    private final AtomicBoolean mOngoingVideoTranscoding = new AtomicBoolean(false);
 250    private final AtomicBoolean mForceDuringOnCreate = new AtomicBoolean(false);
 251    private final AtomicReference<OngoingCall> ongoingCall = new AtomicReference<>();
 252    private final MessageGenerator mMessageGenerator = new MessageGenerator(this);
 253    public OnContactStatusChanged onContactStatusChanged =
 254            (contact, online) -> {
 255                final var conversation = find(contact);
 256                if (conversation == null) {
 257                    return;
 258                }
 259                if (online) {
 260                    if (contact.getPresences().size() == 1) {
 261                        sendUnsentMessages(conversation);
 262                    }
 263                }
 264            };
 265    private final PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
 266    private List<Account> accounts;
 267    private final JingleConnectionManager mJingleConnectionManager =
 268            new JingleConnectionManager(this);
 269    private final HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(this);
 270    private final AvatarService mAvatarService = new AvatarService(this);
 271    private final MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
 272    private final PushManagementService mPushManagementService = new PushManagementService(this);
 273    private final QuickConversationsService mQuickConversationsService =
 274            new QuickConversationsService(this);
 275    private final ConversationsFileObserver fileObserver =
 276            new ConversationsFileObserver(
 277                    Environment.getExternalStorageDirectory().getAbsolutePath()) {
 278                @Override
 279                public void onEvent(final int event, final File file) {
 280                    markFileDeleted(file);
 281                }
 282            };
 283    private final OnMessageAcknowledged mOnMessageAcknowledgedListener =
 284            new OnMessageAcknowledged() {
 285
 286                @Override
 287                public boolean onMessageAcknowledged(
 288                        final Account account, final Jid to, final String id) {
 289                    if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
 290                        final String sessionId =
 291                                id.substring(
 292                                        JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX
 293                                                .length());
 294                        mJingleConnectionManager.updateProposedSessionDiscovered(
 295                                account,
 296                                to,
 297                                sessionId,
 298                                JingleConnectionManager.DeviceDiscoveryState
 299                                        .SEARCHING_ACKNOWLEDGED);
 300                    }
 301
 302                    final Jid bare = to.asBareJid();
 303
 304                    for (final Conversation conversation : getConversations()) {
 305                        if (conversation.getAccount() == account
 306                                && conversation.getJid().asBareJid().equals(bare)) {
 307                            final Message message = conversation.findUnsentMessageWithUuid(id);
 308                            if (message != null) {
 309                                message.setStatus(Message.STATUS_SEND);
 310                                message.setErrorMessage(null);
 311                                databaseBackend.updateMessage(message, false);
 312                                return true;
 313                            }
 314                        }
 315                    }
 316                    return false;
 317                }
 318            };
 319
 320    private boolean destroyed = false;
 321
 322    private int unreadCount = -1;
 323
 324    // Ui callback listeners
 325    private final Set<OnConversationUpdate> mOnConversationUpdates =
 326            Collections.newSetFromMap(new WeakHashMap<OnConversationUpdate, Boolean>());
 327    private final Set<OnShowErrorToast> mOnShowErrorToasts =
 328            Collections.newSetFromMap(new WeakHashMap<OnShowErrorToast, Boolean>());
 329    private final Set<OnAccountUpdate> mOnAccountUpdates =
 330            Collections.newSetFromMap(new WeakHashMap<OnAccountUpdate, Boolean>());
 331    private final Set<OnCaptchaRequested> mOnCaptchaRequested =
 332            Collections.newSetFromMap(new WeakHashMap<OnCaptchaRequested, Boolean>());
 333    private final Set<OnRosterUpdate> mOnRosterUpdates =
 334            Collections.newSetFromMap(new WeakHashMap<OnRosterUpdate, Boolean>());
 335    private final Set<OnUpdateBlocklist> mOnUpdateBlocklist =
 336            Collections.newSetFromMap(new WeakHashMap<OnUpdateBlocklist, Boolean>());
 337    private final Set<OnMucRosterUpdate> mOnMucRosterUpdate =
 338            Collections.newSetFromMap(new WeakHashMap<OnMucRosterUpdate, Boolean>());
 339    private final Set<OnKeyStatusUpdated> mOnKeyStatusUpdated =
 340            Collections.newSetFromMap(new WeakHashMap<OnKeyStatusUpdated, Boolean>());
 341    private final Set<OnJingleRtpConnectionUpdate> onJingleRtpConnectionUpdate =
 342            Collections.newSetFromMap(new WeakHashMap<OnJingleRtpConnectionUpdate, Boolean>());
 343
 344    private final Object LISTENER_LOCK = new Object();
 345
 346    public final Set<String> FILENAMES_TO_IGNORE_DELETION = new HashSet<>();
 347
 348    private final AtomicLong mLastExpiryRun = new AtomicLong(0);
 349    private final LruCache<Pair<String, String>, ServiceDiscoveryResult> discoCache =
 350            new LruCache<>(20);
 351    private final OnStatusChanged statusListener =
 352            new OnStatusChanged() {
 353
 354                @Override
 355                public void onStatusChanged(final Account account) {
 356                    XmppConnection connection = account.getXmppConnection();
 357                    updateAccountUi();
 358
 359                    if (account.getStatus() == Account.State.ONLINE
 360                            || account.getStatus().isError()) {
 361                        mQuickConversationsService.signalAccountStateChange();
 362                    }
 363
 364                    if (account.getStatus() == Account.State.ONLINE) {
 365                        synchronized (mLowPingTimeoutMode) {
 366                            if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
 367                                Log.d(
 368                                        Config.LOGTAG,
 369                                        account.getJid().asBareJid()
 370                                                + ": leaving low ping timeout mode");
 371                            }
 372                        }
 373                        if (account.setShowErrorNotification(true)) {
 374                            databaseBackend.updateAccount(account);
 375                        }
 376                        mMessageArchiveService.executePendingQueries(account);
 377                        if (connection != null && connection.getFeatures().csi()) {
 378                            if (checkListeners()) {
 379                                Log.d(
 380                                        Config.LOGTAG,
 381                                        account.getJid().asBareJid() + " sending csi//inactive");
 382                                connection.sendInactive();
 383                            } else {
 384                                Log.d(
 385                                        Config.LOGTAG,
 386                                        account.getJid().asBareJid() + " sending csi//active");
 387                                connection.sendActive();
 388                            }
 389                        }
 390                        List<Conversation> conversations = getConversations();
 391                        for (Conversation conversation : conversations) {
 392                            final boolean inProgressJoin;
 393                            synchronized (account.inProgressConferenceJoins) {
 394                                inProgressJoin =
 395                                        account.inProgressConferenceJoins.contains(conversation);
 396                            }
 397                            final boolean pendingJoin;
 398                            synchronized (account.pendingConferenceJoins) {
 399                                pendingJoin = account.pendingConferenceJoins.contains(conversation);
 400                            }
 401                            if (conversation.getAccount() == account
 402                                    && !pendingJoin
 403                                    && !inProgressJoin) {
 404                                sendUnsentMessages(conversation);
 405                            }
 406                        }
 407                        final List<Conversation> pendingLeaves;
 408                        synchronized (account.pendingConferenceLeaves) {
 409                            pendingLeaves = new ArrayList<>(account.pendingConferenceLeaves);
 410                            account.pendingConferenceLeaves.clear();
 411                        }
 412                        for (Conversation conversation : pendingLeaves) {
 413                            leaveMuc(conversation);
 414                        }
 415                        final List<Conversation> pendingJoins;
 416                        synchronized (account.pendingConferenceJoins) {
 417                            pendingJoins = new ArrayList<>(account.pendingConferenceJoins);
 418                            account.pendingConferenceJoins.clear();
 419                        }
 420                        for (Conversation conversation : pendingJoins) {
 421                            joinMuc(conversation);
 422                        }
 423                        scheduleWakeUpCall(
 424                                Config.PING_MAX_INTERVAL * 1000L, 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((seconds < 0 ? 1 : seconds + 1) * 1000L, requestCode);
1756    }
1757
1758    public 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().toString(), 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 : Jid.Invalid.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().toString(),
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().toString());
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.of(address);
3030        final Account account = new Account(jid, password);
3031        account.setOption(Account.OPTION_DISABLED, true);
3032        Log.d(Config.LOGTAG, jid.asBareJid().toString() + ": 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.isEmpty()
3459                && this.mOnConversationUpdates.isEmpty()
3460                && this.mOnRosterUpdates.isEmpty()
3461                && this.mOnCaptchaRequested.isEmpty()
3462                && this.mOnMucRosterUpdate.isEmpty()
3463                && this.mOnUpdateBlocklist.isEmpty()
3464                && this.mOnShowErrorToasts.isEmpty()
3465                && this.onJingleRtpConnectionUpdate.isEmpty()
3466                && this.mOnKeyStatusUpdated.isEmpty());
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                            final var mucOptions = conversation.getMucOptions();
3819                            final var members = mucOptions.getMembers(true);
3820                            if (success) {
3821                                List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
3822                                boolean changed = false;
3823                                for (ListIterator<Jid> iterator = cryptoTargets.listIterator();
3824                                        iterator.hasNext(); ) {
3825                                    Jid jid = iterator.next();
3826                                    if (!members.contains(jid)
3827                                            && !members.contains(jid.getDomain())) {
3828                                        iterator.remove();
3829                                        Log.d(
3830                                                Config.LOGTAG,
3831                                                account.getJid().asBareJid()
3832                                                        + ": removed "
3833                                                        + jid
3834                                                        + " from crypto targets of "
3835                                                        + conversation.getName());
3836                                        changed = true;
3837                                    }
3838                                }
3839                                if (changed) {
3840                                    conversation.setAcceptedCryptoTargets(cryptoTargets);
3841                                    updateConversation(conversation);
3842                                }
3843                            }
3844                            getAvatarService().clear(mucOptions);
3845                            updateMucRosterUi();
3846                            updateConversationUi();
3847                        }
3848                    }
3849                };
3850        for (String affiliation : affiliations) {
3851            sendIqPacket(
3852                    account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
3853        }
3854        Log.d(
3855                Config.LOGTAG,
3856                account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
3857    }
3858
3859    public void providePasswordForMuc(final Conversation conversation, final String password) {
3860        if (conversation.getMode() == Conversation.MODE_MULTI) {
3861            conversation.getMucOptions().setPassword(password);
3862            if (conversation.getBookmark() != null) {
3863                final Bookmark bookmark = conversation.getBookmark();
3864                bookmark.setAutojoin(true);
3865                createBookmark(conversation.getAccount(), bookmark);
3866            }
3867            updateConversation(conversation);
3868            joinMuc(conversation);
3869        }
3870    }
3871
3872    public void deleteAvatar(final Account account) {
3873        final AtomicBoolean executed = new AtomicBoolean(false);
3874        final Runnable onDeleted =
3875                () -> {
3876                    if (executed.compareAndSet(false, true)) {
3877                        account.setAvatar(null);
3878                        databaseBackend.updateAccount(account);
3879                        getAvatarService().clear(account);
3880                        updateAccountUi();
3881                    }
3882                };
3883        deleteVcardAvatar(account, onDeleted);
3884        deletePepNode(account, Namespace.AVATAR_DATA);
3885        deletePepNode(account, Namespace.AVATAR_METADATA, onDeleted);
3886    }
3887
3888    public void deletePepNode(final Account account, final String node) {
3889        deletePepNode(account, node, null);
3890    }
3891
3892    private void deletePepNode(final Account account, final String node, final Runnable runnable) {
3893        final Iq request = mIqGenerator.deleteNode(node);
3894        sendIqPacket(
3895                account,
3896                request,
3897                (packet) -> {
3898                    if (packet.getType() == Iq.Type.RESULT) {
3899                        Log.d(
3900                                Config.LOGTAG,
3901                                account.getJid().asBareJid()
3902                                        + ": successfully deleted pep node "
3903                                        + node);
3904                        if (runnable != null) {
3905                            runnable.run();
3906                        }
3907                    } else {
3908                        Log.d(
3909                                Config.LOGTAG,
3910                                account.getJid().asBareJid() + ": failed to delete " + packet);
3911                    }
3912                });
3913    }
3914
3915    private void deleteVcardAvatar(final Account account, @NonNull final Runnable runnable) {
3916        final Iq retrieveVcard = mIqGenerator.retrieveVcardAvatar(account.getJid().asBareJid());
3917        sendIqPacket(
3918                account,
3919                retrieveVcard,
3920                (response) -> {
3921                    if (response.getType() != Iq.Type.RESULT) {
3922                        Log.d(
3923                                Config.LOGTAG,
3924                                account.getJid().asBareJid() + ": no vCard set. nothing to do");
3925                        return;
3926                    }
3927                    final Element vcard = response.findChild("vCard", "vcard-temp");
3928                    if (vcard == null) {
3929                        Log.d(
3930                                Config.LOGTAG,
3931                                account.getJid().asBareJid() + ": no vCard set. nothing to do");
3932                        return;
3933                    }
3934                    Element photo = vcard.findChild("PHOTO");
3935                    if (photo == null) {
3936                        photo = vcard.addChild("PHOTO");
3937                    }
3938                    photo.clearChildren();
3939                    final Iq publication = new Iq(Iq.Type.SET);
3940                    publication.setTo(account.getJid().asBareJid());
3941                    publication.addChild(vcard);
3942                    sendIqPacket(
3943                            account,
3944                            publication,
3945                            (publicationResponse) -> {
3946                                if (publicationResponse.getType() == Iq.Type.RESULT) {
3947                                    Log.d(
3948                                            Config.LOGTAG,
3949                                            account.getJid().asBareJid()
3950                                                    + ": successfully deleted vcard avatar");
3951                                    runnable.run();
3952                                } else {
3953                                    Log.d(
3954                                            Config.LOGTAG,
3955                                            "failed to publish vcard "
3956                                                    + publicationResponse.getErrorCondition());
3957                                }
3958                            });
3959                });
3960    }
3961
3962    private boolean hasEnabledAccounts() {
3963        if (this.accounts == null) {
3964            return false;
3965        }
3966        for (final Account account : this.accounts) {
3967            if (account.isConnectionEnabled()) {
3968                return true;
3969            }
3970        }
3971        return false;
3972    }
3973
3974    public void getAttachments(
3975            final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
3976        getAttachments(
3977                conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
3978    }
3979
3980    public void getAttachments(
3981            final Account account,
3982            final Jid jid,
3983            final int limit,
3984            final OnMediaLoaded onMediaLoaded) {
3985        getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
3986    }
3987
3988    public void getAttachments(
3989            final String account,
3990            final Jid jid,
3991            final int limit,
3992            final OnMediaLoaded onMediaLoaded) {
3993        new Thread(
3994                        () ->
3995                                onMediaLoaded.onMediaLoaded(
3996                                        fileBackend.convertToAttachments(
3997                                                databaseBackend.getRelativeFilePaths(
3998                                                        account, jid, limit))))
3999                .start();
4000    }
4001
4002    public void persistSelfNick(final MucOptions.User self, final boolean modified) {
4003        final Conversation conversation = self.getConversation();
4004        final Account account = conversation.getAccount();
4005        final Jid full = self.getFullJid();
4006        if (!full.equals(conversation.getJid())) {
4007            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persisting full jid " + full);
4008            conversation.setContactJid(full);
4009            databaseBackend.updateConversation(conversation);
4010        }
4011
4012        final Bookmark bookmark = conversation.getBookmark();
4013        if (bookmark == null || !modified) {
4014            return;
4015        }
4016        final var nick = full.getResource();
4017        final String defaultNick = MucOptions.defaultNick(account);
4018        if (nick.equals(defaultNick) || nick.equals(bookmark.getNick())) {
4019            return;
4020        }
4021        Log.d(
4022                Config.LOGTAG,
4023                account.getJid().asBareJid()
4024                        + ": persist nick '"
4025                        + full.getResource()
4026                        + "' into bookmark for "
4027                        + conversation.getJid().asBareJid());
4028        bookmark.setNick(nick);
4029        createBookmark(bookmark.getAccount(), bookmark);
4030    }
4031
4032    public boolean renameInMuc(
4033            final Conversation conversation,
4034            final String nick,
4035            final UiCallback<Conversation> callback) {
4036        final Account account = conversation.getAccount();
4037        final Bookmark bookmark = conversation.getBookmark();
4038        final MucOptions options = conversation.getMucOptions();
4039        final Jid joinJid = options.createJoinJid(nick);
4040        if (joinJid == null) {
4041            return false;
4042        }
4043        if (options.online()) {
4044            options.setOnRenameListener(
4045                    new OnRenameListener() {
4046
4047                        @Override
4048                        public void onSuccess() {
4049                            callback.success(conversation);
4050                        }
4051
4052                        @Override
4053                        public void onFailure() {
4054                            callback.error(R.string.nick_in_use, conversation);
4055                        }
4056                    });
4057
4058            final var packet =
4059                    mPresenceGenerator.selfPresence(
4060                            account, Presence.Status.ONLINE, options.nonanonymous());
4061            packet.setTo(joinJid);
4062            sendPresencePacket(account, packet);
4063            if (nick.equals(MucOptions.defaultNick(account))
4064                    && bookmark != null
4065                    && bookmark.getNick() != null) {
4066                Log.d(
4067                        Config.LOGTAG,
4068                        account.getJid().asBareJid()
4069                                + ": removing nick from bookmark for "
4070                                + bookmark.getJid());
4071                bookmark.setNick(null);
4072                createBookmark(account, bookmark);
4073            }
4074        } else {
4075            conversation.setContactJid(joinJid);
4076            databaseBackend.updateConversation(conversation);
4077            if (account.getStatus() == Account.State.ONLINE) {
4078                if (bookmark != null) {
4079                    bookmark.setNick(nick);
4080                    createBookmark(account, bookmark);
4081                }
4082                joinMuc(conversation);
4083            }
4084        }
4085        return true;
4086    }
4087
4088    public void checkMucRequiresRename() {
4089        synchronized (this.conversations) {
4090            for (final Conversation conversation : this.conversations) {
4091                if (conversation.getMode() == Conversational.MODE_MULTI) {
4092                    checkMucRequiresRename(conversation);
4093                }
4094            }
4095        }
4096    }
4097
4098    private void checkMucRequiresRename(final Conversation conversation) {
4099        final var options = conversation.getMucOptions();
4100        if (!options.online()) {
4101            return;
4102        }
4103        final var account = conversation.getAccount();
4104        final String current = options.getActualNick();
4105        final String proposed = options.getProposedNickPure();
4106        if (current == null || current.equals(proposed)) {
4107            return;
4108        }
4109        final Jid joinJid = options.createJoinJid(proposed);
4110        Log.d(
4111                Config.LOGTAG,
4112                String.format(
4113                        "%s: muc rename required %s (was: %s)",
4114                        account.getJid().asBareJid(), joinJid, current));
4115        final var packet =
4116                mPresenceGenerator.selfPresence(
4117                        account, Presence.Status.ONLINE, options.nonanonymous());
4118        packet.setTo(joinJid);
4119        sendPresencePacket(account, packet);
4120    }
4121
4122    public void leaveMuc(Conversation conversation) {
4123        leaveMuc(conversation, false);
4124    }
4125
4126    private void leaveMuc(Conversation conversation, boolean now) {
4127        final Account account = conversation.getAccount();
4128        synchronized (account.pendingConferenceJoins) {
4129            account.pendingConferenceJoins.remove(conversation);
4130        }
4131        synchronized (account.pendingConferenceLeaves) {
4132            account.pendingConferenceLeaves.remove(conversation);
4133        }
4134        if (account.getStatus() == Account.State.ONLINE || now) {
4135            sendPresencePacket(
4136                    conversation.getAccount(),
4137                    mPresenceGenerator.leave(conversation.getMucOptions()));
4138            conversation.getMucOptions().setOffline();
4139            Bookmark bookmark = conversation.getBookmark();
4140            if (bookmark != null) {
4141                bookmark.setConversation(null);
4142            }
4143            Log.d(
4144                    Config.LOGTAG,
4145                    conversation.getAccount().getJid().asBareJid()
4146                            + ": leaving muc "
4147                            + conversation.getJid());
4148        } else {
4149            synchronized (account.pendingConferenceLeaves) {
4150                account.pendingConferenceLeaves.add(conversation);
4151            }
4152        }
4153    }
4154
4155    public String findConferenceServer(final Account account) {
4156        String server;
4157        if (account.getXmppConnection() != null) {
4158            server = account.getXmppConnection().getMucServer();
4159            if (server != null) {
4160                return server;
4161            }
4162        }
4163        for (Account other : getAccounts()) {
4164            if (other != account && other.getXmppConnection() != null) {
4165                server = other.getXmppConnection().getMucServer();
4166                if (server != null) {
4167                    return server;
4168                }
4169            }
4170        }
4171        return null;
4172    }
4173
4174    public void createPublicChannel(
4175            final Account account,
4176            final String name,
4177            final Jid address,
4178            final UiCallback<Conversation> callback) {
4179        joinMuc(
4180                findOrCreateConversation(account, address, true, false, true),
4181                conversation -> {
4182                    final Bundle configuration = IqGenerator.defaultChannelConfiguration();
4183                    if (!TextUtils.isEmpty(name)) {
4184                        configuration.putString("muc#roomconfig_roomname", name);
4185                    }
4186                    pushConferenceConfiguration(
4187                            conversation,
4188                            configuration,
4189                            new OnConfigurationPushed() {
4190                                @Override
4191                                public void onPushSucceeded() {
4192                                    saveConversationAsBookmark(conversation, name);
4193                                    callback.success(conversation);
4194                                }
4195
4196                                @Override
4197                                public void onPushFailed() {
4198                                    if (conversation
4199                                            .getMucOptions()
4200                                            .getSelf()
4201                                            .getAffiliation()
4202                                            .ranks(MucOptions.Affiliation.OWNER)) {
4203                                        callback.error(
4204                                                R.string.unable_to_set_channel_configuration,
4205                                                conversation);
4206                                    } else {
4207                                        callback.error(
4208                                                R.string.joined_an_existing_channel, conversation);
4209                                    }
4210                                }
4211                            });
4212                });
4213    }
4214
4215    public boolean createAdhocConference(
4216            final Account account,
4217            final String name,
4218            final Iterable<Jid> jids,
4219            final UiCallback<Conversation> callback) {
4220        Log.d(
4221                Config.LOGTAG,
4222                account.getJid().asBareJid().toString()
4223                        + ": creating adhoc conference with "
4224                        + jids.toString());
4225        if (account.getStatus() == Account.State.ONLINE) {
4226            try {
4227                String server = findConferenceServer(account);
4228                if (server == null) {
4229                    if (callback != null) {
4230                        callback.error(R.string.no_conference_server_found, null);
4231                    }
4232                    return false;
4233                }
4234                final Jid jid = Jid.of(CryptoHelper.pronounceable(), server, null);
4235                final Conversation conversation =
4236                        findOrCreateConversation(account, jid, true, false, true);
4237                joinMuc(
4238                        conversation,
4239                        new OnConferenceJoined() {
4240                            @Override
4241                            public void onConferenceJoined(final Conversation conversation) {
4242                                final Bundle configuration =
4243                                        IqGenerator.defaultGroupChatConfiguration();
4244                                if (!TextUtils.isEmpty(name)) {
4245                                    configuration.putString("muc#roomconfig_roomname", name);
4246                                }
4247                                pushConferenceConfiguration(
4248                                        conversation,
4249                                        configuration,
4250                                        new OnConfigurationPushed() {
4251                                            @Override
4252                                            public void onPushSucceeded() {
4253                                                for (Jid invite : jids) {
4254                                                    invite(conversation, invite);
4255                                                }
4256                                                for (String resource :
4257                                                        account.getSelfContact()
4258                                                                .getPresences()
4259                                                                .toResourceArray()) {
4260                                                    Jid other =
4261                                                            account.getJid().withResource(resource);
4262                                                    Log.d(
4263                                                            Config.LOGTAG,
4264                                                            account.getJid().asBareJid()
4265                                                                    + ": sending direct invite to "
4266                                                                    + other);
4267                                                    directInvite(conversation, other);
4268                                                }
4269                                                saveConversationAsBookmark(conversation, name);
4270                                                if (callback != null) {
4271                                                    callback.success(conversation);
4272                                                }
4273                                            }
4274
4275                                            @Override
4276                                            public void onPushFailed() {
4277                                                archiveConversation(conversation);
4278                                                if (callback != null) {
4279                                                    callback.error(
4280                                                            R.string.conference_creation_failed,
4281                                                            conversation);
4282                                                }
4283                                            }
4284                                        });
4285                            }
4286                        });
4287                return true;
4288            } catch (IllegalArgumentException e) {
4289                if (callback != null) {
4290                    callback.error(R.string.conference_creation_failed, null);
4291                }
4292                return false;
4293            }
4294        } else {
4295            if (callback != null) {
4296                callback.error(R.string.not_connected_try_again, null);
4297            }
4298            return false;
4299        }
4300    }
4301
4302    public void fetchConferenceConfiguration(final Conversation conversation) {
4303        fetchConferenceConfiguration(conversation, null);
4304    }
4305
4306    public void fetchConferenceConfiguration(
4307            final Conversation conversation, final OnConferenceConfigurationFetched callback) {
4308        final Iq request = mIqGenerator.queryDiscoInfo(conversation.getJid().asBareJid());
4309        final var account = conversation.getAccount();
4310        sendIqPacket(
4311                account,
4312                request,
4313                response -> {
4314                    if (response.getType() == Iq.Type.RESULT) {
4315                        final MucOptions mucOptions = conversation.getMucOptions();
4316                        final Bookmark bookmark = conversation.getBookmark();
4317                        final boolean sameBefore =
4318                                StringUtils.equals(
4319                                        bookmark == null ? null : bookmark.getBookmarkName(),
4320                                        mucOptions.getName());
4321
4322                        if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(response))) {
4323                            Log.d(
4324                                    Config.LOGTAG,
4325                                    account.getJid().asBareJid()
4326                                            + ": muc configuration changed for "
4327                                            + conversation.getJid().asBareJid());
4328                            updateConversation(conversation);
4329                        }
4330
4331                        if (bookmark != null
4332                                && (sameBefore || bookmark.getBookmarkName() == null)) {
4333                            if (bookmark.setBookmarkName(
4334                                    StringUtils.nullOnEmpty(mucOptions.getName()))) {
4335                                createBookmark(account, bookmark);
4336                            }
4337                        }
4338
4339                        if (callback != null) {
4340                            callback.onConferenceConfigurationFetched(conversation);
4341                        }
4342
4343                        updateConversationUi();
4344                    } else if (response.getType() == Iq.Type.TIMEOUT) {
4345                        Log.d(
4346                                Config.LOGTAG,
4347                                account.getJid().asBareJid()
4348                                        + ": received timeout waiting for conference configuration"
4349                                        + " fetch");
4350                    } else {
4351                        if (callback != null) {
4352                            callback.onFetchFailed(conversation, response.getErrorCondition());
4353                        }
4354                    }
4355                });
4356    }
4357
4358    public void pushNodeConfiguration(
4359            Account account,
4360            final String node,
4361            final Bundle options,
4362            final OnConfigurationPushed callback) {
4363        pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
4364    }
4365
4366    public void pushNodeConfiguration(
4367            Account account,
4368            final Jid jid,
4369            final String node,
4370            final Bundle options,
4371            final OnConfigurationPushed callback) {
4372        Log.d(Config.LOGTAG, "pushing node configuration");
4373        sendIqPacket(
4374                account,
4375                mIqGenerator.requestPubsubConfiguration(jid, node),
4376                responseToRequest -> {
4377                    if (responseToRequest.getType() == Iq.Type.RESULT) {
4378                        Element pubsub =
4379                                responseToRequest.findChild(
4380                                        "pubsub", "http://jabber.org/protocol/pubsub#owner");
4381                        Element configuration =
4382                                pubsub == null ? null : pubsub.findChild("configure");
4383                        Element x =
4384                                configuration == null
4385                                        ? null
4386                                        : configuration.findChild("x", Namespace.DATA);
4387                        if (x != null) {
4388                            final Data data = Data.parse(x);
4389                            data.submit(options);
4390                            sendIqPacket(
4391                                    account,
4392                                    mIqGenerator.publishPubsubConfiguration(jid, node, data),
4393                                    responseToPublish -> {
4394                                        if (responseToPublish.getType() == Iq.Type.RESULT
4395                                                && callback != null) {
4396                                            Log.d(
4397                                                    Config.LOGTAG,
4398                                                    account.getJid().asBareJid()
4399                                                            + ": successfully changed node"
4400                                                            + " configuration for node "
4401                                                            + node);
4402                                            callback.onPushSucceeded();
4403                                        } else if (responseToPublish.getType() == Iq.Type.ERROR
4404                                                && callback != null) {
4405                                            callback.onPushFailed();
4406                                        }
4407                                    });
4408                        } else if (callback != null) {
4409                            callback.onPushFailed();
4410                        }
4411                    } else if (responseToRequest.getType() == Iq.Type.ERROR && callback != null) {
4412                        callback.onPushFailed();
4413                    }
4414                });
4415    }
4416
4417    public void pushConferenceConfiguration(
4418            final Conversation conversation,
4419            final Bundle options,
4420            final OnConfigurationPushed callback) {
4421        if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
4422            conversation.setAttribute("accept_non_anonymous", true);
4423            updateConversation(conversation);
4424        }
4425        if (options.containsKey("muc#roomconfig_moderatedroom")) {
4426            final boolean moderated = "1".equals(options.getString("muc#roomconfig_moderatedroom"));
4427            options.putString("members_by_default", moderated ? "0" : "1");
4428        }
4429        if (options.containsKey("muc#roomconfig_allowpm")) {
4430            // ejabberd :-/
4431            final boolean allow = "anyone".equals(options.getString("muc#roomconfig_allowpm"));
4432            options.putString("allow_private_messages", allow ? "1" : "0");
4433            options.putString("allow_private_messages_from_visitors", allow ? "anyone" : "nobody");
4434        }
4435        final var account = conversation.getAccount();
4436        final Iq request = new Iq(Iq.Type.GET);
4437        request.setTo(conversation.getJid().asBareJid());
4438        request.query("http://jabber.org/protocol/muc#owner");
4439        sendIqPacket(
4440                account,
4441                request,
4442                response -> {
4443                    if (response.getType() == Iq.Type.RESULT) {
4444                        final Data data =
4445                                Data.parse(response.query().findChild("x", Namespace.DATA));
4446                        data.submit(options);
4447                        final Iq set = new Iq(Iq.Type.SET);
4448                        set.setTo(conversation.getJid().asBareJid());
4449                        set.query("http://jabber.org/protocol/muc#owner").addChild(data);
4450                        sendIqPacket(
4451                                account,
4452                                set,
4453                                packet -> {
4454                                    if (callback != null) {
4455                                        if (packet.getType() == Iq.Type.RESULT) {
4456                                            callback.onPushSucceeded();
4457                                        } else {
4458                                            Log.d(Config.LOGTAG, "failed: " + packet.toString());
4459                                            callback.onPushFailed();
4460                                        }
4461                                    }
4462                                });
4463                    } else {
4464                        if (callback != null) {
4465                            callback.onPushFailed();
4466                        }
4467                    }
4468                });
4469    }
4470
4471    public void pushSubjectToConference(final Conversation conference, final String subject) {
4472        final var packet =
4473                this.getMessageGenerator()
4474                        .conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
4475        this.sendMessagePacket(conference.getAccount(), packet);
4476    }
4477
4478    public void changeAffiliationInConference(
4479            final Conversation conference,
4480            Jid user,
4481            final MucOptions.Affiliation affiliation,
4482            final OnAffiliationChanged callback) {
4483        final Jid jid = user.asBareJid();
4484        final Iq request =
4485                this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
4486        sendIqPacket(
4487                conference.getAccount(),
4488                request,
4489                (response) -> {
4490                    if (response.getType() == Iq.Type.RESULT) {
4491                        final var mucOptions = conference.getMucOptions();
4492                        mucOptions.changeAffiliation(jid, affiliation);
4493                        getAvatarService().clear(mucOptions);
4494                        if (callback != null) {
4495                            callback.onAffiliationChangedSuccessful(jid);
4496                        } else {
4497                            Log.d(
4498                                    Config.LOGTAG,
4499                                    "changed affiliation of " + user + " to " + affiliation);
4500                        }
4501                    } else if (callback != null) {
4502                        callback.onAffiliationChangeFailed(
4503                                jid, R.string.could_not_change_affiliation);
4504                    } else {
4505                        Log.d(Config.LOGTAG, "unable to change affiliation");
4506                    }
4507                });
4508    }
4509
4510    public void changeRoleInConference(
4511            final Conversation conference, final String nick, MucOptions.Role role) {
4512        final var account = conference.getAccount();
4513        final Iq request = this.mIqGenerator.changeRole(conference, nick, role.toString());
4514        sendIqPacket(
4515                account,
4516                request,
4517                (packet) -> {
4518                    if (packet.getType() != Iq.Type.RESULT) {
4519                        Log.d(
4520                                Config.LOGTAG,
4521                                account.getJid().asBareJid() + " unable to change role of " + nick);
4522                    }
4523                });
4524    }
4525
4526    public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
4527        final Iq request = new Iq(Iq.Type.SET);
4528        request.setTo(conversation.getJid().asBareJid());
4529        request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
4530        sendIqPacket(
4531                conversation.getAccount(),
4532                request,
4533                response -> {
4534                    if (response.getType() == Iq.Type.RESULT) {
4535                        if (callback != null) {
4536                            callback.onRoomDestroySucceeded();
4537                        }
4538                    } else if (response.getType() == Iq.Type.ERROR) {
4539                        if (callback != null) {
4540                            callback.onRoomDestroyFailed();
4541                        }
4542                    }
4543                });
4544    }
4545
4546    private void disconnect(final Account account, boolean force) {
4547        final XmppConnection connection = account.getXmppConnection();
4548        if (connection == null) {
4549            return;
4550        }
4551        if (!force) {
4552            final List<Conversation> conversations = getConversations();
4553            for (Conversation conversation : conversations) {
4554                if (conversation.getAccount() == account) {
4555                    if (conversation.getMode() == Conversation.MODE_MULTI) {
4556                        leaveMuc(conversation, true);
4557                    }
4558                }
4559            }
4560            sendOfflinePresence(account);
4561        }
4562        connection.disconnect(force);
4563    }
4564
4565    @Override
4566    public IBinder onBind(Intent intent) {
4567        return mBinder;
4568    }
4569
4570    public void updateMessage(Message message) {
4571        updateMessage(message, true);
4572    }
4573
4574    public void updateMessage(Message message, boolean includeBody) {
4575        databaseBackend.updateMessage(message, includeBody);
4576        updateConversationUi();
4577    }
4578
4579    public void createMessageAsync(final Message message) {
4580        mDatabaseWriterExecutor.execute(() -> databaseBackend.createMessage(message));
4581    }
4582
4583    public void updateMessage(Message message, String uuid) {
4584        if (!databaseBackend.updateMessage(message, uuid)) {
4585            Log.e(Config.LOGTAG, "error updated message in DB after edit");
4586        }
4587        updateConversationUi();
4588    }
4589
4590    public void syncDirtyContacts(Account account) {
4591        for (Contact contact : account.getRoster().getContacts()) {
4592            if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
4593                pushContactToServer(contact);
4594            }
4595            if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
4596                deleteContactOnServer(contact);
4597            }
4598        }
4599    }
4600
4601    public void createContact(final Contact contact, final boolean autoGrant) {
4602        createContact(contact, autoGrant, null);
4603    }
4604
4605    public void createContact(
4606            final Contact contact, final boolean autoGrant, final String preAuth) {
4607        if (autoGrant) {
4608            contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
4609            contact.setOption(Contact.Options.ASKING);
4610        }
4611        pushContactToServer(contact, preAuth);
4612    }
4613
4614    public void pushContactToServer(final Contact contact) {
4615        pushContactToServer(contact, null);
4616    }
4617
4618    private void pushContactToServer(final Contact contact, final String preAuth) {
4619        contact.resetOption(Contact.Options.DIRTY_DELETE);
4620        contact.setOption(Contact.Options.DIRTY_PUSH);
4621        final Account account = contact.getAccount();
4622        if (account.getStatus() == Account.State.ONLINE) {
4623            final boolean ask = contact.getOption(Contact.Options.ASKING);
4624            final boolean sendUpdates =
4625                    contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
4626                            && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
4627            final Iq iq = new Iq(Iq.Type.SET);
4628            iq.query(Namespace.ROSTER).addChild(contact.asElement());
4629            account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
4630            if (sendUpdates) {
4631                sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
4632            }
4633            if (ask) {
4634                sendPresencePacket(
4635                        account, mPresenceGenerator.requestPresenceUpdatesFrom(contact, preAuth));
4636            }
4637        } else {
4638            syncRoster(contact.getAccount());
4639        }
4640    }
4641
4642    public void publishMucAvatar(
4643            final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
4644        new Thread(
4645                        () -> {
4646                            final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
4647                            final int size = Config.AVATAR_SIZE;
4648                            final Avatar avatar =
4649                                    getFileBackend().getPepAvatar(image, size, format);
4650                            if (avatar != null) {
4651                                if (!getFileBackend().save(avatar)) {
4652                                    callback.onAvatarPublicationFailed(
4653                                            R.string.error_saving_avatar);
4654                                    return;
4655                                }
4656                                avatar.owner = conversation.getJid().asBareJid();
4657                                publishMucAvatar(conversation, avatar, callback);
4658                            } else {
4659                                callback.onAvatarPublicationFailed(
4660                                        R.string.error_publish_avatar_converting);
4661                            }
4662                        })
4663                .start();
4664    }
4665
4666    public void publishAvatarAsync(
4667            final Account account,
4668            final Uri image,
4669            final boolean open,
4670            final OnAvatarPublication callback) {
4671        new Thread(() -> publishAvatar(account, image, open, callback)).start();
4672    }
4673
4674    private void publishAvatar(
4675            final Account account,
4676            final Uri image,
4677            final boolean open,
4678            final OnAvatarPublication callback) {
4679        final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
4680        final int size = Config.AVATAR_SIZE;
4681        final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
4682        if (avatar != null) {
4683            if (!getFileBackend().save(avatar)) {
4684                Log.d(Config.LOGTAG, "unable to save vcard");
4685                callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
4686                return;
4687            }
4688            publishAvatar(account, avatar, open, callback);
4689        } else {
4690            callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
4691        }
4692    }
4693
4694    private void publishMucAvatar(
4695            Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
4696        final var account = conversation.getAccount();
4697        final Iq retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
4698        sendIqPacket(
4699                account,
4700                retrieve,
4701                (response) -> {
4702                    boolean itemNotFound =
4703                            response.getType() == Iq.Type.ERROR
4704                                    && response.hasChild("error")
4705                                    && response.findChild("error").hasChild("item-not-found");
4706                    if (response.getType() == Iq.Type.RESULT || itemNotFound) {
4707                        Element vcard = response.findChild("vCard", "vcard-temp");
4708                        if (vcard == null) {
4709                            vcard = new Element("vCard", "vcard-temp");
4710                        }
4711                        Element photo = vcard.findChild("PHOTO");
4712                        if (photo == null) {
4713                            photo = vcard.addChild("PHOTO");
4714                        }
4715                        photo.clearChildren();
4716                        photo.addChild("TYPE").setContent(avatar.type);
4717                        photo.addChild("BINVAL").setContent(avatar.image);
4718                        final Iq publication = new Iq(Iq.Type.SET);
4719                        publication.setTo(conversation.getJid().asBareJid());
4720                        publication.addChild(vcard);
4721                        sendIqPacket(
4722                                account,
4723                                publication,
4724                                (publicationResponse) -> {
4725                                    if (publicationResponse.getType() == Iq.Type.RESULT) {
4726                                        callback.onAvatarPublicationSucceeded();
4727                                    } else {
4728                                        Log.d(
4729                                                Config.LOGTAG,
4730                                                "failed to publish vcard "
4731                                                        + publicationResponse.getErrorCondition());
4732                                        callback.onAvatarPublicationFailed(
4733                                                R.string.error_publish_avatar_server_reject);
4734                                    }
4735                                });
4736                    } else {
4737                        Log.d(Config.LOGTAG, "failed to request vcard " + response);
4738                        callback.onAvatarPublicationFailed(
4739                                R.string.error_publish_avatar_no_server_support);
4740                    }
4741                });
4742    }
4743
4744    public void publishAvatar(
4745            final Account account,
4746            final Avatar avatar,
4747            final boolean open,
4748            final OnAvatarPublication callback) {
4749        final Bundle options;
4750        if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
4751            options = open ? PublishOptions.openAccess() : PublishOptions.presenceAccess();
4752        } else {
4753            options = null;
4754        }
4755        publishAvatar(account, avatar, options, true, callback);
4756    }
4757
4758    public void publishAvatar(
4759            Account account,
4760            final Avatar avatar,
4761            final Bundle options,
4762            final boolean retry,
4763            final OnAvatarPublication callback) {
4764        Log.d(
4765                Config.LOGTAG,
4766                account.getJid().asBareJid() + ": publishing avatar. options=" + options);
4767        final Iq packet = this.mIqGenerator.publishAvatar(avatar, options);
4768        this.sendIqPacket(
4769                account,
4770                packet,
4771                result -> {
4772                    if (result.getType() == Iq.Type.RESULT) {
4773                        publishAvatarMetadata(account, avatar, options, true, callback);
4774                    } else if (retry && PublishOptions.preconditionNotMet(result)) {
4775                        pushNodeConfiguration(
4776                                account,
4777                                Namespace.AVATAR_DATA,
4778                                options,
4779                                new OnConfigurationPushed() {
4780                                    @Override
4781                                    public void onPushSucceeded() {
4782                                        Log.d(
4783                                                Config.LOGTAG,
4784                                                account.getJid().asBareJid()
4785                                                        + ": changed node configuration for avatar"
4786                                                        + " node");
4787                                        publishAvatar(account, avatar, options, false, callback);
4788                                    }
4789
4790                                    @Override
4791                                    public void onPushFailed() {
4792                                        Log.d(
4793                                                Config.LOGTAG,
4794                                                account.getJid().asBareJid()
4795                                                        + ": unable to change node configuration"
4796                                                        + " for avatar node");
4797                                        publishAvatar(account, avatar, null, false, callback);
4798                                    }
4799                                });
4800                    } else {
4801                        Element error = result.findChild("error");
4802                        Log.d(
4803                                Config.LOGTAG,
4804                                account.getJid().asBareJid()
4805                                        + ": server rejected avatar "
4806                                        + (avatar.size / 1024)
4807                                        + "KiB "
4808                                        + (error != null ? error.toString() : ""));
4809                        if (callback != null) {
4810                            callback.onAvatarPublicationFailed(
4811                                    R.string.error_publish_avatar_server_reject);
4812                        }
4813                    }
4814                });
4815    }
4816
4817    public void publishAvatarMetadata(
4818            Account account,
4819            final Avatar avatar,
4820            final Bundle options,
4821            final boolean retry,
4822            final OnAvatarPublication callback) {
4823        final Iq packet =
4824                XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
4825        sendIqPacket(
4826                account,
4827                packet,
4828                result -> {
4829                    if (result.getType() == Iq.Type.RESULT) {
4830                        if (account.setAvatar(avatar.getFilename())) {
4831                            getAvatarService().clear(account);
4832                            databaseBackend.updateAccount(account);
4833                            notifyAccountAvatarHasChanged(account);
4834                        }
4835                        Log.d(
4836                                Config.LOGTAG,
4837                                account.getJid().asBareJid()
4838                                        + ": published avatar "
4839                                        + (avatar.size / 1024)
4840                                        + "KiB");
4841                        if (callback != null) {
4842                            callback.onAvatarPublicationSucceeded();
4843                        }
4844                    } else if (retry && PublishOptions.preconditionNotMet(result)) {
4845                        pushNodeConfiguration(
4846                                account,
4847                                Namespace.AVATAR_METADATA,
4848                                options,
4849                                new OnConfigurationPushed() {
4850                                    @Override
4851                                    public void onPushSucceeded() {
4852                                        Log.d(
4853                                                Config.LOGTAG,
4854                                                account.getJid().asBareJid()
4855                                                        + ": changed node configuration for avatar"
4856                                                        + " meta data node");
4857                                        publishAvatarMetadata(
4858                                                account, avatar, options, false, callback);
4859                                    }
4860
4861                                    @Override
4862                                    public void onPushFailed() {
4863                                        Log.d(
4864                                                Config.LOGTAG,
4865                                                account.getJid().asBareJid()
4866                                                        + ": unable to change node configuration"
4867                                                        + " for avatar meta data node");
4868                                        publishAvatarMetadata(
4869                                                account, avatar, null, false, callback);
4870                                    }
4871                                });
4872                    } else {
4873                        if (callback != null) {
4874                            callback.onAvatarPublicationFailed(
4875                                    R.string.error_publish_avatar_server_reject);
4876                        }
4877                    }
4878                });
4879    }
4880
4881    public void republishAvatarIfNeeded(final Account account) {
4882        if (account.getAxolotlService().isPepBroken()) {
4883            Log.d(
4884                    Config.LOGTAG,
4885                    account.getJid().asBareJid()
4886                            + ": skipping republication of avatar because pep is broken");
4887            return;
4888        }
4889        final Iq packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4890        this.sendIqPacket(
4891                account,
4892                packet,
4893                new Consumer<Iq>() {
4894
4895                    private Avatar parseAvatar(Iq packet) {
4896                        Element pubsub =
4897                                packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
4898                        if (pubsub != null) {
4899                            Element items = pubsub.findChild("items");
4900                            if (items != null) {
4901                                return Avatar.parseMetadata(items);
4902                            }
4903                        }
4904                        return null;
4905                    }
4906
4907                    private boolean errorIsItemNotFound(Iq packet) {
4908                        Element error = packet.findChild("error");
4909                        return packet.getType() == Iq.Type.ERROR
4910                                && error != null
4911                                && error.hasChild("item-not-found");
4912                    }
4913
4914                    @Override
4915                    public void accept(final Iq packet) {
4916                        if (packet.getType() == Iq.Type.RESULT || errorIsItemNotFound(packet)) {
4917                            final Avatar serverAvatar = parseAvatar(packet);
4918                            if (serverAvatar == null && account.getAvatar() != null) {
4919                                final Avatar avatar =
4920                                        fileBackend.getStoredPepAvatar(account.getAvatar());
4921                                if (avatar != null) {
4922                                    Log.d(
4923                                            Config.LOGTAG,
4924                                            account.getJid().asBareJid()
4925                                                    + ": avatar on server was null. republishing");
4926                                    // publishing as 'open' - old server (that requires
4927                                    // republication) likely doesn't support access models anyway
4928                                    publishAvatar(
4929                                            account,
4930                                            fileBackend.getStoredPepAvatar(account.getAvatar()),
4931                                            true,
4932                                            null);
4933                                } else {
4934                                    Log.e(
4935                                            Config.LOGTAG,
4936                                            account.getJid().asBareJid()
4937                                                    + ": error rereading avatar");
4938                                }
4939                            }
4940                        }
4941                    }
4942                });
4943    }
4944
4945    public void cancelAvatarFetches(final Account account) {
4946        synchronized (mInProgressAvatarFetches) {
4947            for (final Iterator<String> iterator = mInProgressAvatarFetches.iterator();
4948                    iterator.hasNext(); ) {
4949                final String KEY = iterator.next();
4950                if (KEY.startsWith(account.getJid().asBareJid() + "_")) {
4951                    iterator.remove();
4952                }
4953            }
4954        }
4955    }
4956
4957    public void fetchAvatar(Account account, Avatar avatar) {
4958        fetchAvatar(account, avatar, null);
4959    }
4960
4961    public void fetchAvatar(
4962            Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4963        final String KEY = generateFetchKey(account, avatar);
4964        synchronized (this.mInProgressAvatarFetches) {
4965            if (mInProgressAvatarFetches.add(KEY)) {
4966                switch (avatar.origin) {
4967                    case PEP:
4968                        this.mInProgressAvatarFetches.add(KEY);
4969                        fetchAvatarPep(account, avatar, callback);
4970                        break;
4971                    case VCARD:
4972                        this.mInProgressAvatarFetches.add(KEY);
4973                        fetchAvatarVcard(account, avatar, callback);
4974                        break;
4975                }
4976            } else if (avatar.origin == Avatar.Origin.PEP) {
4977                mOmittedPepAvatarFetches.add(KEY);
4978            } else {
4979                Log.d(
4980                        Config.LOGTAG,
4981                        account.getJid().asBareJid()
4982                                + ": already fetching "
4983                                + avatar.origin
4984                                + " avatar for "
4985                                + avatar.owner);
4986            }
4987        }
4988    }
4989
4990    private void fetchAvatarPep(
4991            final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4992        final Iq packet = this.mIqGenerator.retrievePepAvatar(avatar);
4993        sendIqPacket(
4994                account,
4995                packet,
4996                (result) -> {
4997                    synchronized (mInProgressAvatarFetches) {
4998                        mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
4999                    }
5000                    final String ERROR =
5001                            account.getJid().asBareJid()
5002                                    + ": fetching avatar for "
5003                                    + avatar.owner
5004                                    + " failed ";
5005                    if (result.getType() == Iq.Type.RESULT) {
5006                        avatar.image = IqParser.avatarData(result);
5007                        if (avatar.image != null) {
5008                            if (getFileBackend().save(avatar)) {
5009                                if (account.getJid().asBareJid().equals(avatar.owner)) {
5010                                    if (account.setAvatar(avatar.getFilename())) {
5011                                        databaseBackend.updateAccount(account);
5012                                    }
5013                                    getAvatarService().clear(account);
5014                                    updateConversationUi();
5015                                    updateAccountUi();
5016                                } else {
5017                                    final Contact contact =
5018                                            account.getRoster().getContact(avatar.owner);
5019                                    contact.setAvatar(avatar);
5020                                    syncRoster(account);
5021                                    getAvatarService().clear(contact);
5022                                    updateConversationUi();
5023                                    updateRosterUi();
5024                                }
5025                                if (callback != null) {
5026                                    callback.success(avatar);
5027                                }
5028                                Log.d(
5029                                        Config.LOGTAG,
5030                                        account.getJid().asBareJid()
5031                                                + ": successfully fetched pep avatar for "
5032                                                + avatar.owner);
5033                                return;
5034                            }
5035                        } else {
5036
5037                            Log.d(Config.LOGTAG, ERROR + "(parsing error)");
5038                        }
5039                    } else {
5040                        Element error = result.findChild("error");
5041                        if (error == null) {
5042                            Log.d(Config.LOGTAG, ERROR + "(server error)");
5043                        } else {
5044                            Log.d(Config.LOGTAG, ERROR + error.toString());
5045                        }
5046                    }
5047                    if (callback != null) {
5048                        callback.error(0, null);
5049                    }
5050                });
5051    }
5052
5053    private void fetchAvatarVcard(
5054            final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
5055        final Iq packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
5056        this.sendIqPacket(
5057                account,
5058                packet,
5059                response -> {
5060                    final boolean previouslyOmittedPepFetch;
5061                    synchronized (mInProgressAvatarFetches) {
5062                        final String KEY = generateFetchKey(account, avatar);
5063                        mInProgressAvatarFetches.remove(KEY);
5064                        previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
5065                    }
5066                    if (response.getType() == Iq.Type.RESULT) {
5067                        Element vCard = response.findChild("vCard", "vcard-temp");
5068                        Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
5069                        String image = photo != null ? photo.findChildContent("BINVAL") : null;
5070                        if (image != null) {
5071                            avatar.image = image;
5072                            if (getFileBackend().save(avatar)) {
5073                                Log.d(
5074                                        Config.LOGTAG,
5075                                        account.getJid().asBareJid()
5076                                                + ": successfully fetched vCard avatar for "
5077                                                + avatar.owner
5078                                                + " omittedPep="
5079                                                + previouslyOmittedPepFetch);
5080                                if (avatar.owner.isBareJid()) {
5081                                    if (account.getJid().asBareJid().equals(avatar.owner)
5082                                            && account.getAvatar() == null) {
5083                                        Log.d(
5084                                                Config.LOGTAG,
5085                                                account.getJid().asBareJid()
5086                                                        + ": had no avatar. replacing with vcard");
5087                                        account.setAvatar(avatar.getFilename());
5088                                        databaseBackend.updateAccount(account);
5089                                        getAvatarService().clear(account);
5090                                        updateAccountUi();
5091                                    } else {
5092                                        final Contact contact =
5093                                                account.getRoster().getContact(avatar.owner);
5094                                        contact.setAvatar(avatar, previouslyOmittedPepFetch);
5095                                        syncRoster(account);
5096                                        getAvatarService().clear(contact);
5097                                        updateRosterUi();
5098                                    }
5099                                    updateConversationUi();
5100                                } else {
5101                                    Conversation conversation =
5102                                            find(account, avatar.owner.asBareJid());
5103                                    if (conversation != null
5104                                            && conversation.getMode() == Conversation.MODE_MULTI) {
5105                                        MucOptions.User user =
5106                                                conversation
5107                                                        .getMucOptions()
5108                                                        .findUserByFullJid(avatar.owner);
5109                                        if (user != null) {
5110                                            if (user.setAvatar(avatar)) {
5111                                                getAvatarService().clear(user);
5112                                                updateConversationUi();
5113                                                updateMucRosterUi();
5114                                            }
5115                                            if (user.getRealJid() != null) {
5116                                                Contact contact =
5117                                                        account.getRoster()
5118                                                                .getContact(user.getRealJid());
5119                                                contact.setAvatar(avatar);
5120                                                syncRoster(account);
5121                                                getAvatarService().clear(contact);
5122                                                updateRosterUi();
5123                                            }
5124                                        }
5125                                    }
5126                                }
5127                            }
5128                        }
5129                    }
5130                });
5131    }
5132
5133    public void checkForAvatar(final Account account, final UiCallback<Avatar> callback) {
5134        final Iq packet = this.mIqGenerator.retrieveAvatarMetaData(null);
5135        this.sendIqPacket(
5136                account,
5137                packet,
5138                response -> {
5139                    if (response.getType() == Iq.Type.RESULT) {
5140                        Element pubsub =
5141                                response.findChild("pubsub", "http://jabber.org/protocol/pubsub");
5142                        if (pubsub != null) {
5143                            Element items = pubsub.findChild("items");
5144                            if (items != null) {
5145                                Avatar avatar = Avatar.parseMetadata(items);
5146                                if (avatar != null) {
5147                                    avatar.owner = account.getJid().asBareJid();
5148                                    if (fileBackend.isAvatarCached(avatar)) {
5149                                        if (account.setAvatar(avatar.getFilename())) {
5150                                            databaseBackend.updateAccount(account);
5151                                        }
5152                                        getAvatarService().clear(account);
5153                                        callback.success(avatar);
5154                                    } else {
5155                                        fetchAvatarPep(account, avatar, callback);
5156                                    }
5157                                    return;
5158                                }
5159                            }
5160                        }
5161                    }
5162                    callback.error(0, null);
5163                });
5164    }
5165
5166    public void notifyAccountAvatarHasChanged(final Account account) {
5167        final XmppConnection connection = account.getXmppConnection();
5168        if (connection != null && connection.getFeatures().bookmarksConversion()) {
5169            Log.d(
5170                    Config.LOGTAG,
5171                    account.getJid().asBareJid()
5172                            + ": avatar changed. resending presence to online group chats");
5173            for (Conversation conversation : conversations) {
5174                if (conversation.getAccount() == account
5175                        && conversation.getMode() == Conversational.MODE_MULTI) {
5176                    final MucOptions mucOptions = conversation.getMucOptions();
5177                    if (mucOptions.online()) {
5178                        final var packet =
5179                                mPresenceGenerator.selfPresence(
5180                                        account, Presence.Status.ONLINE, mucOptions.nonanonymous());
5181                        packet.setTo(mucOptions.getSelf().getFullJid());
5182                        connection.sendPresencePacket(packet);
5183                    }
5184                }
5185            }
5186        }
5187    }
5188
5189    public void deleteContactOnServer(Contact contact) {
5190        contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
5191        contact.resetOption(Contact.Options.DIRTY_PUSH);
5192        contact.setOption(Contact.Options.DIRTY_DELETE);
5193        Account account = contact.getAccount();
5194        if (account.getStatus() == Account.State.ONLINE) {
5195            final Iq iq = new Iq(Iq.Type.SET);
5196            Element item = iq.query(Namespace.ROSTER).addChild("item");
5197            item.setAttribute("jid", contact.getJid());
5198            item.setAttribute("subscription", "remove");
5199            account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
5200        }
5201    }
5202
5203    public void updateConversation(final Conversation conversation) {
5204        mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
5205    }
5206
5207    private void reconnectAccount(
5208            final Account account, final boolean force, final boolean interactive) {
5209        synchronized (account) {
5210            final XmppConnection existingConnection = account.getXmppConnection();
5211            final XmppConnection connection;
5212            if (existingConnection != null) {
5213                connection = existingConnection;
5214            } else if (account.isConnectionEnabled()) {
5215                connection = createConnection(account);
5216                account.setXmppConnection(connection);
5217            } else {
5218                return;
5219            }
5220            final boolean hasInternet = hasInternetConnection();
5221            if (account.isConnectionEnabled() && hasInternet) {
5222                if (!force) {
5223                    disconnect(account, false);
5224                }
5225                Thread thread = new Thread(connection);
5226                connection.setInteractive(interactive);
5227                connection.prepareNewConnection();
5228                connection.interrupt();
5229                thread.start();
5230                scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
5231            } else {
5232                disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
5233                account.getRoster().clearPresences();
5234                connection.resetEverything();
5235                final AxolotlService axolotlService = account.getAxolotlService();
5236                if (axolotlService != null) {
5237                    axolotlService.resetBrokenness();
5238                }
5239                if (!hasInternet) {
5240                    account.setStatus(Account.State.NO_INTERNET);
5241                }
5242            }
5243        }
5244    }
5245
5246    public void reconnectAccountInBackground(final Account account) {
5247        new Thread(() -> reconnectAccount(account, false, true)).start();
5248    }
5249
5250    public void invite(final Conversation conversation, final Jid contact) {
5251        Log.d(
5252                Config.LOGTAG,
5253                conversation.getAccount().getJid().asBareJid()
5254                        + ": inviting "
5255                        + contact
5256                        + " to "
5257                        + conversation.getJid().asBareJid());
5258        final MucOptions.User user =
5259                conversation.getMucOptions().findUserByRealJid(contact.asBareJid());
5260        if (user == null || user.getAffiliation() == MucOptions.Affiliation.OUTCAST) {
5261            changeAffiliationInConference(conversation, contact, MucOptions.Affiliation.NONE, null);
5262        }
5263        final var packet = mMessageGenerator.invite(conversation, contact);
5264        sendMessagePacket(conversation.getAccount(), packet);
5265    }
5266
5267    public void directInvite(Conversation conversation, Jid jid) {
5268        final var packet = mMessageGenerator.directInvite(conversation, jid);
5269        sendMessagePacket(conversation.getAccount(), packet);
5270    }
5271
5272    public void resetSendingToWaiting(Account account) {
5273        for (Conversation conversation : getConversations()) {
5274            if (conversation.getAccount() == account) {
5275                conversation.findUnsentTextMessages(
5276                        message -> markMessage(message, Message.STATUS_WAITING));
5277            }
5278        }
5279    }
5280
5281    public Message markMessage(
5282            final Account account, final Jid recipient, final String uuid, final int status) {
5283        return markMessage(account, recipient, uuid, status, null);
5284    }
5285
5286    public Message markMessage(
5287            final Account account,
5288            final Jid recipient,
5289            final String uuid,
5290            final int status,
5291            String errorMessage) {
5292        if (uuid == null) {
5293            return null;
5294        }
5295        for (Conversation conversation : getConversations()) {
5296            if (conversation.getJid().asBareJid().equals(recipient)
5297                    && conversation.getAccount() == account) {
5298                final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
5299                if (message != null) {
5300                    markMessage(message, status, errorMessage);
5301                }
5302                return message;
5303            }
5304        }
5305        return null;
5306    }
5307
5308    public boolean markMessage(
5309            final Conversation conversation,
5310            final String uuid,
5311            final int status,
5312            final String serverMessageId) {
5313        return markMessage(conversation, uuid, status, serverMessageId, null);
5314    }
5315
5316    public boolean markMessage(
5317            final Conversation conversation,
5318            final String uuid,
5319            final int status,
5320            final String serverMessageId,
5321            final LocalizedContent body) {
5322        if (uuid == null) {
5323            return false;
5324        } else {
5325            final Message message = conversation.findSentMessageWithUuid(uuid);
5326            if (message != null) {
5327                if (message.getServerMsgId() == null) {
5328                    message.setServerMsgId(serverMessageId);
5329                }
5330                if (message.getEncryption() == Message.ENCRYPTION_NONE
5331                        && message.isTypeText()
5332                        && isBodyModified(message, body)) {
5333                    message.setBody(body.content);
5334                    if (body.count > 1) {
5335                        message.setBodyLanguage(body.language);
5336                    }
5337                    markMessage(message, status, null, true);
5338                } else {
5339                    markMessage(message, status);
5340                }
5341                return true;
5342            } else {
5343                return false;
5344            }
5345        }
5346    }
5347
5348    private static boolean isBodyModified(final Message message, final LocalizedContent body) {
5349        if (body == null || body.content == null) {
5350            return false;
5351        }
5352        return !body.content.equals(message.getBody());
5353    }
5354
5355    public void markMessage(Message message, int status) {
5356        markMessage(message, status, null);
5357    }
5358
5359    public void markMessage(final Message message, final int status, final String errorMessage) {
5360        markMessage(message, status, errorMessage, false);
5361    }
5362
5363    public void markMessage(
5364            final Message message,
5365            final int status,
5366            final String errorMessage,
5367            final boolean includeBody) {
5368        final int oldStatus = message.getStatus();
5369        if (status == Message.STATUS_SEND_FAILED
5370                && (oldStatus == Message.STATUS_SEND_RECEIVED
5371                        || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
5372            return;
5373        }
5374        if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
5375            return;
5376        }
5377        message.setErrorMessage(errorMessage);
5378        message.setStatus(status);
5379        databaseBackend.updateMessage(message, includeBody);
5380        updateConversationUi();
5381        if (oldStatus != status && status == Message.STATUS_SEND_FAILED) {
5382            mNotificationService.pushFailedDelivery(message);
5383        }
5384    }
5385
5386    private SharedPreferences getPreferences() {
5387        return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
5388    }
5389
5390    public long getAutomaticMessageDeletionDate() {
5391        final long timeout =
5392                getLongPreference(
5393                        AppSettings.AUTOMATIC_MESSAGE_DELETION,
5394                        R.integer.automatic_message_deletion);
5395        return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
5396    }
5397
5398    public long getLongPreference(String name, @IntegerRes int res) {
5399        long defaultValue = getResources().getInteger(res);
5400        try {
5401            return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
5402        } catch (NumberFormatException e) {
5403            return defaultValue;
5404        }
5405    }
5406
5407    public boolean getBooleanPreference(String name, @BoolRes int res) {
5408        return getPreferences().getBoolean(name, getResources().getBoolean(res));
5409    }
5410
5411    public boolean confirmMessages() {
5412        return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
5413    }
5414
5415    public boolean allowMessageCorrection() {
5416        return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
5417    }
5418
5419    public boolean sendChatStates() {
5420        return getBooleanPreference("chat_states", R.bool.chat_states);
5421    }
5422
5423    public boolean useTorToConnect() {
5424        return QuickConversationsService.isConversations()
5425                && getBooleanPreference("use_tor", R.bool.use_tor);
5426    }
5427
5428    public boolean showExtendedConnectionOptions() {
5429        return QuickConversationsService.isConversations()
5430                && getBooleanPreference(
5431                        AppSettings.SHOW_CONNECTION_OPTIONS, R.bool.show_connection_options);
5432    }
5433
5434    public boolean broadcastLastActivity() {
5435        return getBooleanPreference(AppSettings.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
5436    }
5437
5438    public int unreadCount() {
5439        int count = 0;
5440        for (Conversation conversation : getConversations()) {
5441            count += conversation.unreadCount();
5442        }
5443        return count;
5444    }
5445
5446    private <T> List<T> threadSafeList(Set<T> set) {
5447        synchronized (LISTENER_LOCK) {
5448            return set.isEmpty() ? Collections.emptyList() : new ArrayList<>(set);
5449        }
5450    }
5451
5452    public void showErrorToastInUi(int resId) {
5453        for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
5454            listener.onShowErrorToast(resId);
5455        }
5456    }
5457
5458    public void updateConversationUi() {
5459        for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
5460            listener.onConversationUpdate();
5461        }
5462    }
5463
5464    public void notifyJingleRtpConnectionUpdate(
5465            final Account account,
5466            final Jid with,
5467            final String sessionId,
5468            final RtpEndUserState state) {
5469        for (OnJingleRtpConnectionUpdate listener :
5470                threadSafeList(this.onJingleRtpConnectionUpdate)) {
5471            listener.onJingleRtpConnectionUpdate(account, with, sessionId, state);
5472        }
5473    }
5474
5475    public void notifyJingleRtpConnectionUpdate(
5476            CallIntegration.AudioDevice selectedAudioDevice,
5477            Set<CallIntegration.AudioDevice> availableAudioDevices) {
5478        for (OnJingleRtpConnectionUpdate listener :
5479                threadSafeList(this.onJingleRtpConnectionUpdate)) {
5480            listener.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
5481        }
5482    }
5483
5484    public void updateAccountUi() {
5485        for (final OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
5486            listener.onAccountUpdate();
5487        }
5488    }
5489
5490    public void updateRosterUi() {
5491        for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
5492            listener.onRosterUpdate();
5493        }
5494    }
5495
5496    public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
5497        if (mOnCaptchaRequested.size() > 0) {
5498            DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
5499            Bitmap scaled =
5500                    Bitmap.createScaledBitmap(
5501                            captcha,
5502                            (int) (captcha.getWidth() * metrics.scaledDensity),
5503                            (int) (captcha.getHeight() * metrics.scaledDensity),
5504                            false);
5505            for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
5506                listener.onCaptchaRequested(account, id, data, scaled);
5507            }
5508            return true;
5509        }
5510        return false;
5511    }
5512
5513    public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
5514        for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
5515            listener.OnUpdateBlocklist(status);
5516        }
5517    }
5518
5519    public void updateMucRosterUi() {
5520        for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
5521            listener.onMucRosterUpdate();
5522        }
5523    }
5524
5525    public void keyStatusUpdated(AxolotlService.FetchStatus report) {
5526        for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
5527            listener.onKeyStatusUpdated(report);
5528        }
5529    }
5530
5531    public Account findAccountByJid(final Jid jid) {
5532        for (final Account account : this.accounts) {
5533            if (account.getJid().asBareJid().equals(jid.asBareJid())) {
5534                return account;
5535            }
5536        }
5537        return null;
5538    }
5539
5540    public Account findAccountByUuid(final String uuid) {
5541        for (Account account : this.accounts) {
5542            if (account.getUuid().equals(uuid)) {
5543                return account;
5544            }
5545        }
5546        return null;
5547    }
5548
5549    public Conversation findConversationByUuid(String uuid) {
5550        for (Conversation conversation : getConversations()) {
5551            if (conversation.getUuid().equals(uuid)) {
5552                return conversation;
5553            }
5554        }
5555        return null;
5556    }
5557
5558    public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
5559        List<Conversation> findings = new ArrayList<>();
5560        for (Conversation c : getConversations()) {
5561            if (c.getAccount().isEnabled()
5562                    && c.getJid().asBareJid().equals(xmppUri.getJid())
5563                    && ((c.getMode() == Conversational.MODE_MULTI)
5564                            == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
5565                findings.add(c);
5566            }
5567        }
5568        return findings.size() == 1 ? findings.get(0) : null;
5569    }
5570
5571    public boolean markRead(final Conversation conversation, boolean dismiss) {
5572        return markRead(conversation, null, dismiss).size() > 0;
5573    }
5574
5575    public void markRead(final Conversation conversation) {
5576        markRead(conversation, null, true);
5577    }
5578
5579    public List<Message> markRead(
5580            final Conversation conversation, String upToUuid, boolean dismiss) {
5581        if (dismiss) {
5582            mNotificationService.clear(conversation);
5583        }
5584        final List<Message> readMessages = conversation.markRead(upToUuid);
5585        if (readMessages.size() > 0) {
5586            Runnable runnable =
5587                    () -> {
5588                        for (Message message : readMessages) {
5589                            databaseBackend.updateMessage(message, false);
5590                        }
5591                    };
5592            mDatabaseWriterExecutor.execute(runnable);
5593            updateConversationUi();
5594            updateUnreadCountBadge();
5595            return readMessages;
5596        } else {
5597            return readMessages;
5598        }
5599    }
5600
5601    public synchronized void updateUnreadCountBadge() {
5602        int count = unreadCount();
5603        if (unreadCount != count) {
5604            Log.d(Config.LOGTAG, "update unread count to " + count);
5605            if (count > 0) {
5606                ShortcutBadger.applyCount(getApplicationContext(), count);
5607            } else {
5608                ShortcutBadger.removeCount(getApplicationContext());
5609            }
5610            unreadCount = count;
5611        }
5612    }
5613
5614    public void sendReadMarker(final Conversation conversation, final String upToUuid) {
5615        final boolean isPrivateAndNonAnonymousMuc =
5616                conversation.getMode() == Conversation.MODE_MULTI
5617                        && conversation.isPrivateAndNonAnonymous();
5618        final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
5619        if (readMessages.isEmpty()) {
5620            return;
5621        }
5622        final var account = conversation.getAccount();
5623        final var connection = account.getXmppConnection();
5624        updateConversationUi();
5625        final var last =
5626                Iterables.getLast(
5627                        Collections2.filter(
5628                                readMessages,
5629                                m ->
5630                                        !m.isPrivateMessage()
5631                                                && m.getStatus() == Message.STATUS_RECEIVED),
5632                        null);
5633        if (last == null) {
5634            return;
5635        }
5636
5637        final boolean sendDisplayedMarker =
5638                confirmMessages()
5639                        && (last.trusted() || isPrivateAndNonAnonymousMuc)
5640                        && last.getRemoteMsgId() != null
5641                        && (last.markable || isPrivateAndNonAnonymousMuc);
5642        final boolean serverAssist =
5643                connection != null && connection.getFeatures().mdsServerAssist();
5644
5645        final String stanzaId = last.getServerMsgId();
5646
5647        if (sendDisplayedMarker && serverAssist) {
5648            final var mdsDisplayed = mIqGenerator.mdsDisplayed(stanzaId, conversation);
5649            final var packet = mMessageGenerator.confirm(last);
5650            packet.addChild(mdsDisplayed);
5651            if (!last.isPrivateMessage()) {
5652                packet.setTo(packet.getTo().asBareJid());
5653            }
5654            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server assisted " + packet);
5655            this.sendMessagePacket(account, packet);
5656        } else {
5657            publishMds(last);
5658            // read markers will be sent after MDS to flush the CSI stanza queue
5659            if (sendDisplayedMarker) {
5660                Log.d(
5661                        Config.LOGTAG,
5662                        conversation.getAccount().getJid().asBareJid()
5663                                + ": sending displayed marker to "
5664                                + last.getCounterpart().toString());
5665                final var packet = mMessageGenerator.confirm(last);
5666                this.sendMessagePacket(account, packet);
5667            }
5668        }
5669    }
5670
5671    private void publishMds(@Nullable final Message message) {
5672        final String stanzaId = message == null ? null : message.getServerMsgId();
5673        if (Strings.isNullOrEmpty(stanzaId)) {
5674            return;
5675        }
5676        final Conversation conversation;
5677        final var conversational = message.getConversation();
5678        if (conversational instanceof Conversation c) {
5679            conversation = c;
5680        } else {
5681            return;
5682        }
5683        final var account = conversation.getAccount();
5684        final var connection = account.getXmppConnection();
5685        if (connection == null || !connection.getFeatures().mds()) {
5686            return;
5687        }
5688        final Jid itemId;
5689        if (message.isPrivateMessage()) {
5690            itemId = message.getCounterpart();
5691        } else {
5692            itemId = conversation.getJid().asBareJid();
5693        }
5694        Log.d(Config.LOGTAG, "publishing mds for " + itemId + "/" + stanzaId);
5695        publishMds(account, itemId, stanzaId, conversation);
5696    }
5697
5698    private void publishMds(
5699            final Account account,
5700            final Jid itemId,
5701            final String stanzaId,
5702            final Conversation conversation) {
5703        final var item = mIqGenerator.mdsDisplayed(stanzaId, conversation);
5704        pushNodeAndEnforcePublishOptions(
5705                account,
5706                Namespace.MDS_DISPLAYED,
5707                item,
5708                itemId.toString(),
5709                PublishOptions.persistentWhitelistAccessMaxItems());
5710    }
5711
5712    public boolean sendReactions(final Message message, final Collection<String> reactions) {
5713        if (message.getConversation() instanceof Conversation conversation) {
5714            final var isPrivateMessage = message.isPrivateMessage();
5715            final Jid reactTo;
5716            final boolean typeGroupChat;
5717            final String reactToId;
5718            final Collection<Reaction> combinedReactions;
5719            if (conversation.getMode() == Conversational.MODE_MULTI && !isPrivateMessage) {
5720                final var mucOptions = conversation.getMucOptions();
5721                if (!mucOptions.participating()) {
5722                    Log.d(Config.LOGTAG, "not participating in MUC");
5723                    return false;
5724                }
5725                final var self = mucOptions.getSelf();
5726                final String occupantId = self.getOccupantId();
5727                if (Strings.isNullOrEmpty(occupantId)) {
5728                    Log.d(Config.LOGTAG, "occupant id not found for reaction in MUC");
5729                    return false;
5730                }
5731                final var existingRaw =
5732                        ImmutableSet.copyOf(
5733                                Collections2.transform(message.getReactions(), r -> r.reaction));
5734                final var reactionsAsExistingVariants =
5735                        ImmutableSet.copyOf(
5736                                Collections2.transform(
5737                                        reactions, r -> Emoticons.existingVariant(r, existingRaw)));
5738                if (!reactions.equals(reactionsAsExistingVariants)) {
5739                    Log.d(Config.LOGTAG, "modified reactions to existing variants");
5740                }
5741                reactToId = message.getServerMsgId();
5742                reactTo = conversation.getJid().asBareJid();
5743                typeGroupChat = true;
5744                combinedReactions =
5745                        Reaction.withOccupantId(
5746                                message.getReactions(),
5747                                reactionsAsExistingVariants,
5748                                false,
5749                                self.getFullJid(),
5750                                conversation.getAccount().getJid(),
5751                                occupantId);
5752            } else {
5753                if (message.isCarbon() || message.getStatus() == Message.STATUS_RECEIVED) {
5754                    reactToId = message.getRemoteMsgId();
5755                } else {
5756                    reactToId = message.getUuid();
5757                }
5758                typeGroupChat = false;
5759                if (isPrivateMessage) {
5760                    reactTo = message.getCounterpart();
5761                } else {
5762                    reactTo = conversation.getJid().asBareJid();
5763                }
5764                combinedReactions =
5765                        Reaction.withFrom(
5766                                message.getReactions(),
5767                                reactions,
5768                                false,
5769                                conversation.getAccount().getJid());
5770            }
5771            if (reactTo == null || Strings.isNullOrEmpty(reactToId)) {
5772                return false;
5773            }
5774            final var reactionMessage =
5775                    mMessageGenerator.reaction(reactTo, typeGroupChat, reactToId, reactions);
5776            sendMessagePacket(conversation.getAccount(), reactionMessage);
5777            message.setReactions(combinedReactions);
5778            updateMessage(message, false);
5779            return true;
5780        } else {
5781            return false;
5782        }
5783    }
5784
5785    public MemorizingTrustManager getMemorizingTrustManager() {
5786        return this.mMemorizingTrustManager;
5787    }
5788
5789    public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
5790        this.mMemorizingTrustManager = trustManager;
5791    }
5792
5793    public void updateMemorizingTrustManager() {
5794        final MemorizingTrustManager trustManager;
5795        if (appSettings.isTrustSystemCAStore()) {
5796            trustManager = new MemorizingTrustManager(getApplicationContext());
5797        } else {
5798            trustManager = new MemorizingTrustManager(getApplicationContext(), null);
5799        }
5800        setMemorizingTrustManager(trustManager);
5801    }
5802
5803    public LruCache<String, Bitmap> getBitmapCache() {
5804        return this.mBitmapCache;
5805    }
5806
5807    public Collection<String> getKnownHosts() {
5808        final Set<String> hosts = new HashSet<>();
5809        for (final Account account : getAccounts()) {
5810            hosts.add(account.getServer());
5811            for (final Contact contact : account.getRoster().getContacts()) {
5812                if (contact.showInRoster()) {
5813                    final String server = contact.getServer();
5814                    if (server != null) {
5815                        hosts.add(server);
5816                    }
5817                }
5818            }
5819        }
5820        if (Config.QUICKSY_DOMAIN != null) {
5821            hosts.remove(
5822                    Config.QUICKSY_DOMAIN
5823                            .toString()); // we only want to show this when we type a e164
5824            // number
5825        }
5826        if (Config.MAGIC_CREATE_DOMAIN != null) {
5827            hosts.add(Config.MAGIC_CREATE_DOMAIN);
5828        }
5829        return hosts;
5830    }
5831
5832    public Collection<String> getKnownConferenceHosts() {
5833        final Set<String> mucServers = new HashSet<>();
5834        for (final Account account : accounts) {
5835            if (account.getXmppConnection() != null) {
5836                mucServers.addAll(account.getXmppConnection().getMucServers());
5837                for (final Bookmark bookmark : account.getBookmarks()) {
5838                    final Jid jid = bookmark.getJid();
5839                    final String s = jid == null ? null : jid.getDomain().toString();
5840                    if (s != null) {
5841                        mucServers.add(s);
5842                    }
5843                }
5844            }
5845        }
5846        return mucServers;
5847    }
5848
5849    public void sendMessagePacket(
5850            final Account account,
5851            final im.conversations.android.xmpp.model.stanza.Message packet) {
5852        final XmppConnection connection = account.getXmppConnection();
5853        if (connection != null) {
5854            connection.sendMessagePacket(packet);
5855        }
5856    }
5857
5858    public void sendPresencePacket(
5859            final Account account,
5860            final im.conversations.android.xmpp.model.stanza.Presence packet) {
5861        final XmppConnection connection = account.getXmppConnection();
5862        if (connection != null) {
5863            connection.sendPresencePacket(packet);
5864        }
5865    }
5866
5867    public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
5868        final XmppConnection connection = account.getXmppConnection();
5869        if (connection == null) {
5870            return;
5871        }
5872        connection.sendCreateAccountWithCaptchaPacket(id, data);
5873    }
5874
5875    public void sendIqPacket(final Account account, final Iq packet, final Consumer<Iq> callback) {
5876        final XmppConnection connection = account.getXmppConnection();
5877        if (connection != null) {
5878            connection.sendIqPacket(packet, callback);
5879        } else if (callback != null) {
5880            callback.accept(Iq.TIMEOUT);
5881        }
5882    }
5883
5884    public void sendPresence(final Account account) {
5885        sendPresence(account, checkListeners() && broadcastLastActivity());
5886    }
5887
5888    private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
5889        final Presence.Status status;
5890        if (manuallyChangePresence()) {
5891            status = account.getPresenceStatus();
5892        } else {
5893            status = getTargetPresence();
5894        }
5895        final var packet = mPresenceGenerator.selfPresence(account, status);
5896        if (mLastActivity > 0 && includeIdleTimestamp) {
5897            long since =
5898                    Math.min(mLastActivity, System.currentTimeMillis()); // don't send future dates
5899            packet.addChild("idle", Namespace.IDLE)
5900                    .setAttribute("since", AbstractGenerator.getTimestamp(since));
5901        }
5902        sendPresencePacket(account, packet);
5903    }
5904
5905    private void deactivateGracePeriod() {
5906        for (Account account : getAccounts()) {
5907            account.deactivateGracePeriod();
5908        }
5909    }
5910
5911    public void refreshAllPresences() {
5912        boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
5913        for (Account account : getAccounts()) {
5914            if (account.isConnectionEnabled()) {
5915                sendPresence(account, includeIdleTimestamp);
5916            }
5917        }
5918    }
5919
5920    private void refreshAllFcmTokens() {
5921        for (Account account : getAccounts()) {
5922            if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
5923                mPushManagementService.registerPushTokenOnServer(account);
5924            }
5925        }
5926    }
5927
5928    private void sendOfflinePresence(final Account account) {
5929        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
5930        sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
5931    }
5932
5933    public MessageGenerator getMessageGenerator() {
5934        return this.mMessageGenerator;
5935    }
5936
5937    public PresenceGenerator getPresenceGenerator() {
5938        return this.mPresenceGenerator;
5939    }
5940
5941    public IqGenerator getIqGenerator() {
5942        return this.mIqGenerator;
5943    }
5944
5945    public JingleConnectionManager getJingleConnectionManager() {
5946        return this.mJingleConnectionManager;
5947    }
5948
5949    private boolean hasJingleRtpConnection(final Account account) {
5950        return this.mJingleConnectionManager.hasJingleRtpConnection(account);
5951    }
5952
5953    public MessageArchiveService getMessageArchiveService() {
5954        return this.mMessageArchiveService;
5955    }
5956
5957    public QuickConversationsService getQuickConversationsService() {
5958        return this.mQuickConversationsService;
5959    }
5960
5961    public List<Contact> findContacts(Jid jid, String accountJid) {
5962        ArrayList<Contact> contacts = new ArrayList<>();
5963        for (Account account : getAccounts()) {
5964            if ((account.isEnabled() || accountJid != null)
5965                    && (accountJid == null
5966                            || accountJid.equals(account.getJid().asBareJid().toString()))) {
5967                Contact contact = account.getRoster().getContactFromContactList(jid);
5968                if (contact != null) {
5969                    contacts.add(contact);
5970                }
5971            }
5972        }
5973        return contacts;
5974    }
5975
5976    public Conversation findFirstMuc(Jid jid) {
5977        for (Conversation conversation : getConversations()) {
5978            if (conversation.getAccount().isEnabled()
5979                    && conversation.getJid().asBareJid().equals(jid.asBareJid())
5980                    && conversation.getMode() == Conversation.MODE_MULTI) {
5981                return conversation;
5982            }
5983        }
5984        return null;
5985    }
5986
5987    public NotificationService getNotificationService() {
5988        return this.mNotificationService;
5989    }
5990
5991    public HttpConnectionManager getHttpConnectionManager() {
5992        return this.mHttpConnectionManager;
5993    }
5994
5995    public void resendFailedMessages(final Message message) {
5996        message.setTime(System.currentTimeMillis());
5997        markMessage(message, Message.STATUS_WAITING);
5998        this.resendMessage(message, false);
5999        if (message.getConversation() instanceof Conversation c) {
6000            c.sort();
6001        }
6002        updateConversationUi();
6003    }
6004
6005    public void clearConversationHistory(final Conversation conversation) {
6006        final long clearDate;
6007        final String reference;
6008        if (conversation.countMessages() > 0) {
6009            Message latestMessage = conversation.getLatestMessage();
6010            clearDate = latestMessage.getTimeSent() + 1000;
6011            reference = latestMessage.getServerMsgId();
6012        } else {
6013            clearDate = System.currentTimeMillis();
6014            reference = null;
6015        }
6016        conversation.clearMessages();
6017        conversation.setHasMessagesLeftOnServer(false); // avoid messages getting loaded through mam
6018        conversation.setLastClearHistory(clearDate, reference);
6019        Runnable runnable =
6020                () -> {
6021                    databaseBackend.deleteMessagesInConversation(conversation);
6022                    databaseBackend.updateConversation(conversation);
6023                };
6024        mDatabaseWriterExecutor.execute(runnable);
6025    }
6026
6027    public boolean sendBlockRequest(
6028            final Blockable blockable, final boolean reportSpam, final String serverMsgId) {
6029        if (blockable != null && blockable.getBlockedJid() != null) {
6030            final var account = blockable.getAccount();
6031            final Jid jid = blockable.getBlockedJid();
6032            this.sendIqPacket(
6033                    account,
6034                    getIqGenerator().generateSetBlockRequest(jid, reportSpam, serverMsgId),
6035                    (response) -> {
6036                        if (response.getType() == Iq.Type.RESULT) {
6037                            account.getBlocklist().add(jid);
6038                            updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
6039                        }
6040                    });
6041            if (blockable.getBlockedJid().isFullJid()) {
6042                return false;
6043            } else if (removeBlockedConversations(blockable.getAccount(), jid)) {
6044                updateConversationUi();
6045                return true;
6046            } else {
6047                return false;
6048            }
6049        } else {
6050            return false;
6051        }
6052    }
6053
6054    public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
6055        boolean removed = false;
6056        synchronized (this.conversations) {
6057            boolean domainJid = blockedJid.getLocal() == null;
6058            for (Conversation conversation : this.conversations) {
6059                boolean jidMatches =
6060                        (domainJid
6061                                        && blockedJid
6062                                                .getDomain()
6063                                                .equals(conversation.getJid().getDomain()))
6064                                || blockedJid.equals(conversation.getJid().asBareJid());
6065                if (conversation.getAccount() == account
6066                        && conversation.getMode() == Conversation.MODE_SINGLE
6067                        && jidMatches) {
6068                    this.conversations.remove(conversation);
6069                    markRead(conversation);
6070                    conversation.setStatus(Conversation.STATUS_ARCHIVED);
6071                    Log.d(
6072                            Config.LOGTAG,
6073                            account.getJid().asBareJid()
6074                                    + ": archiving conversation "
6075                                    + conversation.getJid().asBareJid()
6076                                    + " because jid was blocked");
6077                    updateConversation(conversation);
6078                    removed = true;
6079                }
6080            }
6081        }
6082        return removed;
6083    }
6084
6085    public void sendUnblockRequest(final Blockable blockable) {
6086        if (blockable != null && blockable.getJid() != null) {
6087            final var account = blockable.getAccount();
6088            final Jid jid = blockable.getBlockedJid();
6089            this.sendIqPacket(
6090                    account,
6091                    getIqGenerator().generateSetUnblockRequest(jid),
6092                    response -> {
6093                        if (response.getType() == Iq.Type.RESULT) {
6094                            account.getBlocklist().remove(jid);
6095                            updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
6096                        }
6097                    });
6098        }
6099    }
6100
6101    public void publishDisplayName(final Account account) {
6102        String displayName = account.getDisplayName();
6103        final Iq request;
6104        if (TextUtils.isEmpty(displayName)) {
6105            request = mIqGenerator.deleteNode(Namespace.NICK);
6106        } else {
6107            request = mIqGenerator.publishNick(displayName);
6108        }
6109        mAvatarService.clear(account);
6110        sendIqPacket(
6111                account,
6112                request,
6113                (packet) -> {
6114                    if (packet.getType() == Iq.Type.ERROR) {
6115                        Log.d(
6116                                Config.LOGTAG,
6117                                account.getJid().asBareJid()
6118                                        + ": unable to modify nick name "
6119                                        + packet);
6120                    }
6121                });
6122    }
6123
6124    public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
6125        ServiceDiscoveryResult result = discoCache.get(key);
6126        if (result != null) {
6127            return result;
6128        } else {
6129            result = databaseBackend.findDiscoveryResult(key.first, key.second);
6130            if (result != null) {
6131                discoCache.put(key, result);
6132            }
6133            return result;
6134        }
6135    }
6136
6137    public void fetchCaps(final Account account, final Jid jid, final Presence presence) {
6138        final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
6139        final ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
6140        if (disco != null) {
6141            presence.setServiceDiscoveryResult(disco);
6142            final Contact contact = account.getRoster().getContact(jid);
6143            if (contact.refreshRtpCapability()) {
6144                syncRoster(account);
6145            }
6146        } else {
6147            final Iq request = new Iq(Iq.Type.GET);
6148            request.setTo(jid);
6149            final String node = presence.getNode();
6150            final String ver = presence.getVer();
6151            final Element query = request.query(Namespace.DISCO_INFO);
6152            if (node != null && ver != null) {
6153                query.setAttribute("node", node + "#" + ver);
6154            }
6155            Log.d(
6156                    Config.LOGTAG,
6157                    account.getJid().asBareJid()
6158                            + ": making disco request for "
6159                            + key.second
6160                            + " to "
6161                            + jid);
6162            sendIqPacket(
6163                    account,
6164                    request,
6165                    (response) -> {
6166                        if (response.getType() == Iq.Type.RESULT) {
6167                            final ServiceDiscoveryResult discoveryResult =
6168                                    new ServiceDiscoveryResult(response);
6169                            if (presence.getVer().equals(discoveryResult.getVer())) {
6170                                databaseBackend.insertDiscoveryResult(discoveryResult);
6171                                injectServiceDiscoveryResult(
6172                                        account.getRoster(),
6173                                        presence.getHash(),
6174                                        presence.getVer(),
6175                                        discoveryResult);
6176                            } else {
6177                                Log.d(
6178                                        Config.LOGTAG,
6179                                        account.getJid().asBareJid()
6180                                                + ": mismatch in caps for contact "
6181                                                + jid
6182                                                + " "
6183                                                + presence.getVer()
6184                                                + " vs "
6185                                                + discoveryResult.getVer());
6186                            }
6187                        } else {
6188                            Log.d(
6189                                    Config.LOGTAG,
6190                                    account.getJid().asBareJid()
6191                                            + ": unable to fetch caps from "
6192                                            + jid);
6193                        }
6194                    });
6195        }
6196    }
6197
6198    private void injectServiceDiscoveryResult(
6199            Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
6200        boolean rosterNeedsSync = false;
6201        for (final Contact contact : roster.getContacts()) {
6202            boolean serviceDiscoverySet = false;
6203            for (final Presence presence : contact.getPresences().getPresences()) {
6204                if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
6205                    presence.setServiceDiscoveryResult(disco);
6206                    serviceDiscoverySet = true;
6207                }
6208            }
6209            if (serviceDiscoverySet) {
6210                rosterNeedsSync |= contact.refreshRtpCapability();
6211            }
6212        }
6213        if (rosterNeedsSync) {
6214            syncRoster(roster.getAccount());
6215        }
6216    }
6217
6218    public void fetchMamPreferences(final Account account, final OnMamPreferencesFetched callback) {
6219        final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
6220        final Iq request = new Iq(Iq.Type.GET);
6221        request.addChild("prefs", version.namespace);
6222        sendIqPacket(
6223                account,
6224                request,
6225                (packet) -> {
6226                    final Element prefs = packet.findChild("prefs", version.namespace);
6227                    if (packet.getType() == Iq.Type.RESULT && prefs != null) {
6228                        callback.onPreferencesFetched(prefs);
6229                    } else {
6230                        callback.onPreferencesFetchFailed();
6231                    }
6232                });
6233    }
6234
6235    public PushManagementService getPushManagementService() {
6236        return mPushManagementService;
6237    }
6238
6239    public void changeStatus(Account account, PresenceTemplate template, String signature) {
6240        if (!template.getStatusMessage().isEmpty()) {
6241            databaseBackend.insertPresenceTemplate(template);
6242        }
6243        account.setPgpSignature(signature);
6244        account.setPresenceStatus(template.getStatus());
6245        account.setPresenceStatusMessage(template.getStatusMessage());
6246        databaseBackend.updateAccount(account);
6247        sendPresence(account);
6248    }
6249
6250    public List<PresenceTemplate> getPresenceTemplates(Account account) {
6251        List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
6252        for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
6253            if (!templates.contains(template)) {
6254                templates.add(0, template);
6255            }
6256        }
6257        return templates;
6258    }
6259
6260    public void saveConversationAsBookmark(final Conversation conversation, final String name) {
6261        final Account account = conversation.getAccount();
6262        final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
6263        final String nick = conversation.getJid().getResource();
6264        if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
6265            bookmark.setNick(nick);
6266        }
6267        if (!TextUtils.isEmpty(name)) {
6268            bookmark.setBookmarkName(name);
6269        }
6270        bookmark.setAutojoin(true);
6271        createBookmark(account, bookmark);
6272        bookmark.setConversation(conversation);
6273    }
6274
6275    public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
6276        boolean performedVerification = false;
6277        final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
6278        for (XmppUri.Fingerprint fp : fingerprints) {
6279            if (fp.type == XmppUri.FingerprintType.OMEMO) {
6280                String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
6281                FingerprintStatus fingerprintStatus =
6282                        axolotlService.getFingerprintTrust(fingerprint);
6283                if (fingerprintStatus != null) {
6284                    if (!fingerprintStatus.isVerified()) {
6285                        performedVerification = true;
6286                        axolotlService.setFingerprintTrust(
6287                                fingerprint, fingerprintStatus.toVerified());
6288                    }
6289                } else {
6290                    axolotlService.preVerifyFingerprint(contact, fingerprint);
6291                }
6292            }
6293        }
6294        return performedVerification;
6295    }
6296
6297    public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
6298        final AxolotlService axolotlService = account.getAxolotlService();
6299        boolean verifiedSomething = false;
6300        for (XmppUri.Fingerprint fp : fingerprints) {
6301            if (fp.type == XmppUri.FingerprintType.OMEMO) {
6302                String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
6303                Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
6304                FingerprintStatus fingerprintStatus =
6305                        axolotlService.getFingerprintTrust(fingerprint);
6306                if (fingerprintStatus != null) {
6307                    if (!fingerprintStatus.isVerified()) {
6308                        axolotlService.setFingerprintTrust(
6309                                fingerprint, fingerprintStatus.toVerified());
6310                        verifiedSomething = true;
6311                    }
6312                } else {
6313                    axolotlService.preVerifyFingerprint(account, fingerprint);
6314                    verifiedSomething = true;
6315                }
6316            }
6317        }
6318        return verifiedSomething;
6319    }
6320
6321    public boolean blindTrustBeforeVerification() {
6322        return getBooleanPreference(AppSettings.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
6323    }
6324
6325    public ShortcutService getShortcutService() {
6326        return mShortcutService;
6327    }
6328
6329    public void pushMamPreferences(Account account, Element prefs) {
6330        final Iq set = new Iq(Iq.Type.SET);
6331        set.addChild(prefs);
6332        sendIqPacket(account, set, null);
6333    }
6334
6335    public void evictPreview(String uuid) {
6336        if (mBitmapCache.remove(uuid) != null) {
6337            Log.d(Config.LOGTAG, "deleted cached preview");
6338        }
6339    }
6340
6341    public interface OnMamPreferencesFetched {
6342        void onPreferencesFetched(Element prefs);
6343
6344        void onPreferencesFetchFailed();
6345    }
6346
6347    public interface OnAccountCreated {
6348        void onAccountCreated(Account account);
6349
6350        void informUser(int r);
6351    }
6352
6353    public interface OnMoreMessagesLoaded {
6354        void onMoreMessagesLoaded(int count, Conversation conversation);
6355
6356        void informUser(int r);
6357    }
6358
6359    public interface OnAccountPasswordChanged {
6360        void onPasswordChangeSucceeded();
6361
6362        void onPasswordChangeFailed();
6363    }
6364
6365    public interface OnRoomDestroy {
6366        void onRoomDestroySucceeded();
6367
6368        void onRoomDestroyFailed();
6369    }
6370
6371    public interface OnAffiliationChanged {
6372        void onAffiliationChangedSuccessful(Jid jid);
6373
6374        void onAffiliationChangeFailed(Jid jid, int resId);
6375    }
6376
6377    public interface OnConversationUpdate {
6378        void onConversationUpdate();
6379    }
6380
6381    public interface OnJingleRtpConnectionUpdate {
6382        void onJingleRtpConnectionUpdate(
6383                final Account account,
6384                final Jid with,
6385                final String sessionId,
6386                final RtpEndUserState state);
6387
6388        void onAudioDeviceChanged(
6389                CallIntegration.AudioDevice selectedAudioDevice,
6390                Set<CallIntegration.AudioDevice> availableAudioDevices);
6391    }
6392
6393    public interface OnAccountUpdate {
6394        void onAccountUpdate();
6395    }
6396
6397    public interface OnCaptchaRequested {
6398        void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
6399    }
6400
6401    public interface OnRosterUpdate {
6402        void onRosterUpdate();
6403    }
6404
6405    public interface OnMucRosterUpdate {
6406        void onMucRosterUpdate();
6407    }
6408
6409    public interface OnConferenceConfigurationFetched {
6410        void onConferenceConfigurationFetched(Conversation conversation);
6411
6412        void onFetchFailed(Conversation conversation, String errorCondition);
6413    }
6414
6415    public interface OnConferenceJoined {
6416        void onConferenceJoined(Conversation conversation);
6417    }
6418
6419    public interface OnConfigurationPushed {
6420        void onPushSucceeded();
6421
6422        void onPushFailed();
6423    }
6424
6425    public interface OnShowErrorToast {
6426        void onShowErrorToast(int resId);
6427    }
6428
6429    public class XmppConnectionBinder extends Binder {
6430        public XmppConnectionService getService() {
6431            return XmppConnectionService.this;
6432        }
6433    }
6434
6435    private class InternalEventReceiver extends BroadcastReceiver {
6436
6437        @Override
6438        public void onReceive(final Context context, final Intent intent) {
6439            onStartCommand(intent, 0, 0);
6440        }
6441    }
6442
6443    private class RestrictedEventReceiver extends BroadcastReceiver {
6444
6445        private final Collection<String> allowedActions;
6446
6447        private RestrictedEventReceiver(final Collection<String> allowedActions) {
6448            this.allowedActions = allowedActions;
6449        }
6450
6451        @Override
6452        public void onReceive(final Context context, final Intent intent) {
6453            final String action = intent == null ? null : intent.getAction();
6454            if (allowedActions.contains(action)) {
6455                onStartCommand(intent, 0, 0);
6456            } else {
6457                Log.e(Config.LOGTAG, "restricting broadcast of event " + action);
6458            }
6459        }
6460    }
6461
6462    public static class OngoingCall {
6463        public final AbstractJingleConnection.Id id;
6464        public final Set<Media> media;
6465        public final boolean reconnecting;
6466
6467        public OngoingCall(
6468                AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
6469            this.id = id;
6470            this.media = media;
6471            this.reconnecting = reconnecting;
6472        }
6473
6474        @Override
6475        public boolean equals(Object o) {
6476            if (this == o) return true;
6477            if (o == null || getClass() != o.getClass()) return false;
6478            OngoingCall that = (OngoingCall) o;
6479            return reconnecting == that.reconnecting
6480                    && Objects.equal(id, that.id)
6481                    && Objects.equal(media, that.media);
6482        }
6483
6484        @Override
6485        public int hashCode() {
6486            return Objects.hashCode(id, media, reconnecting);
6487        }
6488    }
6489
6490    public static void toggleForegroundService(final XmppConnectionService service) {
6491        if (service == null) {
6492            return;
6493        }
6494        service.toggleForegroundService();
6495    }
6496
6497    public static void toggleForegroundService(final ConversationsActivity activity) {
6498        if (activity == null) {
6499            return;
6500        }
6501        toggleForegroundService(activity.xmppConnectionService);
6502    }
6503}