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