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