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