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