XmppConnectionService.java

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