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