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