XmppConnectionService.java

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