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