XmppConnectionService.java

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