XmppConnectionService.java

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