XmppConnectionService.java

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