XmppConnectionService.java

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