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