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