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