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