XmppConnectionService.java

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