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