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