XmppConnectionService.java

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