XmppConnectionService.java

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