XmppConnectionService.java

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