XmppConnectionService.java

   1package eu.siacs.conversations.services;
   2
   3import android.Manifest;
   4import android.annotation.SuppressLint;
   5import android.annotation.TargetApi;
   6import android.app.AlarmManager;
   7import android.app.NotificationManager;
   8import android.app.PendingIntent;
   9import android.app.Service;
  10import android.content.BroadcastReceiver;
  11import android.content.Context;
  12import android.content.Intent;
  13import android.content.IntentFilter;
  14import android.content.SharedPreferences;
  15import android.content.pm.PackageManager;
  16import android.database.ContentObserver;
  17import android.graphics.Bitmap;
  18import android.media.AudioManager;
  19import android.net.ConnectivityManager;
  20import android.net.NetworkInfo;
  21import android.net.Uri;
  22import android.os.Binder;
  23import android.os.Build;
  24import android.os.Bundle;
  25import android.os.Environment;
  26import android.os.IBinder;
  27import android.os.PowerManager;
  28import android.os.PowerManager.WakeLock;
  29import android.os.SystemClock;
  30import android.preference.PreferenceManager;
  31import android.provider.ContactsContract;
  32import android.security.KeyChain;
  33import android.support.annotation.BoolRes;
  34import android.support.annotation.IntegerRes;
  35import android.support.v4.app.RemoteInput;
  36import android.support.v4.content.ContextCompat;
  37import android.text.TextUtils;
  38import android.util.DisplayMetrics;
  39import android.util.Log;
  40import android.util.LruCache;
  41import android.util.Pair;
  42
  43import org.conscrypt.Conscrypt;
  44import org.openintents.openpgp.IOpenPgpService2;
  45import org.openintents.openpgp.util.OpenPgpApi;
  46import org.openintents.openpgp.util.OpenPgpServiceConnection;
  47
  48import java.net.URL;
  49import java.security.SecureRandom;
  50import java.security.Security;
  51import java.security.cert.CertificateException;
  52import java.security.cert.X509Certificate;
  53import java.util.ArrayList;
  54import java.util.Arrays;
  55import java.util.Collection;
  56import java.util.Collections;
  57import java.util.HashMap;
  58import java.util.HashSet;
  59import java.util.Hashtable;
  60import java.util.Iterator;
  61import java.util.List;
  62import java.util.ListIterator;
  63import java.util.Map;
  64import java.util.Set;
  65import java.util.WeakHashMap;
  66import java.util.concurrent.CopyOnWriteArrayList;
  67import java.util.concurrent.CountDownLatch;
  68import java.util.concurrent.atomic.AtomicBoolean;
  69import java.util.concurrent.atomic.AtomicLong;
  70
  71
  72import eu.siacs.conversations.Config;
  73import eu.siacs.conversations.R;
  74import eu.siacs.conversations.crypto.OmemoSetting;
  75import eu.siacs.conversations.crypto.PgpDecryptionService;
  76import eu.siacs.conversations.crypto.PgpEngine;
  77import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  78import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  79import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
  80import eu.siacs.conversations.entities.Account;
  81import eu.siacs.conversations.entities.Blockable;
  82import eu.siacs.conversations.entities.Bookmark;
  83import eu.siacs.conversations.entities.Contact;
  84import eu.siacs.conversations.entities.Conversation;
  85import eu.siacs.conversations.entities.Conversational;
  86import eu.siacs.conversations.entities.DownloadableFile;
  87import eu.siacs.conversations.entities.Message;
  88import eu.siacs.conversations.entities.MucOptions;
  89import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
  90import eu.siacs.conversations.entities.Presence;
  91import eu.siacs.conversations.entities.PresenceTemplate;
  92import eu.siacs.conversations.entities.Roster;
  93import eu.siacs.conversations.entities.ServiceDiscoveryResult;
  94import eu.siacs.conversations.entities.Transferable;
  95import eu.siacs.conversations.entities.TransferablePlaceholder;
  96import eu.siacs.conversations.generator.AbstractGenerator;
  97import eu.siacs.conversations.generator.IqGenerator;
  98import eu.siacs.conversations.generator.MessageGenerator;
  99import eu.siacs.conversations.generator.PresenceGenerator;
 100import eu.siacs.conversations.http.HttpConnectionManager;
 101import eu.siacs.conversations.http.CustomURLStreamHandlerFactory;
 102import eu.siacs.conversations.parser.AbstractParser;
 103import eu.siacs.conversations.parser.IqParser;
 104import eu.siacs.conversations.parser.MessageParser;
 105import eu.siacs.conversations.parser.PresenceParser;
 106import eu.siacs.conversations.persistance.DatabaseBackend;
 107import eu.siacs.conversations.persistance.FileBackend;
 108import eu.siacs.conversations.ui.SettingsActivity;
 109import eu.siacs.conversations.ui.UiCallback;
 110import eu.siacs.conversations.ui.interfaces.OnAvatarPublication;
 111import eu.siacs.conversations.ui.interfaces.OnMediaLoaded;
 112import eu.siacs.conversations.ui.interfaces.OnSearchResultsAvailable;
 113import eu.siacs.conversations.utils.Compatibility;
 114import eu.siacs.conversations.utils.ConversationsFileObserver;
 115import eu.siacs.conversations.utils.CryptoHelper;
 116import eu.siacs.conversations.utils.ExceptionHelper;
 117import eu.siacs.conversations.utils.MimeUtils;
 118import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
 119import eu.siacs.conversations.utils.PRNGFixes;
 120import eu.siacs.conversations.utils.PhoneHelper;
 121import eu.siacs.conversations.utils.QuickLoader;
 122import eu.siacs.conversations.utils.ReplacingSerialSingleThreadExecutor;
 123import eu.siacs.conversations.utils.ReplacingTaskManager;
 124import eu.siacs.conversations.utils.Resolver;
 125import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
 126import eu.siacs.conversations.utils.StringUtils;
 127import eu.siacs.conversations.utils.WakeLockHelper;
 128import eu.siacs.conversations.xml.Namespace;
 129import eu.siacs.conversations.utils.XmppUri;
 130import eu.siacs.conversations.xml.Element;
 131import eu.siacs.conversations.xmpp.OnBindListener;
 132import eu.siacs.conversations.xmpp.OnContactStatusChanged;
 133import eu.siacs.conversations.xmpp.OnIqPacketReceived;
 134import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
 135import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
 136import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
 137import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
 138import eu.siacs.conversations.xmpp.OnStatusChanged;
 139import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 140import eu.siacs.conversations.xmpp.Patches;
 141import eu.siacs.conversations.xmpp.XmppConnection;
 142import eu.siacs.conversations.xmpp.chatstate.ChatState;
 143import eu.siacs.conversations.xmpp.forms.Data;
 144import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
 145import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
 146import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
 147import eu.siacs.conversations.xmpp.mam.MamReference;
 148import eu.siacs.conversations.xmpp.pep.Avatar;
 149import eu.siacs.conversations.xmpp.pep.PublishOptions;
 150import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 151import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 152import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
 153import me.leolin.shortcutbadger.ShortcutBadger;
 154import rocks.xmpp.addr.Jid;
 155
 156public class XmppConnectionService extends Service {
 157
 158    public static final String ACTION_REPLY_TO_CONVERSATION = "reply_to_conversations";
 159    public static final String ACTION_MARK_AS_READ = "mark_as_read";
 160    public static final String ACTION_SNOOZE = "snooze";
 161    public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification";
 162    public static final String ACTION_DISMISS_ERROR_NOTIFICATIONS = "dismiss_error";
 163    public static final String ACTION_TRY_AGAIN = "try_again";
 164    public static final String ACTION_IDLE_PING = "idle_ping";
 165    public static final String ACTION_FCM_TOKEN_REFRESH = "fcm_token_refresh";
 166    public static final String ACTION_FCM_MESSAGE_RECEIVED = "fcm_message_received";
 167
 168    private static final String SETTING_LAST_ACTIVITY_TS = "last_activity_timestamp";
 169
 170    static {
 171        URL.setURLStreamHandlerFactory(new CustomURLStreamHandlerFactory());
 172    }
 173
 174    public final CountDownLatch restoredFromDatabaseLatch = new CountDownLatch(1);
 175    private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor("FileAdding");
 176    private final SerialSingleThreadExecutor mVideoCompressionExecutor = new SerialSingleThreadExecutor("VideoCompression");
 177    private final SerialSingleThreadExecutor mDatabaseWriterExecutor = new SerialSingleThreadExecutor("DatabaseWriter");
 178    private final SerialSingleThreadExecutor mDatabaseReaderExecutor = new SerialSingleThreadExecutor("DatabaseReader");
 179    private final SerialSingleThreadExecutor mNotificationExecutor = new SerialSingleThreadExecutor("NotificationExecutor");
 180    private final ReplacingTaskManager mRosterSyncTaskManager = new ReplacingTaskManager();
 181    private final IBinder mBinder = new XmppConnectionBinder();
 182    private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
 183    private final IqGenerator mIqGenerator = new IqGenerator(this);
 184    private final List<String> mInProgressAvatarFetches = new ArrayList<>();
 185    private final HashSet<Jid> mLowPingTimeoutMode = new HashSet<>();
 186    private final OnIqPacketReceived mDefaultIqHandler = (account, packet) -> {
 187        if (packet.getType() != IqPacket.TYPE.RESULT) {
 188            Element error = packet.findChild("error");
 189            String text = error != null ? error.findChildContent("text") : null;
 190            if (text != null) {
 191                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received iq error - " + text);
 192            }
 193        }
 194    };
 195    public DatabaseBackend databaseBackend;
 196    private ReplacingSerialSingleThreadExecutor mContactMergerExecutor = new ReplacingSerialSingleThreadExecutor(true);
 197    private long mLastActivity = 0;
 198    private FileBackend fileBackend = new FileBackend(this);
 199    private MemorizingTrustManager mMemorizingTrustManager;
 200    private NotificationService mNotificationService = new NotificationService(this);
 201    private ShortcutService mShortcutService = new ShortcutService(this);
 202    private AtomicBoolean mInitialAddressbookSyncCompleted = new AtomicBoolean(false);
 203    private AtomicBoolean mForceForegroundService = new AtomicBoolean(false);
 204    private OnMessagePacketReceived mMessageParser = new MessageParser(this);
 205    private OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
 206    private IqParser mIqParser = new IqParser(this);
 207    private MessageGenerator mMessageGenerator = new MessageGenerator(this);
 208    public OnContactStatusChanged onContactStatusChanged = (contact, online) -> {
 209        Conversation conversation = find(getConversations(), contact);
 210        if (conversation != null) {
 211            if (online) {
 212                if (contact.getPresences().size() == 1) {
 213                    sendUnsentMessages(conversation);
 214                }
 215            }
 216        }
 217    };
 218    private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
 219    private List<Account> accounts;
 220    private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
 221            this);
 222    private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
 223
 224        @Override
 225        public void onJinglePacketReceived(Account account, JinglePacket packet) {
 226            mJingleConnectionManager.deliverPacket(account, packet);
 227        }
 228    };
 229    private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(
 230            this);
 231    private AvatarService mAvatarService = new AvatarService(this);
 232    private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
 233    private PushManagementService mPushManagementService = new PushManagementService(this);
 234    private final ConversationsFileObserver fileObserver = new ConversationsFileObserver(
 235            Environment.getExternalStorageDirectory().getAbsolutePath()
 236    ) {
 237        @Override
 238        public void onEvent(int event, String path) {
 239            Log.d(Config.LOGTAG,"event "+event+" path="+path);
 240            markFileDeleted(path);
 241        }
 242    };
 243    private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
 244
 245        @Override
 246        public boolean onMessageAcknowledged(Account account, String uuid) {
 247            for (final Conversation conversation : getConversations()) {
 248                if (conversation.getAccount() == account) {
 249                    Message message = conversation.findUnsentMessageWithUuid(uuid);
 250                    if (message != null) {
 251                        message.setStatus(Message.STATUS_SEND);
 252                        message.setErrorMessage(null);
 253                        databaseBackend.updateMessage(message, false);
 254                        return true;
 255                    }
 256                }
 257            }
 258            return false;
 259        }
 260    };
 261
 262    private int unreadCount = -1;
 263
 264    //Ui callback listeners
 265    private final Set<OnConversationUpdate> mOnConversationUpdates = Collections.newSetFromMap(new WeakHashMap<OnConversationUpdate, Boolean>());
 266    private final Set<OnShowErrorToast> mOnShowErrorToasts = Collections.newSetFromMap(new WeakHashMap<OnShowErrorToast, Boolean>());
 267    private final Set<OnAccountUpdate> mOnAccountUpdates = Collections.newSetFromMap(new WeakHashMap<OnAccountUpdate, Boolean>());
 268    private final Set<OnCaptchaRequested> mOnCaptchaRequested = Collections.newSetFromMap(new WeakHashMap<OnCaptchaRequested, Boolean>());
 269    private final Set<OnRosterUpdate> mOnRosterUpdates = Collections.newSetFromMap(new WeakHashMap<OnRosterUpdate, Boolean>());
 270    private final Set<OnUpdateBlocklist> mOnUpdateBlocklist = Collections.newSetFromMap(new WeakHashMap<OnUpdateBlocklist, Boolean>());
 271    private final Set<OnMucRosterUpdate> mOnMucRosterUpdate = Collections.newSetFromMap(new WeakHashMap<OnMucRosterUpdate, Boolean>());
 272    private final Set<OnKeyStatusUpdated> mOnKeyStatusUpdated = Collections.newSetFromMap(new WeakHashMap<OnKeyStatusUpdated, Boolean>());
 273
 274    private final Object LISTENER_LOCK = new Object();
 275
 276
 277    private final OnBindListener mOnBindListener = new OnBindListener() {
 278
 279        @Override
 280        public void onBind(final Account account) {
 281            synchronized (mInProgressAvatarFetches) {
 282                for (Iterator<String> iterator = mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
 283                    final String KEY = iterator.next();
 284                    if (KEY.startsWith(account.getJid().asBareJid() + "_")) {
 285                        iterator.remove();
 286                    }
 287                }
 288            }
 289            boolean needsUpdating = account.setOption(Account.OPTION_LOGGED_IN_SUCCESSFULLY, true);
 290            needsUpdating |= account.setOption(Account.OPTION_HTTP_UPLOAD_AVAILABLE, account.getXmppConnection().getFeatures().httpUpload(0));
 291            if (needsUpdating) {
 292                databaseBackend.updateAccount(account);
 293            }
 294            account.getRoster().clearPresences();
 295            mJingleConnectionManager.cancelInTransmission();
 296            fetchRosterFromServer(account);
 297            if (!account.getXmppConnection().getFeatures().bookmarksConversion()) {
 298                fetchBookmarks(account);
 299            }
 300            final boolean flexible = account.getXmppConnection().getFeatures().flexibleOfflineMessageRetrieval();
 301            final boolean catchup = getMessageArchiveService().inCatchup(account);
 302            if (flexible && catchup) {
 303                sendIqPacket(account, mIqGenerator.purgeOfflineMessages(), (acc, packet) -> {
 304                    if (packet.getType() == IqPacket.TYPE.RESULT) {
 305                        Log.d(Config.LOGTAG, acc.getJid().asBareJid() + ": successfully purged offline messages");
 306                    }
 307                });
 308            }
 309            sendPresence(account);
 310            if (mPushManagementService.available(account)) {
 311                mPushManagementService.registerPushTokenOnServer(account);
 312            }
 313            connectMultiModeConversations(account);
 314            syncDirtyContacts(account);
 315        }
 316    };
 317    private AtomicLong mLastExpiryRun = new AtomicLong(0);
 318    private SecureRandom mRandom;
 319    private LruCache<Pair<String, String>, ServiceDiscoveryResult> discoCache = new LruCache<>(20);
 320    private OnStatusChanged statusListener = new OnStatusChanged() {
 321
 322        @Override
 323        public void onStatusChanged(final Account account) {
 324            XmppConnection connection = account.getXmppConnection();
 325            updateAccountUi();
 326            if (account.getStatus() == Account.State.ONLINE) {
 327                synchronized (mLowPingTimeoutMode) {
 328                    if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
 329                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": leaving low ping timeout mode");
 330                    }
 331                }
 332                if (account.setShowErrorNotification(true)) {
 333                    databaseBackend.updateAccount(account);
 334                }
 335                mMessageArchiveService.executePendingQueries(account);
 336                if (connection != null && connection.getFeatures().csi()) {
 337                    if (checkListeners()) {
 338                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + " sending csi//inactive");
 339                        connection.sendInactive();
 340                    } else {
 341                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + " sending csi//active");
 342                        connection.sendActive();
 343                    }
 344                }
 345                List<Conversation> conversations = getConversations();
 346                for (Conversation conversation : conversations) {
 347                    if (conversation.getAccount() == account && !account.pendingConferenceJoins.contains(conversation)) {
 348                        sendUnsentMessages(conversation);
 349                    }
 350                }
 351                for (Conversation conversation : account.pendingConferenceLeaves) {
 352                    leaveMuc(conversation);
 353                }
 354                account.pendingConferenceLeaves.clear();
 355                for (Conversation conversation : account.pendingConferenceJoins) {
 356                    joinMuc(conversation);
 357                }
 358                account.pendingConferenceJoins.clear();
 359                scheduleWakeUpCall(Config.PING_MAX_INTERVAL, account.getUuid().hashCode());
 360            } else if (account.getStatus() == Account.State.OFFLINE || account.getStatus() == Account.State.DISABLED) {
 361                resetSendingToWaiting(account);
 362                if (account.isEnabled() && isInLowPingTimeoutMode(account)) {
 363                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": went into offline state during low ping mode. reconnecting now");
 364                    reconnectAccount(account, true, false);
 365                } else {
 366                    int timeToReconnect = mRandom.nextInt(10) + 2;
 367                    scheduleWakeUpCall(timeToReconnect, account.getUuid().hashCode());
 368                }
 369            } else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
 370                databaseBackend.updateAccount(account);
 371                reconnectAccount(account, true, false);
 372            } else if (account.getStatus() != Account.State.CONNECTING && account.getStatus() != Account.State.NO_INTERNET) {
 373                resetSendingToWaiting(account);
 374                if (connection != null && account.getStatus().isAttemptReconnect()) {
 375                    final int next = connection.getTimeToNextAttempt();
 376                    final boolean lowPingTimeoutMode = isInLowPingTimeoutMode(account);
 377                    if (next <= 0) {
 378                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error connecting account. reconnecting now. lowPingTimeout=" + Boolean.toString(lowPingTimeoutMode));
 379                        reconnectAccount(account, true, false);
 380                    } else {
 381                        final int attempt = connection.getAttempt() + 1;
 382                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error connecting account. try again in " + next + "s for the " + attempt + " time. lowPingTimeout=" + Boolean.toString(lowPingTimeoutMode));
 383                        scheduleWakeUpCall(next, account.getUuid().hashCode());
 384                    }
 385                }
 386            }
 387            getNotificationService().updateErrorNotification();
 388        }
 389    };
 390    private OpenPgpServiceConnection pgpServiceConnection;
 391    private PgpEngine mPgpEngine = null;
 392    private WakeLock wakeLock;
 393    private PowerManager pm;
 394    private LruCache<String, Bitmap> mBitmapCache;
 395    private BroadcastReceiver mInternalEventReceiver = new InternalEventReceiver();
 396    private BroadcastReceiver mInternalScreenEventReceiver = new InternalEventReceiver();
 397
 398    private static String generateFetchKey(Account account, final Avatar avatar) {
 399        return account.getJid().asBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum;
 400    }
 401
 402    private boolean isInLowPingTimeoutMode(Account account) {
 403        synchronized (mLowPingTimeoutMode) {
 404            return mLowPingTimeoutMode.contains(account.getJid().asBareJid());
 405        }
 406    }
 407
 408    public void startForcingForegroundNotification() {
 409        mForceForegroundService.set(true);
 410        toggleForegroundService();
 411    }
 412
 413    public void stopForcingForegroundNotification() {
 414        mForceForegroundService.set(false);
 415        toggleForegroundService();
 416    }
 417
 418    public boolean areMessagesInitialized() {
 419        return this.restoredFromDatabaseLatch.getCount() == 0;
 420    }
 421
 422    public PgpEngine getPgpEngine() {
 423        if (!Config.supportOpenPgp()) {
 424            return null;
 425        } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
 426            if (this.mPgpEngine == null) {
 427                this.mPgpEngine = new PgpEngine(new OpenPgpApi(
 428                        getApplicationContext(),
 429                        pgpServiceConnection.getService()), this);
 430            }
 431            return mPgpEngine;
 432        } else {
 433            return null;
 434        }
 435
 436    }
 437
 438    public OpenPgpApi getOpenPgpApi() {
 439        if (!Config.supportOpenPgp()) {
 440            return null;
 441        } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
 442            return new OpenPgpApi(this, pgpServiceConnection.getService());
 443        } else {
 444            return null;
 445        }
 446    }
 447
 448    public FileBackend getFileBackend() {
 449        return this.fileBackend;
 450    }
 451
 452    public AvatarService getAvatarService() {
 453        return this.mAvatarService;
 454    }
 455
 456    public void attachLocationToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
 457        int encryption = conversation.getNextEncryption();
 458        if (encryption == Message.ENCRYPTION_PGP) {
 459            encryption = Message.ENCRYPTION_DECRYPTED;
 460        }
 461        Message message = new Message(conversation, uri.toString(), encryption);
 462        if (conversation.getNextCounterpart() != null) {
 463            message.setCounterpart(conversation.getNextCounterpart());
 464        }
 465        if (encryption == Message.ENCRYPTION_DECRYPTED) {
 466            getPgpEngine().encrypt(message, callback);
 467        } else {
 468            sendMessage(message);
 469            callback.success(message);
 470        }
 471    }
 472
 473    public void attachFileToConversation(final Conversation conversation, final Uri uri, final String type, final UiCallback<Message> callback) {
 474        if (FileBackend.weOwnFile(this, uri)) {
 475            Log.d(Config.LOGTAG, "trying to attach file that belonged to us");
 476            callback.error(R.string.security_error_invalid_file_access, null);
 477            return;
 478        }
 479        final Message message;
 480        if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 481            message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
 482        } else {
 483            message = new Message(conversation, "", conversation.getNextEncryption());
 484        }
 485        message.setCounterpart(conversation.getNextCounterpart());
 486        message.setType(Message.TYPE_FILE);
 487        final AttachFileToConversationRunnable runnable = new AttachFileToConversationRunnable(this, uri, type, message, callback);
 488        if (runnable.isVideoMessage()) {
 489            mVideoCompressionExecutor.execute(runnable);
 490        } else {
 491            mFileAddingExecutor.execute(runnable);
 492        }
 493    }
 494
 495    public void attachImageToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
 496        if (FileBackend.weOwnFile(this, uri)) {
 497            Log.d(Config.LOGTAG, "trying to attach file that belonged to us");
 498            callback.error(R.string.security_error_invalid_file_access, null);
 499            return;
 500        }
 501
 502        final String mimeType = MimeUtils.guessMimeTypeFromUri(this, uri);
 503        final String compressPictures = getCompressPicturesPreference();
 504
 505        if ("never".equals(compressPictures)
 506                || ("auto".equals(compressPictures) && getFileBackend().useImageAsIs(uri))
 507                || (mimeType != null && mimeType.endsWith("/gif"))
 508                || getFileBackend().unusualBounds(uri)) {
 509            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": not compressing picture. sending as file");
 510            attachFileToConversation(conversation, uri, mimeType, callback);
 511            return;
 512        }
 513        final Message message;
 514        if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 515            message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
 516        } else {
 517            message = new Message(conversation, "", conversation.getNextEncryption());
 518        }
 519        message.setCounterpart(conversation.getNextCounterpart());
 520        message.setType(Message.TYPE_IMAGE);
 521        mFileAddingExecutor.execute(() -> {
 522            try {
 523                getFileBackend().copyImageToPrivateStorage(message, uri);
 524                if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 525                    final PgpEngine pgpEngine = getPgpEngine();
 526                    if (pgpEngine != null) {
 527                        pgpEngine.encrypt(message, callback);
 528                    } else if (callback != null) {
 529                        callback.error(R.string.unable_to_connect_to_keychain, null);
 530                    }
 531                } else {
 532                    sendMessage(message);
 533                    callback.success(message);
 534                }
 535            } catch (final FileBackend.FileCopyException e) {
 536                callback.error(e.getResId(), message);
 537            }
 538        });
 539    }
 540
 541    public Conversation find(Bookmark bookmark) {
 542        return find(bookmark.getAccount(), bookmark.getJid());
 543    }
 544
 545    public Conversation find(final Account account, final Jid jid) {
 546        return find(getConversations(), account, jid);
 547    }
 548
 549    public boolean isMuc(final Account account, final Jid jid) {
 550        final Conversation c = find(account, jid);
 551        return c != null && c.getMode() == Conversational.MODE_MULTI;
 552    }
 553
 554    public void search(List<String> term, OnSearchResultsAvailable onSearchResultsAvailable) {
 555        MessageSearchTask.search(this, term, onSearchResultsAvailable);
 556    }
 557
 558    @Override
 559    public int onStartCommand(Intent intent, int flags, int startId) {
 560        final String action = intent == null ? null : intent.getAction();
 561        String pushedAccountHash = null;
 562        boolean interactive = false;
 563        if (action != null) {
 564            final String uuid = intent.getStringExtra("uuid");
 565            switch (action) {
 566                case ConnectivityManager.CONNECTIVITY_ACTION:
 567                    if (hasInternetConnection() && Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
 568                        resetAllAttemptCounts(true, false);
 569                    }
 570                    break;
 571                case Intent.ACTION_SHUTDOWN:
 572                    logoutAndSave(true);
 573                    return START_NOT_STICKY;
 574                case ACTION_CLEAR_NOTIFICATION:
 575                    mNotificationExecutor.execute(() -> {
 576                        try {
 577                            final Conversation c = findConversationByUuid(uuid);
 578                            if (c != null) {
 579                                mNotificationService.clear(c);
 580                            } else {
 581                                mNotificationService.clear();
 582                            }
 583                            restoredFromDatabaseLatch.await();
 584
 585                        } catch (InterruptedException e) {
 586                            Log.d(Config.LOGTAG, "unable to process clear notification");
 587                        }
 588                    });
 589                    break;
 590                case ACTION_DISMISS_ERROR_NOTIFICATIONS:
 591                    dismissErrorNotifications();
 592                    break;
 593                case ACTION_TRY_AGAIN:
 594                    resetAllAttemptCounts(false, true);
 595                    interactive = true;
 596                    break;
 597                case ACTION_REPLY_TO_CONVERSATION:
 598                    Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
 599                    if (remoteInput == null) {
 600                        break;
 601                    }
 602                    final CharSequence body = remoteInput.getCharSequence("text_reply");
 603                    final boolean dismissNotification = intent.getBooleanExtra("dismiss_notification", false);
 604                    if (body == null || body.length() <= 0) {
 605                        break;
 606                    }
 607                    mNotificationExecutor.execute(() -> {
 608                        try {
 609                            restoredFromDatabaseLatch.await();
 610                            final Conversation c = findConversationByUuid(uuid);
 611                            if (c != null) {
 612                                directReply(c, body.toString(), dismissNotification);
 613                            }
 614                        } catch (InterruptedException e) {
 615                            Log.d(Config.LOGTAG, "unable to process direct reply");
 616                        }
 617                    });
 618                    break;
 619                case ACTION_MARK_AS_READ:
 620                    mNotificationExecutor.execute(() -> {
 621                        final Conversation c = findConversationByUuid(uuid);
 622                        if (c == null) {
 623                            Log.d(Config.LOGTAG, "received mark read intent for unknown conversation (" + uuid + ")");
 624                            return;
 625                        }
 626                        try {
 627                            restoredFromDatabaseLatch.await();
 628                            sendReadMarker(c, null);
 629                        } catch (InterruptedException e) {
 630                            Log.d(Config.LOGTAG, "unable to process notification read marker for conversation " + c.getName());
 631                        }
 632
 633                    });
 634                    break;
 635                case ACTION_SNOOZE:
 636                    mNotificationExecutor.execute(() -> {
 637                        final Conversation c = findConversationByUuid(uuid);
 638                        if (c == null) {
 639                            Log.d(Config.LOGTAG, "received snooze intent for unknown conversation (" + uuid + ")");
 640                            return;
 641                        }
 642                        c.setMutedTill(System.currentTimeMillis() + 30 * 60 * 1000);
 643                        mNotificationService.clear(c);
 644                        updateConversation(c);
 645                    });
 646                case AudioManager.RINGER_MODE_CHANGED_ACTION:
 647                case NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED:
 648                    if (dndOnSilentMode()) {
 649                        refreshAllPresences();
 650                    }
 651                    break;
 652                case Intent.ACTION_SCREEN_ON:
 653                    deactivateGracePeriod();
 654                case Intent.ACTION_SCREEN_OFF:
 655                    if (awayWhenScreenOff()) {
 656                        refreshAllPresences();
 657                    }
 658                    break;
 659                case ACTION_FCM_TOKEN_REFRESH:
 660                    refreshAllFcmTokens();
 661                    break;
 662                case ACTION_IDLE_PING:
 663                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 664                        scheduleNextIdlePing();
 665                    }
 666                    break;
 667                case ACTION_FCM_MESSAGE_RECEIVED:
 668                    pushedAccountHash = intent.getStringExtra("account");
 669                    Log.d(Config.LOGTAG, "push message arrived in service. account=" + pushedAccountHash);
 670                    break;
 671                case Intent.ACTION_SEND:
 672                    Uri uri = intent.getData();
 673                    if (uri != null) {
 674                        Log.d(Config.LOGTAG, "received uri permission for " + uri.toString());
 675                    }
 676                    return START_STICKY;
 677            }
 678        }
 679        synchronized (this) {
 680            WakeLockHelper.acquire(wakeLock);
 681            boolean pingNow = ConnectivityManager.CONNECTIVITY_ACTION.equals(action);
 682            HashSet<Account> pingCandidates = new HashSet<>();
 683            for (Account account : accounts) {
 684                pingNow |= processAccountState(account,
 685                        interactive,
 686                        "ui".equals(action),
 687                        CryptoHelper.getAccountFingerprint(account, PhoneHelper.getAndroidId(this)).equals(pushedAccountHash),
 688                        pingCandidates);
 689            }
 690            if (pingNow) {
 691                for (Account account : pingCandidates) {
 692                    final boolean lowTimeout = isInLowPingTimeoutMode(account);
 693                    account.getXmppConnection().sendPing();
 694                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + " send ping (action=" + action + ",lowTimeout=" + Boolean.toString(lowTimeout) + ")");
 695                    scheduleWakeUpCall(lowTimeout ? Config.LOW_PING_TIMEOUT : Config.PING_TIMEOUT, account.getUuid().hashCode());
 696                }
 697            }
 698            WakeLockHelper.release(wakeLock);
 699        }
 700        if (SystemClock.elapsedRealtime() - mLastExpiryRun.get() >= Config.EXPIRY_INTERVAL) {
 701            expireOldMessages();
 702        }
 703        return START_STICKY;
 704    }
 705
 706    private boolean processAccountState(Account account, boolean interactive, boolean isUiAction, boolean isAccountPushed, HashSet<Account> pingCandidates) {
 707        boolean pingNow = false;
 708        if (account.getStatus().isAttemptReconnect()) {
 709            if (!hasInternetConnection()) {
 710                account.setStatus(Account.State.NO_INTERNET);
 711                if (statusListener != null) {
 712                    statusListener.onStatusChanged(account);
 713                }
 714            } else {
 715                if (account.getStatus() == Account.State.NO_INTERNET) {
 716                    account.setStatus(Account.State.OFFLINE);
 717                    if (statusListener != null) {
 718                        statusListener.onStatusChanged(account);
 719                    }
 720                }
 721                if (account.getStatus() == Account.State.ONLINE) {
 722                    synchronized (mLowPingTimeoutMode) {
 723                        long lastReceived = account.getXmppConnection().getLastPacketReceived();
 724                        long lastSent = account.getXmppConnection().getLastPingSent();
 725                        long pingInterval = isUiAction ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
 726                        long msToNextPing = (Math.max(lastReceived, lastSent) + pingInterval) - SystemClock.elapsedRealtime();
 727                        int pingTimeout = mLowPingTimeoutMode.contains(account.getJid().asBareJid()) ? Config.LOW_PING_TIMEOUT * 1000 : Config.PING_TIMEOUT * 1000;
 728                        long pingTimeoutIn = (lastSent + pingTimeout) - SystemClock.elapsedRealtime();
 729                        if (lastSent > lastReceived) {
 730                            if (pingTimeoutIn < 0) {
 731                                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ping timeout");
 732                                this.reconnectAccount(account, true, interactive);
 733                            } else {
 734                                int secs = (int) (pingTimeoutIn / 1000);
 735                                this.scheduleWakeUpCall(secs, account.getUuid().hashCode());
 736                            }
 737                        } else {
 738                            pingCandidates.add(account);
 739                            if (isAccountPushed) {
 740                                pingNow = true;
 741                                if (mLowPingTimeoutMode.add(account.getJid().asBareJid())) {
 742                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": entering low ping timeout mode");
 743                                }
 744                            } else if (msToNextPing <= 0) {
 745                                pingNow = true;
 746                            } else {
 747                                this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
 748                                if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
 749                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": leaving low ping timeout mode");
 750                                }
 751                            }
 752                        }
 753                    }
 754                } else if (account.getStatus() == Account.State.OFFLINE) {
 755                    reconnectAccount(account, true, interactive);
 756                } else if (account.getStatus() == Account.State.CONNECTING) {
 757                    long secondsSinceLastConnect = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000;
 758                    long secondsSinceLastDisco = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastDiscoStarted()) / 1000;
 759                    long discoTimeout = Config.CONNECT_DISCO_TIMEOUT - secondsSinceLastDisco;
 760                    long timeout = Config.CONNECT_TIMEOUT - secondsSinceLastConnect;
 761                    if (timeout < 0) {
 762                        Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting (secondsSinceLast=" + secondsSinceLastConnect + ")");
 763                        account.getXmppConnection().resetAttemptCount(false);
 764                        reconnectAccount(account, true, interactive);
 765                    } else if (discoTimeout < 0) {
 766                        account.getXmppConnection().sendDiscoTimeout();
 767                        scheduleWakeUpCall((int) Math.min(timeout, discoTimeout), account.getUuid().hashCode());
 768                    } else {
 769                        scheduleWakeUpCall((int) Math.min(timeout, discoTimeout), account.getUuid().hashCode());
 770                    }
 771                } else {
 772                    if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
 773                        reconnectAccount(account, true, interactive);
 774                    }
 775                }
 776            }
 777        }
 778        return pingNow;
 779    }
 780
 781    public boolean isDataSaverDisabled() {
 782        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 783            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
 784            return !connectivityManager.isActiveNetworkMetered()
 785                    || connectivityManager.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
 786        } else {
 787            return true;
 788        }
 789    }
 790
 791    private void directReply(Conversation conversation, String body, final boolean dismissAfterReply) {
 792        Message message = new Message(conversation, body, conversation.getNextEncryption());
 793        message.markUnread();
 794        if (message.getEncryption() == Message.ENCRYPTION_PGP) {
 795            getPgpEngine().encrypt(message, new UiCallback<Message>() {
 796                @Override
 797                public void success(Message message) {
 798                    message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 799                    sendMessage(message);
 800                    if (dismissAfterReply) {
 801                        markRead((Conversation) message.getConversation(), true);
 802                    } else {
 803                        mNotificationService.pushFromDirectReply(message);
 804                    }
 805                }
 806
 807                @Override
 808                public void error(int errorCode, Message object) {
 809
 810                }
 811
 812                @Override
 813                public void userInputRequried(PendingIntent pi, Message object) {
 814
 815                }
 816            });
 817        } else {
 818            sendMessage(message);
 819            if (dismissAfterReply) {
 820                markRead(conversation, true);
 821            } else {
 822                mNotificationService.pushFromDirectReply(message);
 823            }
 824        }
 825    }
 826
 827    private boolean dndOnSilentMode() {
 828        return getBooleanPreference(SettingsActivity.DND_ON_SILENT_MODE, R.bool.dnd_on_silent_mode);
 829    }
 830
 831    private boolean manuallyChangePresence() {
 832        return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
 833    }
 834
 835    private boolean treatVibrateAsSilent() {
 836        return getBooleanPreference(SettingsActivity.TREAT_VIBRATE_AS_SILENT, R.bool.treat_vibrate_as_silent);
 837    }
 838
 839    private boolean awayWhenScreenOff() {
 840        return getBooleanPreference(SettingsActivity.AWAY_WHEN_SCREEN_IS_OFF, R.bool.away_when_screen_off);
 841    }
 842
 843    private String getCompressPicturesPreference() {
 844        return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression));
 845    }
 846
 847    private Presence.Status getTargetPresence() {
 848        if (dndOnSilentMode() && isPhoneSilenced()) {
 849            return Presence.Status.DND;
 850        } else if (awayWhenScreenOff() && !isInteractive()) {
 851            return Presence.Status.AWAY;
 852        } else {
 853            return Presence.Status.ONLINE;
 854        }
 855    }
 856
 857    @SuppressLint("NewApi")
 858    @SuppressWarnings("deprecation")
 859    public boolean isInteractive() {
 860        final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 861
 862        final boolean isScreenOn;
 863        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
 864            isScreenOn = pm.isScreenOn();
 865        } else {
 866            isScreenOn = pm.isInteractive();
 867        }
 868        return isScreenOn;
 869    }
 870
 871    private boolean isPhoneSilenced() {
 872        final boolean notificationDnd;
 873        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 874            final NotificationManager notificationManager = getSystemService(NotificationManager.class);
 875            final int filter = notificationManager == null ? NotificationManager.INTERRUPTION_FILTER_UNKNOWN : notificationManager.getCurrentInterruptionFilter();
 876            notificationDnd = filter >= NotificationManager.INTERRUPTION_FILTER_PRIORITY;
 877        } else {
 878            notificationDnd = false;
 879        }
 880        final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
 881        final int ringerMode = audioManager == null ? AudioManager.RINGER_MODE_NORMAL : audioManager.getRingerMode();
 882        try {
 883            if (treatVibrateAsSilent()) {
 884                return notificationDnd || ringerMode != AudioManager.RINGER_MODE_NORMAL;
 885            } else {
 886                return notificationDnd || ringerMode == AudioManager.RINGER_MODE_SILENT;
 887            }
 888        } catch (Throwable throwable) {
 889            Log.d(Config.LOGTAG, "platform bug in isPhoneSilenced (" + throwable.getMessage() + ")");
 890            return notificationDnd;
 891        }
 892    }
 893
 894    private void resetAllAttemptCounts(boolean reallyAll, boolean retryImmediately) {
 895        Log.d(Config.LOGTAG, "resetting all attempt counts");
 896        for (Account account : accounts) {
 897            if (account.hasErrorStatus() || reallyAll) {
 898                final XmppConnection connection = account.getXmppConnection();
 899                if (connection != null) {
 900                    connection.resetAttemptCount(retryImmediately);
 901                }
 902            }
 903            if (account.setShowErrorNotification(true)) {
 904                databaseBackend.updateAccount(account);
 905            }
 906        }
 907        mNotificationService.updateErrorNotification();
 908    }
 909
 910    private void dismissErrorNotifications() {
 911        for (final Account account : this.accounts) {
 912            if (account.hasErrorStatus()) {
 913                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": dismissing error notification");
 914                if (account.setShowErrorNotification(false)) {
 915                    databaseBackend.updateAccount(account);
 916                }
 917            }
 918        }
 919    }
 920
 921    private void expireOldMessages() {
 922        expireOldMessages(false);
 923    }
 924
 925    public void expireOldMessages(final boolean resetHasMessagesLeftOnServer) {
 926        mLastExpiryRun.set(SystemClock.elapsedRealtime());
 927        mDatabaseWriterExecutor.execute(() -> {
 928            long timestamp = getAutomaticMessageDeletionDate();
 929            if (timestamp > 0) {
 930                databaseBackend.expireOldMessages(timestamp);
 931                synchronized (XmppConnectionService.this.conversations) {
 932                    for (Conversation conversation : XmppConnectionService.this.conversations) {
 933                        conversation.expireOldMessages(timestamp);
 934                        if (resetHasMessagesLeftOnServer) {
 935                            conversation.messagesLoaded.set(true);
 936                            conversation.setHasMessagesLeftOnServer(true);
 937                        }
 938                    }
 939                }
 940                updateConversationUi();
 941            }
 942        });
 943    }
 944
 945    public boolean hasInternetConnection() {
 946        final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
 947        try {
 948            final NetworkInfo activeNetwork = cm == null ? null : cm.getActiveNetworkInfo();
 949            return activeNetwork != null && (activeNetwork.isConnected() || activeNetwork.getType() == ConnectivityManager.TYPE_ETHERNET);
 950        } catch (RuntimeException e) {
 951            Log.d(Config.LOGTAG, "unable to check for internet connection", e);
 952            return true; //if internet connection can not be checked it is probably best to just try
 953        }
 954    }
 955
 956    @SuppressLint("TrulyRandom")
 957    @Override
 958    public void onCreate() {
 959        OmemoSetting.load(this);
 960        ExceptionHelper.init(getApplicationContext());
 961        Security.insertProviderAt(Conscrypt.newProvider(), 1);
 962        Resolver.init(this);
 963        this.mRandom = new SecureRandom();
 964        updateMemorizingTrustmanager();
 965        if (Compatibility.runsTwentySix()) {
 966            mNotificationService.initializeChannels();
 967        }
 968        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
 969        final int cacheSize = maxMemory / 8;
 970        this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
 971            @Override
 972            protected int sizeOf(final String key, final Bitmap bitmap) {
 973                return bitmap.getByteCount() / 1024;
 974            }
 975        };
 976        if (mLastActivity == 0) {
 977            mLastActivity = getPreferences().getLong(SETTING_LAST_ACTIVITY_TS, System.currentTimeMillis());
 978        }
 979
 980        Log.d(Config.LOGTAG, "initializing database...");
 981        this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
 982        Log.d(Config.LOGTAG, "restoring accounts...");
 983        this.accounts = databaseBackend.getAccounts();
 984        final SharedPreferences.Editor editor = getPreferences().edit();
 985        if (this.accounts.size() == 0 && Arrays.asList("Sony", "Sony Ericsson").contains(Build.MANUFACTURER)) {
 986            editor.putBoolean(SettingsActivity.KEEP_FOREGROUND_SERVICE, true);
 987            Log.d(Config.LOGTAG, Build.MANUFACTURER + " is on blacklist. enabling foreground service");
 988        }
 989        editor.putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts()).apply();
 990        editor.apply();
 991
 992        restoreFromDatabase();
 993
 994        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
 995            startContactObserver();
 996        }
 997        if (Compatibility.hasStoragePermission(this)) {
 998            Log.d(Config.LOGTAG, "starting file observer");
 999            new Thread(fileObserver::startWatching).start();
1000        }
1001        if (Config.supportOpenPgp()) {
1002            this.pgpServiceConnection = new OpenPgpServiceConnection(this, "org.sufficientlysecure.keychain", new OpenPgpServiceConnection.OnBound() {
1003                @Override
1004                public void onBound(IOpenPgpService2 service) {
1005                    for (Account account : accounts) {
1006                        final PgpDecryptionService pgp = account.getPgpDecryptionService();
1007                        if (pgp != null) {
1008                            pgp.continueDecryption(true);
1009                        }
1010                    }
1011                }
1012
1013                @Override
1014                public void onError(Exception e) {
1015                }
1016            });
1017            this.pgpServiceConnection.bindToService();
1018        }
1019
1020        this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
1021        this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "XmppConnectionService");
1022
1023        toggleForegroundService();
1024        updateUnreadCountBadge();
1025        toggleScreenEventReceiver();
1026        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1027            scheduleNextIdlePing();
1028            IntentFilter intentFilter = new IntentFilter();
1029            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1030                intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1031            }
1032            intentFilter.addAction(NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED);
1033            registerReceiver(this.mInternalEventReceiver, intentFilter);
1034        }
1035    }
1036
1037    public void startContactObserver() {
1038        getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, new ContentObserver(null) {
1039            @Override
1040            public void onChange(boolean selfChange) {
1041                super.onChange(selfChange);
1042                if (restoredFromDatabaseLatch.getCount() == 0) {
1043                    loadPhoneContacts();
1044                }
1045            }
1046        });
1047    }
1048
1049    @Override
1050    public void onTrimMemory(int level) {
1051        super.onTrimMemory(level);
1052        if (level >= TRIM_MEMORY_COMPLETE) {
1053            Log.d(Config.LOGTAG, "clear cache due to low memory");
1054            getBitmapCache().evictAll();
1055        }
1056    }
1057
1058    @Override
1059    public void onDestroy() {
1060        try {
1061            unregisterReceiver(this.mInternalEventReceiver);
1062        } catch (IllegalArgumentException e) {
1063            //ignored
1064        }
1065        fileObserver.stopWatching();
1066        super.onDestroy();
1067    }
1068
1069    public void restartFileObserver() {
1070        Log.d(Config.LOGTAG, "restarting file observer");
1071        new Thread(fileObserver::restartWatching).start();
1072    }
1073
1074    public void toggleScreenEventReceiver() {
1075        if (awayWhenScreenOff() && !manuallyChangePresence()) {
1076            final IntentFilter filter = new IntentFilter();
1077            filter.addAction(Intent.ACTION_SCREEN_ON);
1078            filter.addAction(Intent.ACTION_SCREEN_OFF);
1079            registerReceiver(this.mInternalScreenEventReceiver, filter);
1080        } else {
1081            try {
1082                unregisterReceiver(this.mInternalScreenEventReceiver);
1083            } catch (IllegalArgumentException e) {
1084                //ignored
1085            }
1086        }
1087    }
1088
1089    public void toggleForegroundService() {
1090        final boolean status;
1091        if (mForceForegroundService.get() || (Compatibility.keepForegroundService(this) && hasEnabledAccounts())) {
1092            startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
1093            status = true;
1094        } else {
1095            stopForeground(true);
1096            status = false;
1097        }
1098        mNotificationService.dismissForcedForegroundNotification(); //if the channel was changed the previous call might fail
1099        Log.d(Config.LOGTAG,"ForegroundService: "+(status?"on":"off"));
1100    }
1101
1102    @Override
1103    public void onTaskRemoved(final Intent rootIntent) {
1104        super.onTaskRemoved(rootIntent);
1105        if ((Compatibility.keepForegroundService(this) && hasEnabledAccounts()) || mForceForegroundService.get()) {
1106            Log.d(Config.LOGTAG, "ignoring onTaskRemoved because foreground service is activated");
1107        } else {
1108            this.logoutAndSave(false);
1109        }
1110    }
1111
1112    private void logoutAndSave(boolean stop) {
1113        int activeAccounts = 0;
1114        for (final Account account : accounts) {
1115            if (account.getStatus() != Account.State.DISABLED) {
1116                databaseBackend.writeRoster(account.getRoster());
1117                activeAccounts++;
1118            }
1119            if (account.getXmppConnection() != null) {
1120                new Thread(() -> disconnect(account, false)).start();
1121            }
1122        }
1123        if (stop || activeAccounts == 0) {
1124            Log.d(Config.LOGTAG, "good bye");
1125            stopSelf();
1126        }
1127    }
1128
1129    public void scheduleWakeUpCall(int seconds, int requestCode) {
1130        final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
1131        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1132        if (alarmManager == null) {
1133            return;
1134        }
1135        final Intent intent = new Intent(this, EventReceiver.class);
1136        intent.setAction("ping");
1137        try {
1138            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, requestCode, intent, 0);
1139            alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1140        } catch (RuntimeException e) {
1141            Log.e(Config.LOGTAG, "unable to schedule alarm for ping", e);
1142        }
1143    }
1144
1145    @TargetApi(Build.VERSION_CODES.M)
1146    private void scheduleNextIdlePing() {
1147        final long timeToWake = SystemClock.elapsedRealtime() + (Config.IDLE_PING_INTERVAL * 1000);
1148        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1149        if (alarmManager == null) {
1150            return;
1151        }
1152        final Intent intent = new Intent(this, EventReceiver.class);
1153        intent.setAction(ACTION_IDLE_PING);
1154        try {
1155            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
1156            alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1157        } catch (RuntimeException e) {
1158            Log.d(Config.LOGTAG, "unable to schedule alarm for idle ping", e);
1159        }
1160    }
1161
1162    public XmppConnection createConnection(final Account account) {
1163        final XmppConnection connection = new XmppConnection(account, this);
1164        connection.setOnMessagePacketReceivedListener(this.mMessageParser);
1165        connection.setOnStatusChangedListener(this.statusListener);
1166        connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
1167        connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
1168        connection.setOnJinglePacketReceivedListener(this.jingleListener);
1169        connection.setOnBindListener(this.mOnBindListener);
1170        connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
1171        connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
1172        connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
1173        AxolotlService axolotlService = account.getAxolotlService();
1174        if (axolotlService != null) {
1175            connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
1176        }
1177        return connection;
1178    }
1179
1180    public void sendChatState(Conversation conversation) {
1181        if (sendChatStates()) {
1182            MessagePacket packet = mMessageGenerator.generateChatState(conversation);
1183            sendMessagePacket(conversation.getAccount(), packet);
1184        }
1185    }
1186
1187    private void sendFileMessage(final Message message, final boolean delay) {
1188        Log.d(Config.LOGTAG, "send file message");
1189        final Account account = message.getConversation().getAccount();
1190        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1191                || message.getConversation().getMode() == Conversation.MODE_MULTI) {
1192            mHttpConnectionManager.createNewUploadConnection(message, delay);
1193        } else {
1194            mJingleConnectionManager.createNewConnection(message);
1195        }
1196    }
1197
1198    public void sendMessage(final Message message) {
1199        sendMessage(message, false, false);
1200    }
1201
1202    private void sendMessage(final Message message, final boolean resend, final boolean delay) {
1203        final Account account = message.getConversation().getAccount();
1204        if (account.setShowErrorNotification(true)) {
1205            databaseBackend.updateAccount(account);
1206            mNotificationService.updateErrorNotification();
1207        }
1208        final Conversation conversation = (Conversation) message.getConversation();
1209        account.deactivateGracePeriod();
1210        MessagePacket packet = null;
1211        final boolean addToConversation = (conversation.getMode() != Conversation.MODE_MULTI
1212                || !Patches.BAD_MUC_REFLECTION.contains(account.getServerIdentity()))
1213                && !message.edited();
1214        boolean saveInDb = addToConversation;
1215        message.setStatus(Message.STATUS_WAITING);
1216
1217        if (account.isOnlineAndConnected()) {
1218            switch (message.getEncryption()) {
1219                case Message.ENCRYPTION_NONE:
1220                    if (message.needsUploading()) {
1221                        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1222                                || conversation.getMode() == Conversation.MODE_MULTI
1223                                || message.fixCounterpart()) {
1224                            this.sendFileMessage(message, delay);
1225                        } else {
1226                            break;
1227                        }
1228                    } else {
1229                        packet = mMessageGenerator.generateChat(message);
1230                    }
1231                    break;
1232                case Message.ENCRYPTION_PGP:
1233                case Message.ENCRYPTION_DECRYPTED:
1234                    if (message.needsUploading()) {
1235                        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1236                                || conversation.getMode() == Conversation.MODE_MULTI
1237                                || message.fixCounterpart()) {
1238                            this.sendFileMessage(message, delay);
1239                        } else {
1240                            break;
1241                        }
1242                    } else {
1243                        packet = mMessageGenerator.generatePgpChat(message);
1244                    }
1245                    break;
1246                case Message.ENCRYPTION_AXOLOTL:
1247                    message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1248                    if (message.needsUploading()) {
1249                        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1250                                || conversation.getMode() == Conversation.MODE_MULTI
1251                                || message.fixCounterpart()) {
1252                            this.sendFileMessage(message, delay);
1253                        } else {
1254                            break;
1255                        }
1256                    } else {
1257                        XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
1258                        if (axolotlMessage == null) {
1259                            account.getAxolotlService().preparePayloadMessage(message, delay);
1260                        } else {
1261                            packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
1262                        }
1263                    }
1264                    break;
1265
1266            }
1267            if (packet != null) {
1268                if (account.getXmppConnection().getFeatures().sm()
1269                        || (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1270                    message.setStatus(Message.STATUS_UNSEND);
1271                } else {
1272                    message.setStatus(Message.STATUS_SEND);
1273                }
1274            }
1275        } else {
1276            switch (message.getEncryption()) {
1277                case Message.ENCRYPTION_DECRYPTED:
1278                    if (!message.needsUploading()) {
1279                        String pgpBody = message.getEncryptedBody();
1280                        String decryptedBody = message.getBody();
1281                        message.setBody(pgpBody); //TODO might throw NPE
1282                        message.setEncryption(Message.ENCRYPTION_PGP);
1283                        if (message.edited()) {
1284                            message.setBody(decryptedBody);
1285                            message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1286                            databaseBackend.updateMessage(message, message.getEditedId());
1287                            updateConversationUi();
1288                            return;
1289                        } else {
1290                            databaseBackend.createMessage(message);
1291                            saveInDb = false;
1292                            message.setBody(decryptedBody);
1293                            message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1294                        }
1295                    }
1296                    break;
1297                case Message.ENCRYPTION_AXOLOTL:
1298                    message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1299                    break;
1300            }
1301        }
1302
1303
1304        boolean mucMessage = conversation.getMode() == Conversation.MODE_MULTI && message.getType() != Message.TYPE_PRIVATE;
1305        if (mucMessage) {
1306            message.setCounterpart(conversation.getMucOptions().getSelf().getFullJid());
1307        }
1308
1309        if (resend) {
1310            if (packet != null && addToConversation) {
1311                if (account.getXmppConnection().getFeatures().sm() || mucMessage) {
1312                    markMessage(message, Message.STATUS_UNSEND);
1313                } else {
1314                    markMessage(message, Message.STATUS_SEND);
1315                }
1316            }
1317        } else {
1318            if (addToConversation) {
1319                conversation.add(message);
1320            }
1321            if (saveInDb) {
1322                databaseBackend.createMessage(message);
1323            } else if (message.edited()) {
1324                databaseBackend.updateMessage(message, message.getEditedId());
1325            }
1326            updateConversationUi();
1327        }
1328        if (packet != null) {
1329            if (delay) {
1330                mMessageGenerator.addDelay(packet, message.getTimeSent());
1331            }
1332            if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1333                if (this.sendChatStates()) {
1334                    packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
1335                }
1336            }
1337            sendMessagePacket(account, packet);
1338        }
1339    }
1340
1341    private void sendUnsentMessages(final Conversation conversation) {
1342        conversation.findWaitingMessages(message -> resendMessage(message, true));
1343    }
1344
1345    public void resendMessage(final Message message, final boolean delay) {
1346        sendMessage(message, true, delay);
1347    }
1348
1349    public void fetchRosterFromServer(final Account account) {
1350        final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1351        if (!"".equals(account.getRosterVersion())) {
1352            Log.d(Config.LOGTAG, account.getJid().asBareJid()
1353                    + ": fetching roster version " + account.getRosterVersion());
1354        } else {
1355            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching roster");
1356        }
1357        iqPacket.query(Namespace.ROSTER).setAttribute("ver", account.getRosterVersion());
1358        sendIqPacket(account, iqPacket, mIqParser);
1359    }
1360
1361    public void fetchBookmarks(final Account account) {
1362        final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1363        final Element query = iqPacket.query("jabber:iq:private");
1364        query.addChild("storage", Namespace.BOOKMARKS);
1365        final OnIqPacketReceived callback = (a, response) -> {
1366            if (response.getType() == IqPacket.TYPE.RESULT) {
1367                final Element query1 = response.query();
1368                final Element storage = query1.findChild("storage", "storage:bookmarks");
1369                processBookmarks(a, storage);
1370            } else {
1371                Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": could not fetch bookmarks");
1372            }
1373        };
1374        sendIqPacket(account, iqPacket, callback);
1375    }
1376
1377    public void processBookmarks(Account account, Element storage) {
1378        final HashMap<Jid, Bookmark> bookmarks = new HashMap<>();
1379        final boolean autojoin = respectAutojoin();
1380        if (storage != null) {
1381            for (final Element item : storage.getChildren()) {
1382                if (item.getName().equals("conference")) {
1383                    final Bookmark bookmark = Bookmark.parse(item, account);
1384                    Bookmark old = bookmarks.put(bookmark.getJid(), bookmark);
1385                    if (old != null && old.getBookmarkName() != null && bookmark.getBookmarkName() == null) {
1386                        bookmark.setBookmarkName(old.getBookmarkName());
1387                    }
1388                    Conversation conversation = find(bookmark);
1389                    if (conversation != null) {
1390                        bookmark.setConversation(conversation);
1391                    } else if (bookmark.autojoin() && bookmark.getJid() != null && autojoin) {
1392                        conversation = findOrCreateConversation(account, bookmark.getJid(), true, true, false);
1393                        bookmark.setConversation(conversation);
1394                    }
1395                }
1396            }
1397        }
1398        account.setBookmarks(new CopyOnWriteArrayList<>(bookmarks.values()));
1399    }
1400
1401    public void pushBookmarks(Account account) {
1402        if (account.getXmppConnection().getFeatures().bookmarksConversion()) {
1403            pushBookmarksPep(account);
1404        } else {
1405            pushBookmarksPrivateXml(account);
1406        }
1407    }
1408
1409    private void pushBookmarksPrivateXml(Account account) {
1410        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
1411        IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1412        Element query = iqPacket.query("jabber:iq:private");
1413        Element storage = query.addChild("storage", "storage:bookmarks");
1414        for (Bookmark bookmark : account.getBookmarks()) {
1415            storage.addChild(bookmark);
1416        }
1417        sendIqPacket(account, iqPacket, mDefaultIqHandler);
1418    }
1419
1420    private void pushBookmarksPep(Account account) {
1421        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
1422        Element storage = new Element("storage", "storage:bookmarks");
1423        for (Bookmark bookmark : account.getBookmarks()) {
1424            storage.addChild(bookmark);
1425        }
1426        pushNodeAndEnforcePublishOptions(account,Namespace.BOOKMARKS,storage, PublishOptions.persistentWhitelistAccess());
1427
1428    }
1429
1430
1431    private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final Bundle options) {
1432        pushNodeAndEnforcePublishOptions(account, node, element, options, true);
1433
1434    }
1435
1436	private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final Bundle options, final boolean retry) {
1437        IqPacket packet = mIqGenerator.publishElement(node, element, options);
1438        Log.d(Config.LOGTAG,packet.toString());
1439        sendIqPacket(account, packet, (a, response) -> {
1440            if (response.getType() == IqPacket.TYPE.RESULT) {
1441                return;
1442            }
1443            final Element error = response.getType() == IqPacket.TYPE.ERROR ? response.findChild("error") : null;
1444            final boolean preconditionNotMet = error != null && error.hasChild("precondition-not-met", Namespace.PUBSUB_ERROR);
1445            if (retry && preconditionNotMet) {
1446                pushNodeConfiguration(account, node, options, new OnConfigurationPushed() {
1447                    @Override
1448                    public void onPushSucceeded() {
1449                        pushNodeAndEnforcePublishOptions(account, node, element, options, false);
1450                    }
1451
1452                    @Override
1453                    public void onPushFailed() {
1454                        Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to push node configuration ("+node+")");
1455                    }
1456                });
1457            } else {
1458                Log.d(Config.LOGTAG,account.getJid().asBareJid()+": error publishing bookmarks (retry="+Boolean.toString(retry)+") "+response);
1459            }
1460        });
1461    }
1462
1463	private void restoreFromDatabase() {
1464		synchronized (this.conversations) {
1465			final Map<String, Account> accountLookupTable = new Hashtable<>();
1466			for (Account account : this.accounts) {
1467				accountLookupTable.put(account.getUuid(), account);
1468			}
1469			Log.d(Config.LOGTAG, "restoring conversations...");
1470			final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
1471			this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1472			for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
1473				Conversation conversation = iterator.next();
1474				Account account = accountLookupTable.get(conversation.getAccountUuid());
1475				if (account != null) {
1476					conversation.setAccount(account);
1477				} else {
1478					Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
1479					iterator.remove();
1480				}
1481			}
1482			long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
1483			Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
1484			Runnable runnable = () -> {
1485				long deletionDate = getAutomaticMessageDeletionDate();
1486				mLastExpiryRun.set(SystemClock.elapsedRealtime());
1487				if (deletionDate > 0) {
1488					Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
1489					databaseBackend.expireOldMessages(deletionDate);
1490				}
1491				Log.d(Config.LOGTAG, "restoring roster...");
1492				for (Account account : accounts) {
1493					databaseBackend.readRoster(account.getRoster());
1494					account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1495				}
1496				getBitmapCache().evictAll();
1497				loadPhoneContacts();
1498				Log.d(Config.LOGTAG, "restoring messages...");
1499				final long startMessageRestore = SystemClock.elapsedRealtime();
1500				final Conversation quickLoad = QuickLoader.get(this.conversations);
1501				if (quickLoad != null) {
1502					restoreMessages(quickLoad);
1503					updateConversationUi();
1504					final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1505					Log.d(Config.LOGTAG,"quickly restored "+quickLoad.getName()+" after " + diffMessageRestore + "ms");
1506				}
1507				for (Conversation conversation : this.conversations) {
1508					if (quickLoad != conversation) {
1509						restoreMessages(conversation);
1510					}
1511				}
1512				mNotificationService.finishBacklog(false);
1513				restoredFromDatabaseLatch.countDown();
1514				final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1515				Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
1516				updateConversationUi();
1517			};
1518			mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
1519		}
1520	}
1521
1522	private void restoreMessages(Conversation conversation) {
1523		conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1524		checkDeletedFiles(conversation);
1525		conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
1526		conversation.findUnreadMessages(message -> mNotificationService.pushFromBacklog(message));
1527	}
1528
1529	public void loadPhoneContacts() {
1530		mContactMergerExecutor.execute(() -> PhoneHelper.loadPhoneContacts(XmppConnectionService.this, new OnPhoneContactsLoadedListener() {
1531			@Override
1532			public void onPhoneContactsLoaded(List<Bundle> phoneContacts) {
1533				Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1534				for (Account account : accounts) {
1535					List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
1536					for (Bundle phoneContact : phoneContacts) {
1537						Jid jid;
1538						try {
1539							jid = Jid.of(phoneContact.getString("jid"));
1540						} catch (final IllegalArgumentException e) {
1541							continue;
1542						}
1543						final Contact contact = account.getRoster().getContact(jid);
1544						String systemAccount = phoneContact.getInt("phoneid")
1545								+ "#"
1546								+ phoneContact.getString("lookup");
1547						contact.setSystemAccount(systemAccount);
1548						boolean needsCacheClean = contact.setPhotoUri(phoneContact.getString("photouri"));
1549						needsCacheClean |= contact.setSystemName(phoneContact.getString("displayname"));
1550						if (needsCacheClean) {
1551							getAvatarService().clear(contact);
1552						}
1553						withSystemAccounts.remove(contact);
1554					}
1555					for (Contact contact : withSystemAccounts) {
1556						contact.setSystemAccount(null);
1557						boolean needsCacheClean = contact.setPhotoUri(null);
1558						needsCacheClean |= contact.setSystemName(null);
1559						if (needsCacheClean) {
1560							getAvatarService().clear(contact);
1561						}
1562					}
1563				}
1564				Log.d(Config.LOGTAG, "finished merging phone contacts");
1565				mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
1566				updateRosterUi();
1567			}
1568		}));
1569	}
1570
1571
1572	public void syncRoster(final Account account) {
1573		mRosterSyncTaskManager.execute(account, () -> databaseBackend.writeRoster(account.getRoster()));
1574	}
1575
1576	public List<Conversation> getConversations() {
1577		return this.conversations;
1578	}
1579
1580	private void checkDeletedFiles(Conversation conversation) {
1581		conversation.findMessagesWithFiles(message -> {
1582			if (!getFileBackend().isFileAvailable(message)) {
1583				message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1584				final int s = message.getStatus();
1585				if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1586					markMessage(message, Message.STATUS_SEND_FAILED);
1587				}
1588			}
1589		});
1590	}
1591
1592	private void markFileDeleted(final String path) {
1593		Log.d(Config.LOGTAG, "deleted file " + path);
1594		for (Conversation conversation : getConversations()) {
1595			conversation.findMessagesWithFiles(message -> {
1596				DownloadableFile file = fileBackend.getFile(message);
1597				if (file.getAbsolutePath().equals(path)) {
1598					if (!file.exists()) {
1599						message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1600						final int s = message.getStatus();
1601						if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1602							markMessage(message, Message.STATUS_SEND_FAILED);
1603						} else {
1604							updateConversationUi();
1605						}
1606					} else {
1607						Log.d(Config.LOGTAG, "found matching message for file " + path + " but file still exists");
1608					}
1609				}
1610			});
1611		}
1612	}
1613
1614	public void populateWithOrderedConversations(final List<Conversation> list) {
1615		populateWithOrderedConversations(list, true);
1616	}
1617
1618	public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1619		list.clear();
1620		if (includeNoFileUpload) {
1621			list.addAll(getConversations());
1622		} else {
1623			for (Conversation conversation : getConversations()) {
1624				if (conversation.getMode() == Conversation.MODE_SINGLE
1625						|| (conversation.getAccount().httpUploadAvailable() && conversation.getMucOptions().participating())) {
1626					list.add(conversation);
1627				}
1628			}
1629		}
1630		try {
1631			Collections.sort(list);
1632		} catch (IllegalArgumentException e) {
1633			//ignore
1634		}
1635	}
1636
1637	public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1638		if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
1639			return;
1640		} else if (timestamp == 0) {
1641			return;
1642		}
1643		Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1644		final Runnable runnable = () -> {
1645			final Account account = conversation.getAccount();
1646			List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
1647			if (messages.size() > 0) {
1648				conversation.addAll(0, messages);
1649				checkDeletedFiles(conversation);
1650				callback.onMoreMessagesLoaded(messages.size(), conversation);
1651			} else if (conversation.hasMessagesLeftOnServer()
1652					&& account.isOnlineAndConnected()
1653					&& conversation.getLastClearHistory().getTimestamp() == 0) {
1654				final boolean mamAvailable;
1655				if (conversation.getMode() == Conversation.MODE_SINGLE) {
1656					mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
1657				} else {
1658					mamAvailable = conversation.getMucOptions().mamSupport();
1659				}
1660				if (mamAvailable) {
1661					MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
1662					if (query != null) {
1663						query.setCallback(callback);
1664						callback.informUser(R.string.fetching_history_from_server);
1665					} else {
1666						callback.informUser(R.string.not_fetching_history_retention_period);
1667					}
1668
1669				}
1670			}
1671		};
1672		mDatabaseReaderExecutor.execute(runnable);
1673	}
1674
1675	public List<Account> getAccounts() {
1676		return this.accounts;
1677	}
1678
1679	public List<Conversation> findAllConferencesWith(Contact contact) {
1680		ArrayList<Conversation> results = new ArrayList<>();
1681		for (final Conversation c : conversations) {
1682			if (c.getMode() == Conversation.MODE_MULTI
1683					&& (c.getJid().asBareJid().equals(c.getJid().asBareJid()) || c.getMucOptions().isContactInRoom(contact))) {
1684				results.add(c);
1685			}
1686		}
1687		return results;
1688	}
1689
1690	public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1691		for (final Conversation conversation : haystack) {
1692			if (conversation.getContact() == contact) {
1693				return conversation;
1694			}
1695		}
1696		return null;
1697	}
1698
1699	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1700		if (jid == null) {
1701			return null;
1702		}
1703		for (final Conversation conversation : haystack) {
1704			if ((account == null || conversation.getAccount() == account)
1705					&& (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
1706				return conversation;
1707			}
1708		}
1709		return null;
1710	}
1711
1712	public boolean isConversationsListEmpty(final Conversation ignore) {
1713		synchronized (this.conversations) {
1714			final int size = this.conversations.size();
1715			return size == 0 || size == 1 && this.conversations.get(0) == ignore;
1716		}
1717	}
1718
1719	public boolean isConversationStillOpen(final Conversation conversation) {
1720		synchronized (this.conversations) {
1721			for (Conversation current : this.conversations) {
1722				if (current == conversation) {
1723					return true;
1724				}
1725			}
1726		}
1727		return false;
1728	}
1729
1730	public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
1731		return this.findOrCreateConversation(account, jid, muc, false, async);
1732	}
1733
1734	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
1735		return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
1736	}
1737
1738	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
1739		synchronized (this.conversations) {
1740			Conversation conversation = find(account, jid);
1741			if (conversation != null) {
1742				return conversation;
1743			}
1744			conversation = databaseBackend.findConversation(account, jid);
1745			final boolean loadMessagesFromDb;
1746			if (conversation != null) {
1747				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1748				conversation.setAccount(account);
1749				if (muc) {
1750					conversation.setMode(Conversation.MODE_MULTI);
1751					conversation.setContactJid(jid);
1752				} else {
1753					conversation.setMode(Conversation.MODE_SINGLE);
1754					conversation.setContactJid(jid.asBareJid());
1755				}
1756				databaseBackend.updateConversation(conversation);
1757				loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
1758			} else {
1759				String conversationName;
1760				Contact contact = account.getRoster().getContact(jid);
1761				if (contact != null) {
1762					conversationName = contact.getDisplayName();
1763				} else {
1764					conversationName = jid.getLocal();
1765				}
1766				if (muc) {
1767					conversation = new Conversation(conversationName, account, jid,
1768							Conversation.MODE_MULTI);
1769				} else {
1770					conversation = new Conversation(conversationName, account, jid.asBareJid(),
1771							Conversation.MODE_SINGLE);
1772				}
1773				this.databaseBackend.createConversation(conversation);
1774				loadMessagesFromDb = false;
1775			}
1776			final Conversation c = conversation;
1777			final Runnable runnable = () -> {
1778				if (loadMessagesFromDb) {
1779					c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
1780					updateConversationUi();
1781					c.messagesLoaded.set(true);
1782				}
1783				if (account.getXmppConnection() != null
1784						&& !c.getContact().isBlocked()
1785						&& account.getXmppConnection().getFeatures().mam()
1786						&& !muc) {
1787					if (query == null) {
1788						mMessageArchiveService.query(c);
1789					} else {
1790						if (query.getConversation() == null) {
1791							mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
1792						}
1793					}
1794				}
1795				checkDeletedFiles(c);
1796				if (joinAfterCreate) {
1797					joinMuc(c);
1798				}
1799			};
1800			if (async) {
1801				mDatabaseReaderExecutor.execute(runnable);
1802			} else {
1803				runnable.run();
1804			}
1805			this.conversations.add(conversation);
1806			updateConversationUi();
1807			return conversation;
1808		}
1809	}
1810
1811	public void archiveConversation(Conversation conversation) {
1812		getNotificationService().clear(conversation);
1813		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1814		conversation.setNextMessage(null);
1815		synchronized (this.conversations) {
1816			getMessageArchiveService().kill(conversation);
1817			if (conversation.getMode() == Conversation.MODE_MULTI) {
1818				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1819					Bookmark bookmark = conversation.getBookmark();
1820					if (bookmark != null && bookmark.autojoin() && respectAutojoin()) {
1821						bookmark.setAutojoin(false);
1822						pushBookmarks(bookmark.getAccount());
1823					}
1824				}
1825				leaveMuc(conversation);
1826			} else {
1827				if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1828					Log.d(Config.LOGTAG, "Canceling presence request from " + conversation.getJid().toString());
1829					sendPresencePacket(
1830							conversation.getAccount(),
1831							mPresenceGenerator.stopPresenceUpdatesTo(conversation.getContact())
1832					);
1833				}
1834			}
1835			updateConversation(conversation);
1836			this.conversations.remove(conversation);
1837			updateConversationUi();
1838		}
1839	}
1840
1841	public void createAccount(final Account account) {
1842		account.initAccountServices(this);
1843		databaseBackend.createAccount(account);
1844		this.accounts.add(account);
1845		this.reconnectAccountInBackground(account);
1846		updateAccountUi();
1847		syncEnabledAccountSetting();
1848		toggleForegroundService();
1849	}
1850
1851	private void syncEnabledAccountSetting() {
1852		getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts()).apply();
1853	}
1854
1855	public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1856		new Thread(() -> {
1857			try {
1858				final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
1859				final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
1860				if (cert == null) {
1861					callback.informUser(R.string.unable_to_parse_certificate);
1862					return;
1863				}
1864				Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
1865				if (info == null) {
1866					callback.informUser(R.string.certificate_does_not_contain_jid);
1867					return;
1868				}
1869				if (findAccountByJid(info.first) == null) {
1870					Account account = new Account(info.first, "");
1871					account.setPrivateKeyAlias(alias);
1872					account.setOption(Account.OPTION_DISABLED, true);
1873					account.setDisplayName(info.second);
1874					createAccount(account);
1875					callback.onAccountCreated(account);
1876					if (Config.X509_VERIFICATION) {
1877						try {
1878							getMemorizingTrustManager().getNonInteractive(account.getJid().getDomain()).checkClientTrusted(chain, "RSA");
1879						} catch (CertificateException e) {
1880							callback.informUser(R.string.certificate_chain_is_not_trusted);
1881						}
1882					}
1883				} else {
1884					callback.informUser(R.string.account_already_exists);
1885				}
1886			} catch (Exception e) {
1887				e.printStackTrace();
1888				callback.informUser(R.string.unable_to_parse_certificate);
1889			}
1890		}).start();
1891
1892	}
1893
1894	public void updateKeyInAccount(final Account account, final String alias) {
1895		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
1896		try {
1897			X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1898			Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
1899			Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1900			if (info == null) {
1901				showErrorToastInUi(R.string.certificate_does_not_contain_jid);
1902				return;
1903			}
1904			if (account.getJid().asBareJid().equals(info.first)) {
1905				account.setPrivateKeyAlias(alias);
1906				account.setDisplayName(info.second);
1907				databaseBackend.updateAccount(account);
1908				if (Config.X509_VERIFICATION) {
1909					try {
1910						getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1911					} catch (CertificateException e) {
1912						showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1913					}
1914					account.getAxolotlService().regenerateKeys(true);
1915				}
1916			} else {
1917				showErrorToastInUi(R.string.jid_does_not_match_certificate);
1918			}
1919		} catch (Exception e) {
1920			e.printStackTrace();
1921		}
1922	}
1923
1924	public boolean updateAccount(final Account account) {
1925		if (databaseBackend.updateAccount(account)) {
1926			account.setShowErrorNotification(true);
1927			this.statusListener.onStatusChanged(account);
1928			databaseBackend.updateAccount(account);
1929			reconnectAccountInBackground(account);
1930			updateAccountUi();
1931			getNotificationService().updateErrorNotification();
1932			toggleForegroundService();
1933			syncEnabledAccountSetting();
1934			return true;
1935		} else {
1936			return false;
1937		}
1938	}
1939
1940	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1941		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1942		sendIqPacket(account, iq, (a, packet) -> {
1943			if (packet.getType() == IqPacket.TYPE.RESULT) {
1944				a.setPassword(newPassword);
1945				a.setOption(Account.OPTION_MAGIC_CREATE, false);
1946				databaseBackend.updateAccount(a);
1947				callback.onPasswordChangeSucceeded();
1948			} else {
1949				callback.onPasswordChangeFailed();
1950			}
1951		});
1952	}
1953
1954	public void deleteAccount(final Account account) {
1955		synchronized (this.conversations) {
1956			for (final Conversation conversation : conversations) {
1957				if (conversation.getAccount() == account) {
1958					if (conversation.getMode() == Conversation.MODE_MULTI) {
1959						leaveMuc(conversation);
1960					}
1961					conversations.remove(conversation);
1962				}
1963			}
1964			if (account.getXmppConnection() != null) {
1965				new Thread(() -> disconnect(account, true)).start();
1966			}
1967			final Runnable runnable = () -> {
1968				if (!databaseBackend.deleteAccount(account)) {
1969					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
1970				}
1971			};
1972			mDatabaseWriterExecutor.execute(runnable);
1973			this.accounts.remove(account);
1974			this.mRosterSyncTaskManager.clear(account);
1975			updateAccountUi();
1976			getNotificationService().updateErrorNotification();
1977			syncEnabledAccountSetting();
1978			toggleForegroundService();
1979		}
1980	}
1981
1982	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1983		final boolean remainingListeners;
1984		synchronized (LISTENER_LOCK) {
1985			remainingListeners = checkListeners();
1986			if (!this.mOnConversationUpdates.add(listener)) {
1987				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as ConversationListChangedListener");
1988			}
1989			this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
1990		}
1991		if (remainingListeners) {
1992			switchToForeground();
1993		}
1994	}
1995
1996	public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
1997		final boolean remainingListeners;
1998		synchronized (LISTENER_LOCK) {
1999			this.mOnConversationUpdates.remove(listener);
2000			this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2001			remainingListeners = checkListeners();
2002		}
2003		if (remainingListeners) {
2004			switchToBackground();
2005		}
2006	}
2007
2008	public void setOnShowErrorToastListener(OnShowErrorToast listener) {
2009		final boolean remainingListeners;
2010		synchronized (LISTENER_LOCK) {
2011			remainingListeners = checkListeners();
2012			if (!this.mOnShowErrorToasts.add(listener)) {
2013				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnShowErrorToastListener");
2014			}
2015		}
2016		if (remainingListeners) {
2017			switchToForeground();
2018		}
2019	}
2020
2021	public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
2022		final boolean remainingListeners;
2023		synchronized (LISTENER_LOCK) {
2024			this.mOnShowErrorToasts.remove(onShowErrorToast);
2025			remainingListeners = checkListeners();
2026		}
2027		if (remainingListeners) {
2028			switchToBackground();
2029		}
2030	}
2031
2032	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
2033		final boolean remainingListeners;
2034		synchronized (LISTENER_LOCK) {
2035			remainingListeners = checkListeners();
2036			if (!this.mOnAccountUpdates.add(listener)) {
2037				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnAccountListChangedtListener");
2038			}
2039		}
2040		if (remainingListeners) {
2041			switchToForeground();
2042		}
2043	}
2044
2045	public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
2046		final boolean remainingListeners;
2047		synchronized (LISTENER_LOCK) {
2048			this.mOnAccountUpdates.remove(listener);
2049			remainingListeners = checkListeners();
2050		}
2051		if (remainingListeners) {
2052			switchToBackground();
2053		}
2054	}
2055
2056	public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2057		final boolean remainingListeners;
2058		synchronized (LISTENER_LOCK) {
2059			remainingListeners = checkListeners();
2060			if (!this.mOnCaptchaRequested.add(listener)) {
2061				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnCaptchaRequestListener");
2062			}
2063		}
2064		if (remainingListeners) {
2065			switchToForeground();
2066		}
2067	}
2068
2069	public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2070		final boolean remainingListeners;
2071		synchronized (LISTENER_LOCK) {
2072			this.mOnCaptchaRequested.remove(listener);
2073			remainingListeners = checkListeners();
2074		}
2075		if (remainingListeners) {
2076			switchToBackground();
2077		}
2078	}
2079
2080	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
2081		final boolean remainingListeners;
2082		synchronized (LISTENER_LOCK) {
2083			remainingListeners = checkListeners();
2084			if (!this.mOnRosterUpdates.add(listener)) {
2085				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnRosterUpdateListener");
2086			}
2087		}
2088		if (remainingListeners) {
2089			switchToForeground();
2090		}
2091	}
2092
2093	public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
2094		final boolean remainingListeners;
2095		synchronized (LISTENER_LOCK) {
2096			this.mOnRosterUpdates.remove(listener);
2097			remainingListeners = checkListeners();
2098		}
2099		if (remainingListeners) {
2100			switchToBackground();
2101		}
2102	}
2103
2104	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2105		final boolean remainingListeners;
2106		synchronized (LISTENER_LOCK) {
2107			remainingListeners = checkListeners();
2108			if (!this.mOnUpdateBlocklist.add(listener)) {
2109				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnUpdateBlocklistListener");
2110			}
2111		}
2112		if (remainingListeners) {
2113			switchToForeground();
2114		}
2115	}
2116
2117	public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2118		final boolean remainingListeners;
2119		synchronized (LISTENER_LOCK) {
2120			this.mOnUpdateBlocklist.remove(listener);
2121			remainingListeners = checkListeners();
2122		}
2123		if (remainingListeners) {
2124			switchToBackground();
2125		}
2126	}
2127
2128	public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2129		final boolean remainingListeners;
2130		synchronized (LISTENER_LOCK) {
2131			remainingListeners = checkListeners();
2132			if (!this.mOnKeyStatusUpdated.add(listener)) {
2133				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnKeyStatusUpdateListener");
2134			}
2135		}
2136		if (remainingListeners) {
2137			switchToForeground();
2138		}
2139	}
2140
2141	public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
2142		final boolean remainingListeners;
2143		synchronized (LISTENER_LOCK) {
2144			this.mOnKeyStatusUpdated.remove(listener);
2145			remainingListeners = checkListeners();
2146		}
2147		if (remainingListeners) {
2148			switchToBackground();
2149		}
2150	}
2151
2152	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2153		final boolean remainingListeners;
2154		synchronized (LISTENER_LOCK) {
2155			remainingListeners = checkListeners();
2156			if (!this.mOnMucRosterUpdate.add(listener)) {
2157				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnMucRosterListener");
2158			}
2159		}
2160		if (remainingListeners) {
2161			switchToForeground();
2162		}
2163	}
2164
2165	public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
2166		final boolean remainingListeners;
2167		synchronized (LISTENER_LOCK) {
2168			this.mOnMucRosterUpdate.remove(listener);
2169			remainingListeners = checkListeners();
2170		}
2171		if (remainingListeners) {
2172			switchToBackground();
2173		}
2174	}
2175
2176	public boolean checkListeners() {
2177		return (this.mOnAccountUpdates.size() == 0
2178				&& this.mOnConversationUpdates.size() == 0
2179				&& this.mOnRosterUpdates.size() == 0
2180				&& this.mOnCaptchaRequested.size() == 0
2181				&& this.mOnMucRosterUpdate.size() == 0
2182				&& this.mOnUpdateBlocklist.size() == 0
2183				&& this.mOnShowErrorToasts.size() == 0
2184				&& this.mOnKeyStatusUpdated.size() == 0);
2185	}
2186
2187	private void switchToForeground() {
2188		final boolean broadcastLastActivity = broadcastLastActivity();
2189		for (Conversation conversation : getConversations()) {
2190			if (conversation.getMode() == Conversation.MODE_MULTI) {
2191				conversation.getMucOptions().resetChatState();
2192			} else {
2193				conversation.setIncomingChatState(Config.DEFAULT_CHATSTATE);
2194			}
2195		}
2196		for (Account account : getAccounts()) {
2197			if (account.getStatus() == Account.State.ONLINE) {
2198				account.deactivateGracePeriod();
2199				final XmppConnection connection = account.getXmppConnection();
2200				if (connection != null) {
2201					if (connection.getFeatures().csi()) {
2202						connection.sendActive();
2203					}
2204					if (broadcastLastActivity) {
2205						sendPresence(account, false); //send new presence but don't include idle because we are not
2206					}
2207				}
2208			}
2209		}
2210		Log.d(Config.LOGTAG, "app switched into foreground");
2211	}
2212
2213	private void switchToBackground() {
2214		final boolean broadcastLastActivity = broadcastLastActivity();
2215		if (broadcastLastActivity) {
2216			mLastActivity = System.currentTimeMillis();
2217			final SharedPreferences.Editor editor = getPreferences().edit();
2218			editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
2219			editor.apply();
2220		}
2221		for (Account account : getAccounts()) {
2222			if (account.getStatus() == Account.State.ONLINE) {
2223				XmppConnection connection = account.getXmppConnection();
2224				if (connection != null) {
2225					if (broadcastLastActivity) {
2226						sendPresence(account, true);
2227					}
2228					if (connection.getFeatures().csi()) {
2229						connection.sendInactive();
2230					}
2231				}
2232			}
2233		}
2234		this.mNotificationService.setIsInForeground(false);
2235		Log.d(Config.LOGTAG, "app switched into background");
2236	}
2237
2238	private void connectMultiModeConversations(Account account) {
2239		List<Conversation> conversations = getConversations();
2240		for (Conversation conversation : conversations) {
2241			if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2242				joinMuc(conversation);
2243			}
2244		}
2245	}
2246
2247	public void joinMuc(Conversation conversation) {
2248		joinMuc(conversation, null, false);
2249	}
2250
2251	public void joinMuc(Conversation conversation, boolean followedInvite) {
2252		joinMuc(conversation, null, followedInvite);
2253	}
2254
2255	private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2256		joinMuc(conversation, onConferenceJoined, false);
2257	}
2258
2259	private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2260		Account account = conversation.getAccount();
2261		account.pendingConferenceJoins.remove(conversation);
2262		account.pendingConferenceLeaves.remove(conversation);
2263		if (account.getStatus() == Account.State.ONLINE) {
2264			sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
2265			conversation.resetMucOptions();
2266			if (onConferenceJoined != null) {
2267				conversation.getMucOptions().flagNoAutoPushConfiguration();
2268			}
2269			conversation.setHasMessagesLeftOnServer(false);
2270			fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2271
2272				private void join(Conversation conversation) {
2273					Account account = conversation.getAccount();
2274					final MucOptions mucOptions = conversation.getMucOptions();
2275					final Jid joinJid = mucOptions.getSelf().getFullJid();
2276					Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
2277					PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
2278					packet.setTo(joinJid);
2279					Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2280					if (conversation.getMucOptions().getPassword() != null) {
2281						x.addChild("password").setContent(mucOptions.getPassword());
2282					}
2283
2284					if (mucOptions.mamSupport()) {
2285						// Use MAM instead of the limited muc history to get history
2286						x.addChild("history").setAttribute("maxchars", "0");
2287					} else {
2288						// Fallback to muc history
2289						x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
2290					}
2291					sendPresencePacket(account, packet);
2292					if (onConferenceJoined != null) {
2293						onConferenceJoined.onConferenceJoined(conversation);
2294					}
2295					if (!joinJid.equals(conversation.getJid())) {
2296						conversation.setContactJid(joinJid);
2297						databaseBackend.updateConversation(conversation);
2298					}
2299
2300					if (mucOptions.mamSupport()) {
2301						getMessageArchiveService().catchupMUC(conversation);
2302					}
2303					if (mucOptions.isPrivateAndNonAnonymous()) {
2304						fetchConferenceMembers(conversation);
2305						if (followedInvite && conversation.getBookmark() == null) {
2306							saveConversationAsBookmark(conversation, null);
2307						}
2308					}
2309					sendUnsentMessages(conversation);
2310				}
2311
2312				@Override
2313				public void onConferenceConfigurationFetched(Conversation conversation) {
2314					join(conversation);
2315				}
2316
2317				@Override
2318				public void onFetchFailed(final Conversation conversation, Element error) {
2319					if (error != null && "remote-server-not-found".equals(error.getName())) {
2320						conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2321						updateConversationUi();
2322					} else {
2323						join(conversation);
2324						fetchConferenceConfiguration(conversation);
2325					}
2326				}
2327			});
2328			updateConversationUi();
2329		} else {
2330			account.pendingConferenceJoins.add(conversation);
2331			conversation.resetMucOptions();
2332			conversation.setHasMessagesLeftOnServer(false);
2333			updateConversationUi();
2334		}
2335	}
2336
2337	private void fetchConferenceMembers(final Conversation conversation) {
2338		final Account account = conversation.getAccount();
2339		final AxolotlService axolotlService = account.getAxolotlService();
2340		final String[] affiliations = {"member", "admin", "owner"};
2341		OnIqPacketReceived callback = new OnIqPacketReceived() {
2342
2343			private int i = 0;
2344			private boolean success = true;
2345
2346			@Override
2347			public void onIqPacketReceived(Account account, IqPacket packet) {
2348				final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
2349				Element query = packet.query("http://jabber.org/protocol/muc#admin");
2350				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2351					for (Element child : query.getChildren()) {
2352						if ("item".equals(child.getName())) {
2353							MucOptions.User user = AbstractParser.parseItem(conversation, child);
2354							if (!user.realJidMatchesAccount()) {
2355								boolean isNew = conversation.getMucOptions().updateUser(user);
2356								Contact contact = user.getContact();
2357								if (omemoEnabled
2358										&& isNew
2359										&& user.getRealJid() != null
2360										&& (contact == null || !contact.mutualPresenceSubscription())
2361										&& axolotlService.hasEmptyDeviceList(user.getRealJid())) {
2362									axolotlService.fetchDeviceIds(user.getRealJid());
2363								}
2364							}
2365						}
2366					}
2367				} else {
2368					success = false;
2369					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
2370				}
2371				++i;
2372				if (i >= affiliations.length) {
2373					List<Jid> members = conversation.getMucOptions().getMembers(true);
2374					if (success) {
2375						List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
2376						boolean changed = false;
2377						for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
2378							Jid jid = iterator.next();
2379							if (!members.contains(jid) && !members.contains(Jid.ofDomain(jid.getDomain()))) {
2380								iterator.remove();
2381								Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
2382								changed = true;
2383							}
2384						}
2385						if (changed) {
2386							conversation.setAcceptedCryptoTargets(cryptoTargets);
2387							updateConversation(conversation);
2388						}
2389					}
2390					getAvatarService().clear(conversation);
2391					updateMucRosterUi();
2392					updateConversationUi();
2393				}
2394			}
2395		};
2396		for (String affiliation : affiliations) {
2397			sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2398		}
2399		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
2400	}
2401
2402	public void providePasswordForMuc(Conversation conversation, String password) {
2403		if (conversation.getMode() == Conversation.MODE_MULTI) {
2404			conversation.getMucOptions().setPassword(password);
2405			if (conversation.getBookmark() != null) {
2406				if (respectAutojoin()) {
2407					conversation.getBookmark().setAutojoin(true);
2408				}
2409				pushBookmarks(conversation.getAccount());
2410			}
2411			updateConversation(conversation);
2412			joinMuc(conversation);
2413		}
2414	}
2415
2416	private boolean hasEnabledAccounts() {
2417		for (Account account : this.accounts) {
2418			if (account.isEnabled()) {
2419				return true;
2420			}
2421		}
2422		return false;
2423	}
2424
2425
2426	public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
2427        getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
2428    }
2429
2430    public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2431        getAttachments(account.getUuid(),jid.asBareJid(),limit, onMediaLoaded);
2432    }
2433
2434
2435	public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2436        new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
2437    }
2438
2439	public void persistSelfNick(MucOptions.User self) {
2440		final Conversation conversation = self.getConversation();
2441		Jid full = self.getFullJid();
2442		if (!full.equals(conversation.getJid())) {
2443			Log.d(Config.LOGTAG, "nick changed. updating");
2444			conversation.setContactJid(full);
2445			databaseBackend.updateConversation(conversation);
2446		}
2447
2448		Bookmark bookmark = conversation.getBookmark();
2449		if (bookmark != null && !full.getResource().equals(bookmark.getNick())) {
2450			bookmark.setNick(full.getResource());
2451			pushBookmarks(bookmark.getAccount());
2452		}
2453	}
2454
2455	public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2456		final MucOptions options = conversation.getMucOptions();
2457		final Jid joinJid = options.createJoinJid(nick);
2458		if (joinJid == null) {
2459			return false;
2460		}
2461		if (options.online()) {
2462			Account account = conversation.getAccount();
2463			options.setOnRenameListener(new OnRenameListener() {
2464
2465				@Override
2466				public void onSuccess() {
2467					callback.success(conversation);
2468				}
2469
2470				@Override
2471				public void onFailure() {
2472					callback.error(R.string.nick_in_use, conversation);
2473				}
2474			});
2475
2476			PresencePacket packet = new PresencePacket();
2477			packet.setTo(joinJid);
2478			packet.setFrom(conversation.getAccount().getJid());
2479
2480			String sig = account.getPgpSignature();
2481			if (sig != null) {
2482				packet.addChild("status").setContent("online");
2483				packet.addChild("x", "jabber:x:signed").setContent(sig);
2484			}
2485			sendPresencePacket(account, packet);
2486		} else {
2487			conversation.setContactJid(joinJid);
2488			databaseBackend.updateConversation(conversation);
2489			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2490				Bookmark bookmark = conversation.getBookmark();
2491				if (bookmark != null) {
2492					bookmark.setNick(nick);
2493					pushBookmarks(bookmark.getAccount());
2494				}
2495				joinMuc(conversation);
2496			}
2497		}
2498		return true;
2499	}
2500
2501	public void leaveMuc(Conversation conversation) {
2502		leaveMuc(conversation, false);
2503	}
2504
2505	private void leaveMuc(Conversation conversation, boolean now) {
2506		Account account = conversation.getAccount();
2507		account.pendingConferenceJoins.remove(conversation);
2508		account.pendingConferenceLeaves.remove(conversation);
2509		if (account.getStatus() == Account.State.ONLINE || now) {
2510			sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
2511			conversation.getMucOptions().setOffline();
2512			Bookmark bookmark = conversation.getBookmark();
2513			if (bookmark != null) {
2514				bookmark.setConversation(null);
2515			}
2516			Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
2517		} else {
2518			account.pendingConferenceLeaves.add(conversation);
2519		}
2520	}
2521
2522	public String findConferenceServer(final Account account) {
2523		String server;
2524		if (account.getXmppConnection() != null) {
2525			server = account.getXmppConnection().getMucServer();
2526			if (server != null) {
2527				return server;
2528			}
2529		}
2530		for (Account other : getAccounts()) {
2531			if (other != account && other.getXmppConnection() != null) {
2532				server = other.getXmppConnection().getMucServer();
2533				if (server != null) {
2534					return server;
2535				}
2536			}
2537		}
2538		return null;
2539	}
2540
2541	public boolean createAdhocConference(final Account account,
2542	                                     final String name,
2543	                                     final Iterable<Jid> jids,
2544	                                     final UiCallback<Conversation> callback) {
2545		Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2546		if (account.getStatus() == Account.State.ONLINE) {
2547			try {
2548				String server = findConferenceServer(account);
2549				if (server == null) {
2550					if (callback != null) {
2551						callback.error(R.string.no_conference_server_found, null);
2552					}
2553					return false;
2554				}
2555				final Jid jid = Jid.of(CryptoHelper.pronounceable(getRNG()), server, null);
2556				final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
2557				joinMuc(conversation, new OnConferenceJoined() {
2558					@Override
2559					public void onConferenceJoined(final Conversation conversation) {
2560						final Bundle configuration = IqGenerator.defaultRoomConfiguration();
2561						if (!TextUtils.isEmpty(name)) {
2562							configuration.putString("muc#roomconfig_roomname", name);
2563						}
2564						pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
2565							@Override
2566							public void onPushSucceeded() {
2567								for (Jid invite : jids) {
2568									invite(conversation, invite);
2569								}
2570								if (account.countPresences() > 1) {
2571									directInvite(conversation, account.getJid().asBareJid());
2572								}
2573								saveConversationAsBookmark(conversation, name);
2574								if (callback != null) {
2575									callback.success(conversation);
2576								}
2577							}
2578
2579							@Override
2580							public void onPushFailed() {
2581								archiveConversation(conversation);
2582								if (callback != null) {
2583									callback.error(R.string.conference_creation_failed, conversation);
2584								}
2585							}
2586						});
2587					}
2588				});
2589				return true;
2590			} catch (IllegalArgumentException e) {
2591				if (callback != null) {
2592					callback.error(R.string.conference_creation_failed, null);
2593				}
2594				return false;
2595			}
2596		} else {
2597			if (callback != null) {
2598				callback.error(R.string.not_connected_try_again, null);
2599			}
2600			return false;
2601		}
2602	}
2603
2604	public void fetchConferenceConfiguration(final Conversation conversation) {
2605		fetchConferenceConfiguration(conversation, null);
2606	}
2607
2608	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2609		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2610		request.setTo(conversation.getJid().asBareJid());
2611		request.query("http://jabber.org/protocol/disco#info");
2612		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2613			@Override
2614			public void onIqPacketReceived(Account account, IqPacket packet) {
2615				if (packet.getType() == IqPacket.TYPE.RESULT) {
2616
2617					final MucOptions mucOptions = conversation.getMucOptions();
2618					final Bookmark bookmark = conversation.getBookmark();
2619					final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
2620
2621					if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
2622						Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
2623						updateConversation(conversation);
2624					}
2625
2626					if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
2627						if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
2628							pushBookmarks(account);
2629						}
2630					}
2631
2632
2633					if (callback != null) {
2634						callback.onConferenceConfigurationFetched(conversation);
2635					}
2636
2637
2638
2639					updateConversationUi();
2640				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
2641					if (callback != null) {
2642						callback.onFetchFailed(conversation, packet.getError());
2643					}
2644				}
2645			}
2646		});
2647	}
2648
2649	public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
2650		pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
2651	}
2652
2653	public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
2654        Log.d(Config.LOGTAG,"pushing node configuration");
2655		sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
2656			@Override
2657			public void onIqPacketReceived(Account account, IqPacket packet) {
2658				if (packet.getType() == IqPacket.TYPE.RESULT) {
2659					Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
2660					Element configuration = pubsub == null ? null : pubsub.findChild("configure");
2661					Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
2662					if (x != null) {
2663						Data data = Data.parse(x);
2664						data.submit(options);
2665						sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
2666							@Override
2667							public void onIqPacketReceived(Account account, IqPacket packet) {
2668								if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
2669									Log.d(Config.LOGTAG,account.getJid().asBareJid()+": successfully changed node configuration for node "+node);
2670									callback.onPushSucceeded();
2671								} else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
2672									callback.onPushFailed();
2673								}
2674							}
2675						});
2676					} else if (callback != null) {
2677						callback.onPushFailed();
2678					}
2679				} else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
2680					callback.onPushFailed();
2681				}
2682			}
2683		});
2684	}
2685
2686	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
2687		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2688		request.setTo(conversation.getJid().asBareJid());
2689		request.query("http://jabber.org/protocol/muc#owner");
2690		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2691			@Override
2692			public void onIqPacketReceived(Account account, IqPacket packet) {
2693				if (packet.getType() == IqPacket.TYPE.RESULT) {
2694					Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
2695					data.submit(options);
2696					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2697					set.setTo(conversation.getJid().asBareJid());
2698					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2699					sendIqPacket(account, set, new OnIqPacketReceived() {
2700						@Override
2701						public void onIqPacketReceived(Account account, IqPacket packet) {
2702							if (callback != null) {
2703								if (packet.getType() == IqPacket.TYPE.RESULT) {
2704									callback.onPushSucceeded();
2705								} else {
2706									callback.onPushFailed();
2707								}
2708							}
2709						}
2710					});
2711				} else {
2712					if (callback != null) {
2713						callback.onPushFailed();
2714					}
2715				}
2716			}
2717		});
2718	}
2719
2720	public void pushSubjectToConference(final Conversation conference, final String subject) {
2721		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
2722		this.sendMessagePacket(conference.getAccount(), packet);
2723	}
2724
2725	public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2726		final Jid jid = user.asBareJid();
2727		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2728		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2729			@Override
2730			public void onIqPacketReceived(Account account, IqPacket packet) {
2731				if (packet.getType() == IqPacket.TYPE.RESULT) {
2732					conference.getMucOptions().changeAffiliation(jid, affiliation);
2733					getAvatarService().clear(conference);
2734					callback.onAffiliationChangedSuccessful(jid);
2735				} else {
2736					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2737				}
2738			}
2739		});
2740	}
2741
2742	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2743		List<Jid> jids = new ArrayList<>();
2744		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2745			if (user.getAffiliation() == before && user.getRealJid() != null) {
2746				jids.add(user.getRealJid());
2747			}
2748		}
2749		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2750		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2751	}
2752
2753	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2754		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2755		Log.d(Config.LOGTAG, request.toString());
2756		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2757			@Override
2758			public void onIqPacketReceived(Account account, IqPacket packet) {
2759				Log.d(Config.LOGTAG, packet.toString());
2760				if (packet.getType() == IqPacket.TYPE.RESULT) {
2761					callback.onRoleChangedSuccessful(nick);
2762				} else {
2763					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2764				}
2765			}
2766		});
2767	}
2768
2769	private void disconnect(Account account, boolean force) {
2770		if ((account.getStatus() == Account.State.ONLINE)
2771				|| (account.getStatus() == Account.State.DISABLED)) {
2772			final XmppConnection connection = account.getXmppConnection();
2773			if (!force) {
2774				List<Conversation> conversations = getConversations();
2775				for (Conversation conversation : conversations) {
2776					if (conversation.getAccount() == account) {
2777						if (conversation.getMode() == Conversation.MODE_MULTI) {
2778							leaveMuc(conversation, true);
2779						}
2780					}
2781				}
2782				sendOfflinePresence(account);
2783			}
2784			connection.disconnect(force);
2785		}
2786	}
2787
2788	@Override
2789	public IBinder onBind(Intent intent) {
2790		return mBinder;
2791	}
2792
2793	public void updateMessage(Message message) {
2794		updateMessage(message, true);
2795	}
2796
2797	public void updateMessage(Message message, boolean includeBody) {
2798		databaseBackend.updateMessage(message, includeBody);
2799		updateConversationUi();
2800	}
2801
2802	public void updateMessage(Message message, String uuid) {
2803		databaseBackend.updateMessage(message, uuid);
2804		updateConversationUi();
2805	}
2806
2807	protected void syncDirtyContacts(Account account) {
2808		for (Contact contact : account.getRoster().getContacts()) {
2809			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2810				pushContactToServer(contact);
2811			}
2812			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2813				deleteContactOnServer(contact);
2814			}
2815		}
2816	}
2817
2818	public void createContact(Contact contact, boolean autoGrant) {
2819		if (autoGrant) {
2820			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2821			contact.setOption(Contact.Options.ASKING);
2822		}
2823		pushContactToServer(contact);
2824	}
2825
2826	public void pushContactToServer(final Contact contact) {
2827		contact.resetOption(Contact.Options.DIRTY_DELETE);
2828		contact.setOption(Contact.Options.DIRTY_PUSH);
2829		final Account account = contact.getAccount();
2830		if (account.getStatus() == Account.State.ONLINE) {
2831			final boolean ask = contact.getOption(Contact.Options.ASKING);
2832			final boolean sendUpdates = contact
2833					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2834					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2835			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2836			iq.query(Namespace.ROSTER).addChild(contact.asElement());
2837			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2838			if (sendUpdates) {
2839				sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
2840			}
2841			if (ask) {
2842				sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2843			}
2844		} else {
2845			syncRoster(contact.getAccount());
2846		}
2847	}
2848
2849	public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
2850		new Thread(() -> {
2851			final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2852			final int size = Config.AVATAR_SIZE;
2853			final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2854			if (avatar != null) {
2855				if (!getFileBackend().save(avatar)) {
2856					callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
2857					return;
2858				}
2859				avatar.owner = conversation.getJid().asBareJid();
2860				publishMucAvatar(conversation, avatar, callback);
2861			} else {
2862				callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
2863			}
2864		}).start();
2865	}
2866
2867	public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
2868		new Thread(() -> {
2869			final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2870			final int size = Config.AVATAR_SIZE;
2871			final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2872			if (avatar != null) {
2873				if (!getFileBackend().save(avatar)) {
2874					Log.d(Config.LOGTAG,"unable to save vcard");
2875					callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
2876					return;
2877				}
2878				publishAvatar(account, avatar, callback);
2879			} else {
2880				callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
2881			}
2882		}).start();
2883
2884	}
2885
2886	private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
2887		final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
2888		sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
2889			boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
2890			if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
2891				Element vcard = response.findChild("vCard", "vcard-temp");
2892				if (vcard == null) {
2893					vcard = new Element("vCard", "vcard-temp");
2894				}
2895				Element photo = vcard.findChild("PHOTO");
2896				if (photo == null) {
2897					photo = vcard.addChild("PHOTO");
2898				}
2899				photo.clearChildren();
2900				photo.addChild("TYPE").setContent(avatar.type);
2901				photo.addChild("BINVAL").setContent(avatar.image);
2902				IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
2903				publication.setTo(conversation.getJid().asBareJid());
2904				publication.addChild(vcard);
2905				sendIqPacket(account, publication, (a1, publicationResponse) -> {
2906					if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
2907						callback.onAvatarPublicationSucceeded();
2908					} else {
2909						Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getError());
2910						callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
2911					}
2912				});
2913			} else {
2914				Log.d(Config.LOGTAG, "failed to request vcard " + response.toString());
2915				callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
2916			}
2917		});
2918	}
2919
2920	public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
2921		IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2922		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2923
2924			@Override
2925			public void onIqPacketReceived(Account account, IqPacket result) {
2926				if (result.getType() == IqPacket.TYPE.RESULT) {
2927					final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar);
2928					sendIqPacket(account, packet, new OnIqPacketReceived() {
2929						@Override
2930						public void onIqPacketReceived(Account account, IqPacket result) {
2931							if (result.getType() == IqPacket.TYPE.RESULT) {
2932								if (account.setAvatar(avatar.getFilename())) {
2933									getAvatarService().clear(account);
2934									databaseBackend.updateAccount(account);
2935								}
2936								Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
2937								if (callback != null) {
2938									callback.onAvatarPublicationSucceeded();
2939								}
2940							} else {
2941								if (callback != null) {
2942									callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
2943								}
2944							}
2945						}
2946					});
2947				} else {
2948					Element error = result.findChild("error");
2949					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
2950					if (callback != null) {
2951						callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
2952					}
2953				}
2954			}
2955		});
2956	}
2957
2958	public void republishAvatarIfNeeded(Account account) {
2959		if (account.getAxolotlService().isPepBroken()) {
2960			Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
2961			return;
2962		}
2963		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2964		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2965
2966			private Avatar parseAvatar(IqPacket packet) {
2967				Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2968				if (pubsub != null) {
2969					Element items = pubsub.findChild("items");
2970					if (items != null) {
2971						return Avatar.parseMetadata(items);
2972					}
2973				}
2974				return null;
2975			}
2976
2977			private boolean errorIsItemNotFound(IqPacket packet) {
2978				Element error = packet.findChild("error");
2979				return packet.getType() == IqPacket.TYPE.ERROR
2980						&& error != null
2981						&& error.hasChild("item-not-found");
2982			}
2983
2984			@Override
2985			public void onIqPacketReceived(Account account, IqPacket packet) {
2986				if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2987					Avatar serverAvatar = parseAvatar(packet);
2988					if (serverAvatar == null && account.getAvatar() != null) {
2989						Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2990						if (avatar != null) {
2991							Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
2992							publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2993						} else {
2994							Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
2995						}
2996					}
2997				}
2998			}
2999		});
3000	}
3001
3002	public void fetchAvatar(Account account, Avatar avatar) {
3003		fetchAvatar(account, avatar, null);
3004	}
3005
3006	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3007		final String KEY = generateFetchKey(account, avatar);
3008		synchronized (this.mInProgressAvatarFetches) {
3009			if (!this.mInProgressAvatarFetches.contains(KEY)) {
3010				switch (avatar.origin) {
3011					case PEP:
3012						this.mInProgressAvatarFetches.add(KEY);
3013						fetchAvatarPep(account, avatar, callback);
3014						break;
3015					case VCARD:
3016						this.mInProgressAvatarFetches.add(KEY);
3017						fetchAvatarVcard(account, avatar, callback);
3018						break;
3019				}
3020			}
3021		}
3022	}
3023
3024	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3025		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
3026		sendIqPacket(account, packet, (a, result) -> {
3027			synchronized (mInProgressAvatarFetches) {
3028				mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
3029			}
3030			final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
3031			if (result.getType() == IqPacket.TYPE.RESULT) {
3032				avatar.image = mIqParser.avatarData(result);
3033				if (avatar.image != null) {
3034					if (getFileBackend().save(avatar)) {
3035						if (a.getJid().asBareJid().equals(avatar.owner)) {
3036							if (a.setAvatar(avatar.getFilename())) {
3037								databaseBackend.updateAccount(a);
3038							}
3039							getAvatarService().clear(a);
3040							updateConversationUi();
3041							updateAccountUi();
3042						} else {
3043							Contact contact = a.getRoster().getContact(avatar.owner);
3044							if (contact.setAvatar(avatar)) {
3045								syncRoster(account);
3046								getAvatarService().clear(contact);
3047								updateConversationUi();
3048								updateRosterUi();
3049							}
3050						}
3051						if (callback != null) {
3052							callback.success(avatar);
3053						}
3054						Log.d(Config.LOGTAG, a.getJid().asBareJid()
3055								+ ": successfully fetched pep avatar for " + avatar.owner);
3056						return;
3057					}
3058				} else {
3059
3060					Log.d(Config.LOGTAG, ERROR + "(parsing error)");
3061				}
3062			} else {
3063				Element error = result.findChild("error");
3064				if (error == null) {
3065					Log.d(Config.LOGTAG, ERROR + "(server error)");
3066				} else {
3067					Log.d(Config.LOGTAG, ERROR + error.toString());
3068				}
3069			}
3070			if (callback != null) {
3071				callback.error(0, null);
3072			}
3073
3074		});
3075	}
3076
3077	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3078		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
3079		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3080			@Override
3081			public void onIqPacketReceived(Account account, IqPacket packet) {
3082				synchronized (mInProgressAvatarFetches) {
3083					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
3084				}
3085				if (packet.getType() == IqPacket.TYPE.RESULT) {
3086					Element vCard = packet.findChild("vCard", "vcard-temp");
3087					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
3088					String image = photo != null ? photo.findChildContent("BINVAL") : null;
3089					if (image != null) {
3090						avatar.image = image;
3091						if (getFileBackend().save(avatar)) {
3092							Log.d(Config.LOGTAG, account.getJid().asBareJid()
3093									+ ": successfully fetched vCard avatar for " + avatar.owner);
3094							if (avatar.owner.isBareJid()) {
3095								if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
3096									Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
3097									account.setAvatar(avatar.getFilename());
3098									databaseBackend.updateAccount(account);
3099									getAvatarService().clear(account);
3100									updateAccountUi();
3101								} else {
3102									Contact contact = account.getRoster().getContact(avatar.owner);
3103									if (contact.setAvatar(avatar)) {
3104										syncRoster(account);
3105										getAvatarService().clear(contact);
3106										updateRosterUi();
3107									}
3108								}
3109								updateConversationUi();
3110							} else {
3111								Conversation conversation = find(account, avatar.owner.asBareJid());
3112								if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
3113									MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
3114									if (user != null) {
3115										if (user.setAvatar(avatar)) {
3116											getAvatarService().clear(user);
3117											updateConversationUi();
3118											updateMucRosterUi();
3119										}
3120										if (user.getRealJid() != null) {
3121										    Contact contact = account.getRoster().getContact(user.getRealJid());
3122										    if (contact.setAvatar(avatar)) {
3123                                                syncRoster(account);
3124                                                getAvatarService().clear(contact);
3125                                                updateRosterUi();
3126                                            }
3127                                        }
3128									}
3129								}
3130							}
3131						}
3132					}
3133				}
3134			}
3135		});
3136	}
3137
3138	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
3139		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3140		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3141
3142			@Override
3143			public void onIqPacketReceived(Account account, IqPacket packet) {
3144				if (packet.getType() == IqPacket.TYPE.RESULT) {
3145					Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3146					if (pubsub != null) {
3147						Element items = pubsub.findChild("items");
3148						if (items != null) {
3149							Avatar avatar = Avatar.parseMetadata(items);
3150							if (avatar != null) {
3151								avatar.owner = account.getJid().asBareJid();
3152								if (fileBackend.isAvatarCached(avatar)) {
3153									if (account.setAvatar(avatar.getFilename())) {
3154										databaseBackend.updateAccount(account);
3155									}
3156									getAvatarService().clear(account);
3157									callback.success(avatar);
3158								} else {
3159									fetchAvatarPep(account, avatar, callback);
3160								}
3161								return;
3162							}
3163						}
3164					}
3165				}
3166				callback.error(0, null);
3167			}
3168		});
3169	}
3170
3171	public void deleteContactOnServer(Contact contact) {
3172		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
3173		contact.resetOption(Contact.Options.DIRTY_PUSH);
3174		contact.setOption(Contact.Options.DIRTY_DELETE);
3175		Account account = contact.getAccount();
3176		if (account.getStatus() == Account.State.ONLINE) {
3177			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3178			Element item = iq.query(Namespace.ROSTER).addChild("item");
3179			item.setAttribute("jid", contact.getJid().toString());
3180			item.setAttribute("subscription", "remove");
3181			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3182		}
3183	}
3184
3185	public void updateConversation(final Conversation conversation) {
3186		mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
3187	}
3188
3189	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
3190		synchronized (account) {
3191			XmppConnection connection = account.getXmppConnection();
3192			if (connection == null) {
3193				connection = createConnection(account);
3194				account.setXmppConnection(connection);
3195			}
3196			boolean hasInternet = hasInternetConnection();
3197			if (account.isEnabled() && hasInternet) {
3198				if (!force) {
3199					disconnect(account, false);
3200				}
3201				Thread thread = new Thread(connection);
3202				connection.setInteractive(interactive);
3203				connection.prepareNewConnection();
3204				connection.interrupt();
3205				thread.start();
3206				scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
3207			} else {
3208				disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
3209				account.getRoster().clearPresences();
3210				connection.resetEverything();
3211				final AxolotlService axolotlService = account.getAxolotlService();
3212				if (axolotlService != null) {
3213					axolotlService.resetBrokenness();
3214				}
3215				if (!hasInternet) {
3216					account.setStatus(Account.State.NO_INTERNET);
3217				}
3218			}
3219		}
3220	}
3221
3222	public void reconnectAccountInBackground(final Account account) {
3223		new Thread(() -> reconnectAccount(account, false, true)).start();
3224	}
3225
3226	public void invite(Conversation conversation, Jid contact) {
3227		Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
3228		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
3229		sendMessagePacket(conversation.getAccount(), packet);
3230	}
3231
3232	public void directInvite(Conversation conversation, Jid jid) {
3233		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
3234		sendMessagePacket(conversation.getAccount(), packet);
3235	}
3236
3237	public void resetSendingToWaiting(Account account) {
3238		for (Conversation conversation : getConversations()) {
3239			if (conversation.getAccount() == account) {
3240				conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
3241			}
3242		}
3243	}
3244
3245	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
3246		return markMessage(account, recipient, uuid, status, null);
3247	}
3248
3249	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
3250		if (uuid == null) {
3251			return null;
3252		}
3253		for (Conversation conversation : getConversations()) {
3254			if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
3255				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
3256				if (message != null) {
3257					markMessage(message, status, errorMessage);
3258				}
3259				return message;
3260			}
3261		}
3262		return null;
3263	}
3264
3265	public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) {
3266		if (uuid == null) {
3267			return false;
3268		} else {
3269			Message message = conversation.findSentMessageWithUuid(uuid);
3270			if (message != null) {
3271				if (message.getServerMsgId() == null) {
3272					message.setServerMsgId(serverMessageId);
3273				}
3274				markMessage(message, status);
3275				return true;
3276			} else {
3277				return false;
3278			}
3279		}
3280	}
3281
3282	public void markMessage(Message message, int status) {
3283		markMessage(message, status, null);
3284	}
3285
3286
3287	public void markMessage(Message message, int status, String errorMessage) {
3288		final int c = message.getStatus();
3289		if (status == Message.STATUS_SEND_FAILED && (c == Message.STATUS_SEND_RECEIVED || c == Message.STATUS_SEND_DISPLAYED)) {
3290			return;
3291		}
3292		if (status == Message.STATUS_SEND_RECEIVED && c == Message.STATUS_SEND_DISPLAYED) {
3293			return;
3294		}
3295		message.setErrorMessage(errorMessage);
3296		message.setStatus(status);
3297		databaseBackend.updateMessage(message, false);
3298		updateConversationUi();
3299	}
3300
3301	private SharedPreferences getPreferences() {
3302		return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
3303	}
3304
3305	public long getAutomaticMessageDeletionDate() {
3306		final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
3307		return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
3308	}
3309
3310	public long getLongPreference(String name, @IntegerRes int res) {
3311		long defaultValue = getResources().getInteger(res);
3312		try {
3313			return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
3314		} catch (NumberFormatException e) {
3315			return defaultValue;
3316		}
3317	}
3318
3319	public boolean getBooleanPreference(String name, @BoolRes int res) {
3320		return getPreferences().getBoolean(name, getResources().getBoolean(res));
3321	}
3322
3323	public boolean confirmMessages() {
3324		return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
3325	}
3326
3327	public boolean allowMessageCorrection() {
3328		return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
3329	}
3330
3331	public boolean sendChatStates() {
3332		return getBooleanPreference("chat_states", R.bool.chat_states);
3333	}
3334
3335	private boolean respectAutojoin() {
3336		return getBooleanPreference("autojoin", R.bool.autojoin);
3337	}
3338
3339	public boolean indicateReceived() {
3340		return getBooleanPreference("indicate_received", R.bool.indicate_received);
3341	}
3342
3343	public boolean useTorToConnect() {
3344		return Config.FORCE_ORBOT || getBooleanPreference("use_tor", R.bool.use_tor);
3345	}
3346
3347	public boolean showExtendedConnectionOptions() {
3348		return getBooleanPreference("show_connection_options", R.bool.show_connection_options);
3349	}
3350
3351	public boolean broadcastLastActivity() {
3352		return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
3353	}
3354
3355	public int unreadCount() {
3356		int count = 0;
3357		for (Conversation conversation : getConversations()) {
3358			count += conversation.unreadCount();
3359		}
3360		return count;
3361	}
3362
3363
3364	private <T> List<T> threadSafeList(Set<T> set) {
3365		synchronized (LISTENER_LOCK) {
3366			return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
3367		}
3368	}
3369
3370	public void showErrorToastInUi(int resId) {
3371		for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
3372			listener.onShowErrorToast(resId);
3373		}
3374	}
3375
3376	public void updateConversationUi() {
3377		for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
3378			listener.onConversationUpdate();
3379		}
3380	}
3381
3382	public void updateAccountUi() {
3383		for (OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
3384			listener.onAccountUpdate();
3385		}
3386	}
3387
3388	public void updateRosterUi() {
3389		for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
3390			listener.onRosterUpdate();
3391		}
3392	}
3393
3394	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3395		if (mOnCaptchaRequested.size() > 0) {
3396			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3397			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3398					(int) (captcha.getHeight() * metrics.scaledDensity), false);
3399			for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
3400				listener.onCaptchaRequested(account, id, data, scaled);
3401			}
3402			return true;
3403		}
3404		return false;
3405	}
3406
3407	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3408		for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
3409			listener.OnUpdateBlocklist(status);
3410		}
3411	}
3412
3413	public void updateMucRosterUi() {
3414		for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
3415			listener.onMucRosterUpdate();
3416		}
3417	}
3418
3419	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3420		for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
3421			listener.onKeyStatusUpdated(report);
3422		}
3423	}
3424
3425	public Account findAccountByJid(final Jid accountJid) {
3426		for (Account account : this.accounts) {
3427			if (account.getJid().asBareJid().equals(accountJid.asBareJid())) {
3428				return account;
3429			}
3430		}
3431		return null;
3432	}
3433
3434	public Account findAccountByUuid(final String uuid) {
3435		for(Account account : this.accounts) {
3436			if (account.getUuid().equals(uuid)) {
3437				return account;
3438			}
3439		}
3440		return null;
3441	}
3442
3443	public Conversation findConversationByUuid(String uuid) {
3444		for (Conversation conversation : getConversations()) {
3445			if (conversation.getUuid().equals(uuid)) {
3446				return conversation;
3447			}
3448		}
3449		return null;
3450	}
3451
3452	public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
3453		List<Conversation> findings = new ArrayList<>();
3454		for (Conversation c : getConversations()) {
3455			if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
3456				findings.add(c);
3457			}
3458		}
3459		return findings.size() == 1 ? findings.get(0) : null;
3460	}
3461
3462	public boolean markRead(final Conversation conversation, boolean dismiss) {
3463		return markRead(conversation, null, dismiss).size() > 0;
3464	}
3465
3466	public void markRead(final Conversation conversation) {
3467		markRead(conversation, null, true);
3468	}
3469
3470	public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
3471		if (dismiss) {
3472			mNotificationService.clear(conversation);
3473		}
3474		final List<Message> readMessages = conversation.markRead(upToUuid);
3475		if (readMessages.size() > 0) {
3476			Runnable runnable = () -> {
3477				for (Message message : readMessages) {
3478					databaseBackend.updateMessage(message, false);
3479				}
3480			};
3481			mDatabaseWriterExecutor.execute(runnable);
3482			updateUnreadCountBadge();
3483			return readMessages;
3484		} else {
3485			return readMessages;
3486		}
3487	}
3488
3489	public synchronized void updateUnreadCountBadge() {
3490		int count = unreadCount();
3491		if (unreadCount != count) {
3492			Log.d(Config.LOGTAG, "update unread count to " + count);
3493			if (count > 0) {
3494				ShortcutBadger.applyCount(getApplicationContext(), count);
3495			} else {
3496				ShortcutBadger.removeCount(getApplicationContext());
3497			}
3498			unreadCount = count;
3499		}
3500	}
3501
3502	public void sendReadMarker(final Conversation conversation, String upToUuid) {
3503		final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
3504		final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
3505		if (readMessages.size() > 0) {
3506			updateConversationUi();
3507		}
3508		final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
3509		if (confirmMessages()
3510				&& markable != null
3511				&& (markable.trusted() || isPrivateAndNonAnonymousMuc)
3512				&& markable.getRemoteMsgId() != null) {
3513			Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
3514			Account account = conversation.getAccount();
3515			final Jid to = markable.getCounterpart();
3516			final boolean groupChat = conversation.getMode() == Conversation.MODE_MULTI;
3517			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId(), markable.getCounterpart(), groupChat);
3518			this.sendMessagePacket(conversation.getAccount(), packet);
3519		}
3520	}
3521
3522	public SecureRandom getRNG() {
3523		return this.mRandom;
3524	}
3525
3526	public MemorizingTrustManager getMemorizingTrustManager() {
3527		return this.mMemorizingTrustManager;
3528	}
3529
3530	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
3531		this.mMemorizingTrustManager = trustManager;
3532	}
3533
3534	public void updateMemorizingTrustmanager() {
3535		final MemorizingTrustManager tm;
3536		final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
3537		if (dontTrustSystemCAs) {
3538			tm = new MemorizingTrustManager(getApplicationContext(), null);
3539		} else {
3540			tm = new MemorizingTrustManager(getApplicationContext());
3541		}
3542		setMemorizingTrustManager(tm);
3543	}
3544
3545	public LruCache<String, Bitmap> getBitmapCache() {
3546		return this.mBitmapCache;
3547	}
3548
3549	public Collection<String> getKnownHosts() {
3550		final Set<String> hosts = new HashSet<>();
3551		for (final Account account : getAccounts()) {
3552			hosts.add(account.getServer());
3553			for (final Contact contact : account.getRoster().getContacts()) {
3554				if (contact.showInRoster()) {
3555					final String server = contact.getServer();
3556					if (server != null && !hosts.contains(server)) {
3557						hosts.add(server);
3558					}
3559				}
3560			}
3561		}
3562		if (Config.DOMAIN_LOCK != null) {
3563			hosts.add(Config.DOMAIN_LOCK);
3564		}
3565		if (Config.MAGIC_CREATE_DOMAIN != null) {
3566			hosts.add(Config.MAGIC_CREATE_DOMAIN);
3567		}
3568		return hosts;
3569	}
3570
3571	public Collection<String> getKnownConferenceHosts() {
3572		final Set<String> mucServers = new HashSet<>();
3573		for (final Account account : accounts) {
3574			if (account.getXmppConnection() != null) {
3575				mucServers.addAll(account.getXmppConnection().getMucServers());
3576				for (Bookmark bookmark : account.getBookmarks()) {
3577					final Jid jid = bookmark.getJid();
3578					final String s = jid == null ? null : jid.getDomain();
3579					if (s != null) {
3580						mucServers.add(s);
3581					}
3582				}
3583			}
3584		}
3585		return mucServers;
3586	}
3587
3588	public void sendMessagePacket(Account account, MessagePacket packet) {
3589		XmppConnection connection = account.getXmppConnection();
3590		if (connection != null) {
3591			connection.sendMessagePacket(packet);
3592		}
3593	}
3594
3595	public void sendPresencePacket(Account account, PresencePacket packet) {
3596		XmppConnection connection = account.getXmppConnection();
3597		if (connection != null) {
3598			connection.sendPresencePacket(packet);
3599		}
3600	}
3601
3602	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3603		final XmppConnection connection = account.getXmppConnection();
3604		if (connection != null) {
3605			IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3606			connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
3607		}
3608	}
3609
3610	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3611		final XmppConnection connection = account.getXmppConnection();
3612		if (connection != null) {
3613			connection.sendIqPacket(packet, callback);
3614		} else if (callback != null) {
3615		    callback.onIqPacketReceived(account,new IqPacket(IqPacket.TYPE.TIMEOUT));
3616        }
3617	}
3618
3619	public void sendPresence(final Account account) {
3620		sendPresence(account, checkListeners() && broadcastLastActivity());
3621	}
3622
3623	private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3624		Presence.Status status;
3625		if (manuallyChangePresence()) {
3626			status = account.getPresenceStatus();
3627		} else {
3628			status = getTargetPresence();
3629		}
3630		PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
3631		String message = account.getPresenceStatusMessage();
3632		if (message != null && !message.isEmpty()) {
3633			packet.addChild(new Element("status").setContent(message));
3634		}
3635		if (mLastActivity > 0 && includeIdleTimestamp) {
3636			long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3637			packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
3638		}
3639		sendPresencePacket(account, packet);
3640	}
3641
3642	private void deactivateGracePeriod() {
3643		for (Account account : getAccounts()) {
3644			account.deactivateGracePeriod();
3645		}
3646	}
3647
3648	public void refreshAllPresences() {
3649		boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3650		for (Account account : getAccounts()) {
3651			if (account.isEnabled()) {
3652				sendPresence(account, includeIdleTimestamp);
3653			}
3654		}
3655	}
3656
3657	private void refreshAllFcmTokens() {
3658		for (Account account : getAccounts()) {
3659			if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3660				mPushManagementService.registerPushTokenOnServer(account);
3661			}
3662		}
3663	}
3664
3665	private void sendOfflinePresence(final Account account) {
3666		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
3667		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3668	}
3669
3670	public MessageGenerator getMessageGenerator() {
3671		return this.mMessageGenerator;
3672	}
3673
3674	public PresenceGenerator getPresenceGenerator() {
3675		return this.mPresenceGenerator;
3676	}
3677
3678	public IqGenerator getIqGenerator() {
3679		return this.mIqGenerator;
3680	}
3681
3682	public IqParser getIqParser() {
3683		return this.mIqParser;
3684	}
3685
3686	public JingleConnectionManager getJingleConnectionManager() {
3687		return this.mJingleConnectionManager;
3688	}
3689
3690	public MessageArchiveService getMessageArchiveService() {
3691		return this.mMessageArchiveService;
3692	}
3693
3694	public List<Contact> findContacts(Jid jid, String accountJid) {
3695		ArrayList<Contact> contacts = new ArrayList<>();
3696		for (Account account : getAccounts()) {
3697			if ((account.isEnabled() || accountJid != null)
3698					&& (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
3699				Contact contact = account.getRoster().getContactFromRoster(jid);
3700				if (contact != null) {
3701					contacts.add(contact);
3702				}
3703			}
3704		}
3705		return contacts;
3706	}
3707
3708	public Conversation findFirstMuc(Jid jid) {
3709		for (Conversation conversation : getConversations()) {
3710			if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
3711				return conversation;
3712			}
3713		}
3714		return null;
3715	}
3716
3717	public NotificationService getNotificationService() {
3718		return this.mNotificationService;
3719	}
3720
3721	public HttpConnectionManager getHttpConnectionManager() {
3722		return this.mHttpConnectionManager;
3723	}
3724
3725	public void resendFailedMessages(final Message message) {
3726		final Collection<Message> messages = new ArrayList<>();
3727		Message current = message;
3728		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3729			messages.add(current);
3730			if (current.mergeable(current.next())) {
3731				current = current.next();
3732			} else {
3733				break;
3734			}
3735		}
3736		for (final Message msg : messages) {
3737			msg.setTime(System.currentTimeMillis());
3738			markMessage(msg, Message.STATUS_WAITING);
3739			this.resendMessage(msg, false);
3740		}
3741		if (message.getConversation() instanceof Conversation) {
3742			((Conversation) message.getConversation()).sort();
3743		}
3744		updateConversationUi();
3745	}
3746
3747	public void clearConversationHistory(final Conversation conversation) {
3748		final long clearDate;
3749		final String reference;
3750		if (conversation.countMessages() > 0) {
3751			Message latestMessage = conversation.getLatestMessage();
3752			clearDate = latestMessage.getTimeSent() + 1000;
3753			reference = latestMessage.getServerMsgId();
3754		} else {
3755			clearDate = System.currentTimeMillis();
3756			reference = null;
3757		}
3758		conversation.clearMessages();
3759		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3760		conversation.setLastClearHistory(clearDate, reference);
3761		Runnable runnable = () -> {
3762			databaseBackend.deleteMessagesInConversation(conversation);
3763			databaseBackend.updateConversation(conversation);
3764		};
3765		mDatabaseWriterExecutor.execute(runnable);
3766	}
3767
3768	public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
3769		if (blockable != null && blockable.getBlockedJid() != null) {
3770			final Jid jid = blockable.getBlockedJid();
3771			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), new OnIqPacketReceived() {
3772
3773				@Override
3774				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3775					if (packet.getType() == IqPacket.TYPE.RESULT) {
3776						account.getBlocklist().add(jid);
3777						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3778					}
3779				}
3780			});
3781			if (removeBlockedConversations(blockable.getAccount(), jid)) {
3782				updateConversationUi();
3783				return true;
3784			} else {
3785				return false;
3786			}
3787		} else {
3788			return false;
3789		}
3790	}
3791
3792	public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
3793		boolean removed = false;
3794		synchronized (this.conversations) {
3795			boolean domainJid = blockedJid.getLocal() == null;
3796			for (Conversation conversation : this.conversations) {
3797				boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
3798						|| blockedJid.equals(conversation.getJid().asBareJid());
3799				if (conversation.getAccount() == account
3800						&& conversation.getMode() == Conversation.MODE_SINGLE
3801						&& jidMatches) {
3802					this.conversations.remove(conversation);
3803					markRead(conversation);
3804					conversation.setStatus(Conversation.STATUS_ARCHIVED);
3805					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
3806					updateConversation(conversation);
3807					removed = true;
3808				}
3809			}
3810		}
3811		return removed;
3812	}
3813
3814	public void sendUnblockRequest(final Blockable blockable) {
3815		if (blockable != null && blockable.getJid() != null) {
3816			final Jid jid = blockable.getBlockedJid();
3817			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3818				@Override
3819				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3820					if (packet.getType() == IqPacket.TYPE.RESULT) {
3821						account.getBlocklist().remove(jid);
3822						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3823					}
3824				}
3825			});
3826		}
3827	}
3828
3829	public void publishDisplayName(Account account) {
3830		String displayName = account.getDisplayName();
3831		if (displayName != null && !displayName.isEmpty()) {
3832			IqPacket publish = mIqGenerator.publishNick(displayName);
3833			sendIqPacket(account, publish, (account1, packet) -> {
3834				if (packet.getType() == IqPacket.TYPE.ERROR) {
3835					Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": could not publish nick");
3836				}
3837			});
3838		}
3839	}
3840
3841	public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
3842		ServiceDiscoveryResult result = discoCache.get(key);
3843		if (result != null) {
3844			return result;
3845		} else {
3846			result = databaseBackend.findDiscoveryResult(key.first, key.second);
3847			if (result != null) {
3848				discoCache.put(key, result);
3849			}
3850			return result;
3851		}
3852	}
3853
3854	public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3855		final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
3856		ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3857		if (disco != null) {
3858			presence.setServiceDiscoveryResult(disco);
3859		} else {
3860			if (!account.inProgressDiscoFetches.contains(key)) {
3861				account.inProgressDiscoFetches.add(key);
3862				IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3863				request.setTo(jid);
3864				final String node = presence.getNode();
3865				final String ver = presence.getVer();
3866				final Element query = request.query("http://jabber.org/protocol/disco#info");
3867				if (node != null && ver != null) {
3868					query.setAttribute("node",node+"#"+ver);
3869				}
3870				Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
3871				sendIqPacket(account, request, (a, response) -> {
3872					if (response.getType() == IqPacket.TYPE.RESULT) {
3873						ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
3874						if (presence.getVer().equals(discoveryResult.getVer())) {
3875							databaseBackend.insertDiscoveryResult(discoveryResult);
3876							injectServiceDiscoveryResult(a.getRoster(), presence.getHash(), presence.getVer(), discoveryResult);
3877						} else {
3878							Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
3879						}
3880					}
3881					a.inProgressDiscoFetches.remove(key);
3882				});
3883			}
3884		}
3885	}
3886
3887	private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3888		for (Contact contact : roster.getContacts()) {
3889			for (Presence presence : contact.getPresences().getPresences().values()) {
3890				if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3891					presence.setServiceDiscoveryResult(disco);
3892				}
3893			}
3894		}
3895	}
3896
3897	public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3898		final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
3899		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3900		request.addChild("prefs", version.namespace);
3901		sendIqPacket(account, request, (account1, packet) -> {
3902			Element prefs = packet.findChild("prefs", version.namespace);
3903			if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3904				callback.onPreferencesFetched(prefs);
3905			} else {
3906				callback.onPreferencesFetchFailed();
3907			}
3908		});
3909	}
3910
3911	public PushManagementService getPushManagementService() {
3912		return mPushManagementService;
3913	}
3914
3915	public Account getPendingAccount() {
3916		Account pending = null;
3917		for (Account account : getAccounts()) {
3918			if (!account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY)) {
3919				pending = account;
3920			} else {
3921				return null;
3922			}
3923		}
3924		return pending;
3925	}
3926
3927	public void changeStatus(Account account, PresenceTemplate template, String signature) {
3928		if (!template.getStatusMessage().isEmpty()) {
3929			databaseBackend.insertPresenceTemplate(template);
3930		}
3931		account.setPgpSignature(signature);
3932		account.setPresenceStatus(template.getStatus());
3933		account.setPresenceStatusMessage(template.getStatusMessage());
3934		databaseBackend.updateAccount(account);
3935		sendPresence(account);
3936	}
3937
3938	public List<PresenceTemplate> getPresenceTemplates(Account account) {
3939		List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3940		for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3941			if (!templates.contains(template)) {
3942				templates.add(0, template);
3943			}
3944		}
3945		return templates;
3946	}
3947
3948	public void saveConversationAsBookmark(Conversation conversation, String name) {
3949		Account account = conversation.getAccount();
3950		Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
3951		if (!conversation.getJid().isBareJid()) {
3952			bookmark.setNick(conversation.getJid().getResource());
3953		}
3954		if (!TextUtils.isEmpty(name)) {
3955			bookmark.setBookmarkName(name);
3956		}
3957		bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
3958		account.getBookmarks().add(bookmark);
3959		pushBookmarks(account);
3960		bookmark.setConversation(conversation);
3961	}
3962
3963	public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
3964		boolean performedVerification = false;
3965		final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
3966		for (XmppUri.Fingerprint fp : fingerprints) {
3967			if (fp.type == XmppUri.FingerprintType.OMEMO) {
3968				String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
3969				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3970				if (fingerprintStatus != null) {
3971					if (!fingerprintStatus.isVerified()) {
3972						performedVerification = true;
3973						axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
3974					}
3975				} else {
3976					axolotlService.preVerifyFingerprint(contact, fingerprint);
3977				}
3978			}
3979		}
3980		return performedVerification;
3981	}
3982
3983	public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
3984		final AxolotlService axolotlService = account.getAxolotlService();
3985		boolean verifiedSomething = false;
3986		for (XmppUri.Fingerprint fp : fingerprints) {
3987			if (fp.type == XmppUri.FingerprintType.OMEMO) {
3988				String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
3989				Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
3990				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3991				if (fingerprintStatus != null) {
3992					if (!fingerprintStatus.isVerified()) {
3993						axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
3994						verifiedSomething = true;
3995					}
3996				} else {
3997					axolotlService.preVerifyFingerprint(account, fingerprint);
3998					verifiedSomething = true;
3999				}
4000			}
4001		}
4002		return verifiedSomething;
4003	}
4004
4005	public boolean blindTrustBeforeVerification() {
4006		return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
4007	}
4008
4009	public ShortcutService getShortcutService() {
4010		return mShortcutService;
4011	}
4012
4013	public void pushMamPreferences(Account account, Element prefs) {
4014		IqPacket set = new IqPacket(IqPacket.TYPE.SET);
4015		set.addChild(prefs);
4016		sendIqPacket(account, set, null);
4017	}
4018
4019	public interface OnMamPreferencesFetched {
4020		void onPreferencesFetched(Element prefs);
4021
4022		void onPreferencesFetchFailed();
4023	}
4024
4025	public interface OnAccountCreated {
4026		void onAccountCreated(Account account);
4027
4028		void informUser(int r);
4029	}
4030
4031	public interface OnMoreMessagesLoaded {
4032		void onMoreMessagesLoaded(int count, Conversation conversation);
4033
4034		void informUser(int r);
4035	}
4036
4037	public interface OnAccountPasswordChanged {
4038		void onPasswordChangeSucceeded();
4039
4040		void onPasswordChangeFailed();
4041	}
4042
4043	public interface OnAffiliationChanged {
4044		void onAffiliationChangedSuccessful(Jid jid);
4045
4046		void onAffiliationChangeFailed(Jid jid, int resId);
4047	}
4048
4049	public interface OnRoleChanged {
4050		void onRoleChangedSuccessful(String nick);
4051
4052		void onRoleChangeFailed(String nick, int resid);
4053	}
4054
4055	public interface OnConversationUpdate {
4056		void onConversationUpdate();
4057	}
4058
4059	public interface OnAccountUpdate {
4060		void onAccountUpdate();
4061	}
4062
4063	public interface OnCaptchaRequested {
4064		void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
4065	}
4066
4067	public interface OnRosterUpdate {
4068		void onRosterUpdate();
4069	}
4070
4071	public interface OnMucRosterUpdate {
4072		void onMucRosterUpdate();
4073	}
4074
4075	public interface OnConferenceConfigurationFetched {
4076		void onConferenceConfigurationFetched(Conversation conversation);
4077
4078		void onFetchFailed(Conversation conversation, Element error);
4079	}
4080
4081	public interface OnConferenceJoined {
4082		void onConferenceJoined(Conversation conversation);
4083	}
4084
4085	public interface OnConfigurationPushed {
4086		void onPushSucceeded();
4087
4088		void onPushFailed();
4089	}
4090
4091	public interface OnShowErrorToast {
4092		void onShowErrorToast(int resId);
4093	}
4094
4095	public class XmppConnectionBinder extends Binder {
4096		public XmppConnectionService getService() {
4097			return XmppConnectionService.this;
4098		}
4099	}
4100
4101	private class InternalEventReceiver extends BroadcastReceiver {
4102
4103        @Override
4104        public void onReceive(Context context, Intent intent) {
4105            onStartCommand(intent,0,0);
4106        }
4107    }
4108}