XmppConnectionService.java

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