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