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