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