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