XmppConnectionService.java

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