XmppConnectionService.java

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