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(this);
 229    private AvatarService mAvatarService = new AvatarService(this);
 230    private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
 231    private PushManagementService mPushManagementService = new PushManagementService(this);
 232    private QuickConversationsService mQuickConversationsService = new QuickConversationsService(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 && c.getMucOptions().isContactInRoom(contact)) {
1675			    results.add(c);
1676			}
1677		}
1678		return results;
1679	}
1680
1681	public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1682		for (final Conversation conversation : haystack) {
1683			if (conversation.getContact() == contact) {
1684				return conversation;
1685			}
1686		}
1687		return null;
1688	}
1689
1690	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1691		if (jid == null) {
1692			return null;
1693		}
1694		for (final Conversation conversation : haystack) {
1695			if ((account == null || conversation.getAccount() == account)
1696					&& (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
1697				return conversation;
1698			}
1699		}
1700		return null;
1701	}
1702
1703	public boolean isConversationsListEmpty(final Conversation ignore) {
1704		synchronized (this.conversations) {
1705			final int size = this.conversations.size();
1706			return size == 0 || size == 1 && this.conversations.get(0) == ignore;
1707		}
1708	}
1709
1710	public boolean isConversationStillOpen(final Conversation conversation) {
1711		synchronized (this.conversations) {
1712			for (Conversation current : this.conversations) {
1713				if (current == conversation) {
1714					return true;
1715				}
1716			}
1717		}
1718		return false;
1719	}
1720
1721	public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
1722		return this.findOrCreateConversation(account, jid, muc, false, async);
1723	}
1724
1725	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
1726		return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
1727	}
1728
1729	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
1730		synchronized (this.conversations) {
1731			Conversation conversation = find(account, jid);
1732			if (conversation != null) {
1733				return conversation;
1734			}
1735			conversation = databaseBackend.findConversation(account, jid);
1736			final boolean loadMessagesFromDb;
1737			if (conversation != null) {
1738				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1739				conversation.setAccount(account);
1740				if (muc) {
1741					conversation.setMode(Conversation.MODE_MULTI);
1742					conversation.setContactJid(jid);
1743				} else {
1744					conversation.setMode(Conversation.MODE_SINGLE);
1745					conversation.setContactJid(jid.asBareJid());
1746				}
1747				databaseBackend.updateConversation(conversation);
1748				loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
1749			} else {
1750				String conversationName;
1751				Contact contact = account.getRoster().getContact(jid);
1752				if (contact != null) {
1753					conversationName = contact.getDisplayName();
1754				} else {
1755					conversationName = jid.getLocal();
1756				}
1757				if (muc) {
1758					conversation = new Conversation(conversationName, account, jid,
1759							Conversation.MODE_MULTI);
1760				} else {
1761					conversation = new Conversation(conversationName, account, jid.asBareJid(),
1762							Conversation.MODE_SINGLE);
1763				}
1764				this.databaseBackend.createConversation(conversation);
1765				loadMessagesFromDb = false;
1766			}
1767			final Conversation c = conversation;
1768			final Runnable runnable = () -> {
1769				if (loadMessagesFromDb) {
1770					c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
1771					updateConversationUi();
1772					c.messagesLoaded.set(true);
1773				}
1774				if (account.getXmppConnection() != null
1775						&& !c.getContact().isBlocked()
1776						&& account.getXmppConnection().getFeatures().mam()
1777						&& !muc) {
1778					if (query == null) {
1779						mMessageArchiveService.query(c);
1780					} else {
1781						if (query.getConversation() == null) {
1782							mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
1783						}
1784					}
1785				}
1786				checkDeletedFiles(c);
1787				if (joinAfterCreate) {
1788					joinMuc(c);
1789				}
1790			};
1791			if (async) {
1792				mDatabaseReaderExecutor.execute(runnable);
1793			} else {
1794				runnable.run();
1795			}
1796			this.conversations.add(conversation);
1797			updateConversationUi();
1798			return conversation;
1799		}
1800	}
1801
1802	public void archiveConversation(Conversation conversation) {
1803		getNotificationService().clear(conversation);
1804		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1805		conversation.setNextMessage(null);
1806		synchronized (this.conversations) {
1807			getMessageArchiveService().kill(conversation);
1808			if (conversation.getMode() == Conversation.MODE_MULTI) {
1809				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1810					Bookmark bookmark = conversation.getBookmark();
1811					if (bookmark != null && bookmark.autojoin() && respectAutojoin()) {
1812						bookmark.setAutojoin(false);
1813						pushBookmarks(bookmark.getAccount());
1814					}
1815				}
1816				leaveMuc(conversation);
1817			} else {
1818				if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1819					Log.d(Config.LOGTAG, "Canceling presence request from " + conversation.getJid().toString());
1820					sendPresencePacket(
1821							conversation.getAccount(),
1822							mPresenceGenerator.stopPresenceUpdatesTo(conversation.getContact())
1823					);
1824				}
1825			}
1826			updateConversation(conversation);
1827			this.conversations.remove(conversation);
1828			updateConversationUi();
1829		}
1830	}
1831
1832	public void createAccount(final Account account) {
1833		account.initAccountServices(this);
1834		databaseBackend.createAccount(account);
1835		this.accounts.add(account);
1836		this.reconnectAccountInBackground(account);
1837		updateAccountUi();
1838		syncEnabledAccountSetting();
1839		toggleForegroundService();
1840	}
1841
1842	private void syncEnabledAccountSetting() {
1843		getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts()).apply();
1844	}
1845
1846	public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1847		new Thread(() -> {
1848			try {
1849				final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
1850				final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
1851				if (cert == null) {
1852					callback.informUser(R.string.unable_to_parse_certificate);
1853					return;
1854				}
1855				Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
1856				if (info == null) {
1857					callback.informUser(R.string.certificate_does_not_contain_jid);
1858					return;
1859				}
1860				if (findAccountByJid(info.first) == null) {
1861					Account account = new Account(info.first, "");
1862					account.setPrivateKeyAlias(alias);
1863					account.setOption(Account.OPTION_DISABLED, true);
1864					account.setDisplayName(info.second);
1865					createAccount(account);
1866					callback.onAccountCreated(account);
1867					if (Config.X509_VERIFICATION) {
1868						try {
1869							getMemorizingTrustManager().getNonInteractive(account.getJid().getDomain()).checkClientTrusted(chain, "RSA");
1870						} catch (CertificateException e) {
1871							callback.informUser(R.string.certificate_chain_is_not_trusted);
1872						}
1873					}
1874				} else {
1875					callback.informUser(R.string.account_already_exists);
1876				}
1877			} catch (Exception e) {
1878				e.printStackTrace();
1879				callback.informUser(R.string.unable_to_parse_certificate);
1880			}
1881		}).start();
1882
1883	}
1884
1885	public void updateKeyInAccount(final Account account, final String alias) {
1886		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
1887		try {
1888			X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1889			Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
1890			Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1891			if (info == null) {
1892				showErrorToastInUi(R.string.certificate_does_not_contain_jid);
1893				return;
1894			}
1895			if (account.getJid().asBareJid().equals(info.first)) {
1896				account.setPrivateKeyAlias(alias);
1897				account.setDisplayName(info.second);
1898				databaseBackend.updateAccount(account);
1899				if (Config.X509_VERIFICATION) {
1900					try {
1901						getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1902					} catch (CertificateException e) {
1903						showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1904					}
1905					account.getAxolotlService().regenerateKeys(true);
1906				}
1907			} else {
1908				showErrorToastInUi(R.string.jid_does_not_match_certificate);
1909			}
1910		} catch (Exception e) {
1911			e.printStackTrace();
1912		}
1913	}
1914
1915	public boolean updateAccount(final Account account) {
1916		if (databaseBackend.updateAccount(account)) {
1917			account.setShowErrorNotification(true);
1918			this.statusListener.onStatusChanged(account);
1919			databaseBackend.updateAccount(account);
1920			reconnectAccountInBackground(account);
1921			updateAccountUi();
1922			getNotificationService().updateErrorNotification();
1923			toggleForegroundService();
1924			syncEnabledAccountSetting();
1925			return true;
1926		} else {
1927			return false;
1928		}
1929	}
1930
1931	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1932		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1933		sendIqPacket(account, iq, (a, packet) -> {
1934			if (packet.getType() == IqPacket.TYPE.RESULT) {
1935				a.setPassword(newPassword);
1936				a.setOption(Account.OPTION_MAGIC_CREATE, false);
1937				databaseBackend.updateAccount(a);
1938				callback.onPasswordChangeSucceeded();
1939			} else {
1940				callback.onPasswordChangeFailed();
1941			}
1942		});
1943	}
1944
1945	public void deleteAccount(final Account account) {
1946		synchronized (this.conversations) {
1947			for (final Conversation conversation : conversations) {
1948				if (conversation.getAccount() == account) {
1949					if (conversation.getMode() == Conversation.MODE_MULTI) {
1950						leaveMuc(conversation);
1951					}
1952					conversations.remove(conversation);
1953				}
1954			}
1955			if (account.getXmppConnection() != null) {
1956				new Thread(() -> disconnect(account, true)).start();
1957			}
1958			final Runnable runnable = () -> {
1959				if (!databaseBackend.deleteAccount(account)) {
1960					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
1961				}
1962			};
1963			mDatabaseWriterExecutor.execute(runnable);
1964			this.accounts.remove(account);
1965			this.mRosterSyncTaskManager.clear(account);
1966			updateAccountUi();
1967			getNotificationService().updateErrorNotification();
1968			syncEnabledAccountSetting();
1969			toggleForegroundService();
1970		}
1971	}
1972
1973	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1974		final boolean remainingListeners;
1975		synchronized (LISTENER_LOCK) {
1976			remainingListeners = checkListeners();
1977			if (!this.mOnConversationUpdates.add(listener)) {
1978				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as ConversationListChangedListener");
1979			}
1980			this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
1981		}
1982		if (remainingListeners) {
1983			switchToForeground();
1984		}
1985	}
1986
1987	public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
1988		final boolean remainingListeners;
1989		synchronized (LISTENER_LOCK) {
1990			this.mOnConversationUpdates.remove(listener);
1991			this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
1992			remainingListeners = checkListeners();
1993		}
1994		if (remainingListeners) {
1995			switchToBackground();
1996		}
1997	}
1998
1999	public void setOnShowErrorToastListener(OnShowErrorToast listener) {
2000		final boolean remainingListeners;
2001		synchronized (LISTENER_LOCK) {
2002			remainingListeners = checkListeners();
2003			if (!this.mOnShowErrorToasts.add(listener)) {
2004				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnShowErrorToastListener");
2005			}
2006		}
2007		if (remainingListeners) {
2008			switchToForeground();
2009		}
2010	}
2011
2012	public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
2013		final boolean remainingListeners;
2014		synchronized (LISTENER_LOCK) {
2015			this.mOnShowErrorToasts.remove(onShowErrorToast);
2016			remainingListeners = checkListeners();
2017		}
2018		if (remainingListeners) {
2019			switchToBackground();
2020		}
2021	}
2022
2023	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
2024		final boolean remainingListeners;
2025		synchronized (LISTENER_LOCK) {
2026			remainingListeners = checkListeners();
2027			if (!this.mOnAccountUpdates.add(listener)) {
2028				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnAccountListChangedtListener");
2029			}
2030		}
2031		if (remainingListeners) {
2032			switchToForeground();
2033		}
2034	}
2035
2036	public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
2037		final boolean remainingListeners;
2038		synchronized (LISTENER_LOCK) {
2039			this.mOnAccountUpdates.remove(listener);
2040			remainingListeners = checkListeners();
2041		}
2042		if (remainingListeners) {
2043			switchToBackground();
2044		}
2045	}
2046
2047	public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2048		final boolean remainingListeners;
2049		synchronized (LISTENER_LOCK) {
2050			remainingListeners = checkListeners();
2051			if (!this.mOnCaptchaRequested.add(listener)) {
2052				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnCaptchaRequestListener");
2053			}
2054		}
2055		if (remainingListeners) {
2056			switchToForeground();
2057		}
2058	}
2059
2060	public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2061		final boolean remainingListeners;
2062		synchronized (LISTENER_LOCK) {
2063			this.mOnCaptchaRequested.remove(listener);
2064			remainingListeners = checkListeners();
2065		}
2066		if (remainingListeners) {
2067			switchToBackground();
2068		}
2069	}
2070
2071	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
2072		final boolean remainingListeners;
2073		synchronized (LISTENER_LOCK) {
2074			remainingListeners = checkListeners();
2075			if (!this.mOnRosterUpdates.add(listener)) {
2076				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnRosterUpdateListener");
2077			}
2078		}
2079		if (remainingListeners) {
2080			switchToForeground();
2081		}
2082	}
2083
2084	public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
2085		final boolean remainingListeners;
2086		synchronized (LISTENER_LOCK) {
2087			this.mOnRosterUpdates.remove(listener);
2088			remainingListeners = checkListeners();
2089		}
2090		if (remainingListeners) {
2091			switchToBackground();
2092		}
2093	}
2094
2095	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2096		final boolean remainingListeners;
2097		synchronized (LISTENER_LOCK) {
2098			remainingListeners = checkListeners();
2099			if (!this.mOnUpdateBlocklist.add(listener)) {
2100				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnUpdateBlocklistListener");
2101			}
2102		}
2103		if (remainingListeners) {
2104			switchToForeground();
2105		}
2106	}
2107
2108	public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2109		final boolean remainingListeners;
2110		synchronized (LISTENER_LOCK) {
2111			this.mOnUpdateBlocklist.remove(listener);
2112			remainingListeners = checkListeners();
2113		}
2114		if (remainingListeners) {
2115			switchToBackground();
2116		}
2117	}
2118
2119	public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2120		final boolean remainingListeners;
2121		synchronized (LISTENER_LOCK) {
2122			remainingListeners = checkListeners();
2123			if (!this.mOnKeyStatusUpdated.add(listener)) {
2124				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnKeyStatusUpdateListener");
2125			}
2126		}
2127		if (remainingListeners) {
2128			switchToForeground();
2129		}
2130	}
2131
2132	public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
2133		final boolean remainingListeners;
2134		synchronized (LISTENER_LOCK) {
2135			this.mOnKeyStatusUpdated.remove(listener);
2136			remainingListeners = checkListeners();
2137		}
2138		if (remainingListeners) {
2139			switchToBackground();
2140		}
2141	}
2142
2143	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2144		final boolean remainingListeners;
2145		synchronized (LISTENER_LOCK) {
2146			remainingListeners = checkListeners();
2147			if (!this.mOnMucRosterUpdate.add(listener)) {
2148				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnMucRosterListener");
2149			}
2150		}
2151		if (remainingListeners) {
2152			switchToForeground();
2153		}
2154	}
2155
2156	public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
2157		final boolean remainingListeners;
2158		synchronized (LISTENER_LOCK) {
2159			this.mOnMucRosterUpdate.remove(listener);
2160			remainingListeners = checkListeners();
2161		}
2162		if (remainingListeners) {
2163			switchToBackground();
2164		}
2165	}
2166
2167	public boolean checkListeners() {
2168		return (this.mOnAccountUpdates.size() == 0
2169				&& this.mOnConversationUpdates.size() == 0
2170				&& this.mOnRosterUpdates.size() == 0
2171				&& this.mOnCaptchaRequested.size() == 0
2172				&& this.mOnMucRosterUpdate.size() == 0
2173				&& this.mOnUpdateBlocklist.size() == 0
2174				&& this.mOnShowErrorToasts.size() == 0
2175				&& this.mOnKeyStatusUpdated.size() == 0);
2176	}
2177
2178	private void switchToForeground() {
2179		final boolean broadcastLastActivity = broadcastLastActivity();
2180		for (Conversation conversation : getConversations()) {
2181			if (conversation.getMode() == Conversation.MODE_MULTI) {
2182				conversation.getMucOptions().resetChatState();
2183			} else {
2184				conversation.setIncomingChatState(Config.DEFAULT_CHATSTATE);
2185			}
2186		}
2187		for (Account account : getAccounts()) {
2188			if (account.getStatus() == Account.State.ONLINE) {
2189				account.deactivateGracePeriod();
2190				final XmppConnection connection = account.getXmppConnection();
2191				if (connection != null) {
2192					if (connection.getFeatures().csi()) {
2193						connection.sendActive();
2194					}
2195					if (broadcastLastActivity) {
2196						sendPresence(account, false); //send new presence but don't include idle because we are not
2197					}
2198				}
2199			}
2200		}
2201		Log.d(Config.LOGTAG, "app switched into foreground");
2202	}
2203
2204	private void switchToBackground() {
2205		final boolean broadcastLastActivity = broadcastLastActivity();
2206		if (broadcastLastActivity) {
2207			mLastActivity = System.currentTimeMillis();
2208			final SharedPreferences.Editor editor = getPreferences().edit();
2209			editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
2210			editor.apply();
2211		}
2212		for (Account account : getAccounts()) {
2213			if (account.getStatus() == Account.State.ONLINE) {
2214				XmppConnection connection = account.getXmppConnection();
2215				if (connection != null) {
2216					if (broadcastLastActivity) {
2217						sendPresence(account, true);
2218					}
2219					if (connection.getFeatures().csi()) {
2220						connection.sendInactive();
2221					}
2222				}
2223			}
2224		}
2225		this.mNotificationService.setIsInForeground(false);
2226		Log.d(Config.LOGTAG, "app switched into background");
2227	}
2228
2229	private void connectMultiModeConversations(Account account) {
2230		List<Conversation> conversations = getConversations();
2231		for (Conversation conversation : conversations) {
2232			if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2233				joinMuc(conversation);
2234			}
2235		}
2236	}
2237
2238	public void joinMuc(Conversation conversation) {
2239		joinMuc(conversation, null, false);
2240	}
2241
2242	public void joinMuc(Conversation conversation, boolean followedInvite) {
2243		joinMuc(conversation, null, followedInvite);
2244	}
2245
2246	private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2247		joinMuc(conversation, onConferenceJoined, false);
2248	}
2249
2250	private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2251		Account account = conversation.getAccount();
2252		account.pendingConferenceJoins.remove(conversation);
2253		account.pendingConferenceLeaves.remove(conversation);
2254		if (account.getStatus() == Account.State.ONLINE) {
2255			sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
2256			conversation.resetMucOptions();
2257			if (onConferenceJoined != null) {
2258				conversation.getMucOptions().flagNoAutoPushConfiguration();
2259			}
2260			conversation.setHasMessagesLeftOnServer(false);
2261			fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2262
2263				private void join(Conversation conversation) {
2264					Account account = conversation.getAccount();
2265					final MucOptions mucOptions = conversation.getMucOptions();
2266					final Jid joinJid = mucOptions.getSelf().getFullJid();
2267					Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
2268					PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
2269					packet.setTo(joinJid);
2270					Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2271					if (conversation.getMucOptions().getPassword() != null) {
2272						x.addChild("password").setContent(mucOptions.getPassword());
2273					}
2274
2275					if (mucOptions.mamSupport()) {
2276						// Use MAM instead of the limited muc history to get history
2277						x.addChild("history").setAttribute("maxchars", "0");
2278					} else {
2279						// Fallback to muc history
2280						x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
2281					}
2282					sendPresencePacket(account, packet);
2283					if (onConferenceJoined != null) {
2284						onConferenceJoined.onConferenceJoined(conversation);
2285					}
2286					if (!joinJid.equals(conversation.getJid())) {
2287						conversation.setContactJid(joinJid);
2288						databaseBackend.updateConversation(conversation);
2289					}
2290
2291					if (mucOptions.mamSupport()) {
2292						getMessageArchiveService().catchupMUC(conversation);
2293					}
2294					if (mucOptions.isPrivateAndNonAnonymous()) {
2295						fetchConferenceMembers(conversation);
2296						if (followedInvite && conversation.getBookmark() == null) {
2297							saveConversationAsBookmark(conversation, null);
2298						}
2299					}
2300					sendUnsentMessages(conversation);
2301				}
2302
2303				@Override
2304				public void onConferenceConfigurationFetched(Conversation conversation) {
2305					join(conversation);
2306				}
2307
2308				@Override
2309				public void onFetchFailed(final Conversation conversation, Element error) {
2310					if (error != null && "remote-server-not-found".equals(error.getName())) {
2311						conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2312						updateConversationUi();
2313					} else {
2314						join(conversation);
2315						fetchConferenceConfiguration(conversation);
2316					}
2317				}
2318			});
2319			updateConversationUi();
2320		} else {
2321			account.pendingConferenceJoins.add(conversation);
2322			conversation.resetMucOptions();
2323			conversation.setHasMessagesLeftOnServer(false);
2324			updateConversationUi();
2325		}
2326	}
2327
2328	private void fetchConferenceMembers(final Conversation conversation) {
2329		final Account account = conversation.getAccount();
2330		final AxolotlService axolotlService = account.getAxolotlService();
2331		final String[] affiliations = {"member", "admin", "owner"};
2332		OnIqPacketReceived callback = new OnIqPacketReceived() {
2333
2334			private int i = 0;
2335			private boolean success = true;
2336
2337			@Override
2338			public void onIqPacketReceived(Account account, IqPacket packet) {
2339				final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
2340				Element query = packet.query("http://jabber.org/protocol/muc#admin");
2341				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2342					for (Element child : query.getChildren()) {
2343						if ("item".equals(child.getName())) {
2344							MucOptions.User user = AbstractParser.parseItem(conversation, child);
2345							if (!user.realJidMatchesAccount()) {
2346								boolean isNew = conversation.getMucOptions().updateUser(user);
2347								Contact contact = user.getContact();
2348								if (omemoEnabled
2349										&& isNew
2350										&& user.getRealJid() != null
2351										&& (contact == null || !contact.mutualPresenceSubscription())
2352										&& axolotlService.hasEmptyDeviceList(user.getRealJid())) {
2353									axolotlService.fetchDeviceIds(user.getRealJid());
2354								}
2355							}
2356						}
2357					}
2358				} else {
2359					success = false;
2360					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
2361				}
2362				++i;
2363				if (i >= affiliations.length) {
2364					List<Jid> members = conversation.getMucOptions().getMembers(true);
2365					if (success) {
2366						List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
2367						boolean changed = false;
2368						for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
2369							Jid jid = iterator.next();
2370							if (!members.contains(jid) && !members.contains(Jid.ofDomain(jid.getDomain()))) {
2371								iterator.remove();
2372								Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
2373								changed = true;
2374							}
2375						}
2376						if (changed) {
2377							conversation.setAcceptedCryptoTargets(cryptoTargets);
2378							updateConversation(conversation);
2379						}
2380					}
2381					getAvatarService().clear(conversation);
2382					updateMucRosterUi();
2383					updateConversationUi();
2384				}
2385			}
2386		};
2387		for (String affiliation : affiliations) {
2388			sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2389		}
2390		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
2391	}
2392
2393	public void providePasswordForMuc(Conversation conversation, String password) {
2394		if (conversation.getMode() == Conversation.MODE_MULTI) {
2395			conversation.getMucOptions().setPassword(password);
2396			if (conversation.getBookmark() != null) {
2397				if (respectAutojoin()) {
2398					conversation.getBookmark().setAutojoin(true);
2399				}
2400				pushBookmarks(conversation.getAccount());
2401			}
2402			updateConversation(conversation);
2403			joinMuc(conversation);
2404		}
2405	}
2406
2407	private boolean hasEnabledAccounts() {
2408		for (Account account : this.accounts) {
2409			if (account.isEnabled()) {
2410				return true;
2411			}
2412		}
2413		return false;
2414	}
2415
2416
2417	public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
2418        getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
2419    }
2420
2421    public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2422        getAttachments(account.getUuid(),jid.asBareJid(),limit, onMediaLoaded);
2423    }
2424
2425
2426	public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2427        new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
2428    }
2429
2430	public void persistSelfNick(MucOptions.User self) {
2431		final Conversation conversation = self.getConversation();
2432		Jid full = self.getFullJid();
2433		if (!full.equals(conversation.getJid())) {
2434			Log.d(Config.LOGTAG, "nick changed. updating");
2435			conversation.setContactJid(full);
2436			databaseBackend.updateConversation(conversation);
2437		}
2438
2439		Bookmark bookmark = conversation.getBookmark();
2440		if (bookmark != null && !full.getResource().equals(bookmark.getNick())) {
2441			bookmark.setNick(full.getResource());
2442			pushBookmarks(bookmark.getAccount());
2443		}
2444	}
2445
2446	public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2447		final MucOptions options = conversation.getMucOptions();
2448		final Jid joinJid = options.createJoinJid(nick);
2449		if (joinJid == null) {
2450			return false;
2451		}
2452		if (options.online()) {
2453			Account account = conversation.getAccount();
2454			options.setOnRenameListener(new OnRenameListener() {
2455
2456				@Override
2457				public void onSuccess() {
2458					callback.success(conversation);
2459				}
2460
2461				@Override
2462				public void onFailure() {
2463					callback.error(R.string.nick_in_use, conversation);
2464				}
2465			});
2466
2467			PresencePacket packet = new PresencePacket();
2468			packet.setTo(joinJid);
2469			packet.setFrom(conversation.getAccount().getJid());
2470
2471			String sig = account.getPgpSignature();
2472			if (sig != null) {
2473				packet.addChild("status").setContent("online");
2474				packet.addChild("x", "jabber:x:signed").setContent(sig);
2475			}
2476			sendPresencePacket(account, packet);
2477		} else {
2478			conversation.setContactJid(joinJid);
2479			databaseBackend.updateConversation(conversation);
2480			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2481				Bookmark bookmark = conversation.getBookmark();
2482				if (bookmark != null) {
2483					bookmark.setNick(nick);
2484					pushBookmarks(bookmark.getAccount());
2485				}
2486				joinMuc(conversation);
2487			}
2488		}
2489		return true;
2490	}
2491
2492	public void leaveMuc(Conversation conversation) {
2493		leaveMuc(conversation, false);
2494	}
2495
2496	private void leaveMuc(Conversation conversation, boolean now) {
2497		Account account = conversation.getAccount();
2498		account.pendingConferenceJoins.remove(conversation);
2499		account.pendingConferenceLeaves.remove(conversation);
2500		if (account.getStatus() == Account.State.ONLINE || now) {
2501			sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
2502			conversation.getMucOptions().setOffline();
2503			Bookmark bookmark = conversation.getBookmark();
2504			if (bookmark != null) {
2505				bookmark.setConversation(null);
2506			}
2507			Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
2508		} else {
2509			account.pendingConferenceLeaves.add(conversation);
2510		}
2511	}
2512
2513	public String findConferenceServer(final Account account) {
2514		String server;
2515		if (account.getXmppConnection() != null) {
2516			server = account.getXmppConnection().getMucServer();
2517			if (server != null) {
2518				return server;
2519			}
2520		}
2521		for (Account other : getAccounts()) {
2522			if (other != account && other.getXmppConnection() != null) {
2523				server = other.getXmppConnection().getMucServer();
2524				if (server != null) {
2525					return server;
2526				}
2527			}
2528		}
2529		return null;
2530	}
2531
2532	public boolean createAdhocConference(final Account account,
2533	                                     final String name,
2534	                                     final Iterable<Jid> jids,
2535	                                     final UiCallback<Conversation> callback) {
2536		Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2537		if (account.getStatus() == Account.State.ONLINE) {
2538			try {
2539				String server = findConferenceServer(account);
2540				if (server == null) {
2541					if (callback != null) {
2542						callback.error(R.string.no_conference_server_found, null);
2543					}
2544					return false;
2545				}
2546				final Jid jid = Jid.of(CryptoHelper.pronounceable(getRNG()), server, null);
2547				final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
2548				joinMuc(conversation, new OnConferenceJoined() {
2549					@Override
2550					public void onConferenceJoined(final Conversation conversation) {
2551						final Bundle configuration = IqGenerator.defaultRoomConfiguration();
2552						if (!TextUtils.isEmpty(name)) {
2553							configuration.putString("muc#roomconfig_roomname", name);
2554						}
2555						pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
2556							@Override
2557							public void onPushSucceeded() {
2558								for (Jid invite : jids) {
2559									invite(conversation, invite);
2560								}
2561								if (account.countPresences() > 1) {
2562									directInvite(conversation, account.getJid().asBareJid());
2563								}
2564								saveConversationAsBookmark(conversation, name);
2565								if (callback != null) {
2566									callback.success(conversation);
2567								}
2568							}
2569
2570							@Override
2571							public void onPushFailed() {
2572								archiveConversation(conversation);
2573								if (callback != null) {
2574									callback.error(R.string.conference_creation_failed, conversation);
2575								}
2576							}
2577						});
2578					}
2579				});
2580				return true;
2581			} catch (IllegalArgumentException e) {
2582				if (callback != null) {
2583					callback.error(R.string.conference_creation_failed, null);
2584				}
2585				return false;
2586			}
2587		} else {
2588			if (callback != null) {
2589				callback.error(R.string.not_connected_try_again, null);
2590			}
2591			return false;
2592		}
2593	}
2594
2595	public void fetchConferenceConfiguration(final Conversation conversation) {
2596		fetchConferenceConfiguration(conversation, null);
2597	}
2598
2599	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2600		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2601		request.setTo(conversation.getJid().asBareJid());
2602		request.query("http://jabber.org/protocol/disco#info");
2603		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2604			@Override
2605			public void onIqPacketReceived(Account account, IqPacket packet) {
2606				if (packet.getType() == IqPacket.TYPE.RESULT) {
2607
2608					final MucOptions mucOptions = conversation.getMucOptions();
2609					final Bookmark bookmark = conversation.getBookmark();
2610					final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
2611
2612					if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
2613						Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
2614						updateConversation(conversation);
2615					}
2616
2617					if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
2618						if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
2619							pushBookmarks(account);
2620						}
2621					}
2622
2623
2624					if (callback != null) {
2625						callback.onConferenceConfigurationFetched(conversation);
2626					}
2627
2628
2629
2630					updateConversationUi();
2631				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
2632					if (callback != null) {
2633						callback.onFetchFailed(conversation, packet.getError());
2634					}
2635				}
2636			}
2637		});
2638	}
2639
2640	public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
2641		pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
2642	}
2643
2644	public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
2645        Log.d(Config.LOGTAG,"pushing node configuration");
2646		sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
2647			@Override
2648			public void onIqPacketReceived(Account account, IqPacket packet) {
2649				if (packet.getType() == IqPacket.TYPE.RESULT) {
2650					Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
2651					Element configuration = pubsub == null ? null : pubsub.findChild("configure");
2652					Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
2653					if (x != null) {
2654						Data data = Data.parse(x);
2655						data.submit(options);
2656						sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
2657							@Override
2658							public void onIqPacketReceived(Account account, IqPacket packet) {
2659								if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
2660									Log.d(Config.LOGTAG,account.getJid().asBareJid()+": successfully changed node configuration for node "+node);
2661									callback.onPushSucceeded();
2662								} else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
2663									callback.onPushFailed();
2664								}
2665							}
2666						});
2667					} else if (callback != null) {
2668						callback.onPushFailed();
2669					}
2670				} else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
2671					callback.onPushFailed();
2672				}
2673			}
2674		});
2675	}
2676
2677	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
2678		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2679		request.setTo(conversation.getJid().asBareJid());
2680		request.query("http://jabber.org/protocol/muc#owner");
2681		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2682			@Override
2683			public void onIqPacketReceived(Account account, IqPacket packet) {
2684				if (packet.getType() == IqPacket.TYPE.RESULT) {
2685					Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
2686					data.submit(options);
2687					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2688					set.setTo(conversation.getJid().asBareJid());
2689					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2690					sendIqPacket(account, set, new OnIqPacketReceived() {
2691						@Override
2692						public void onIqPacketReceived(Account account, IqPacket packet) {
2693							if (callback != null) {
2694								if (packet.getType() == IqPacket.TYPE.RESULT) {
2695									callback.onPushSucceeded();
2696								} else {
2697									callback.onPushFailed();
2698								}
2699							}
2700						}
2701					});
2702				} else {
2703					if (callback != null) {
2704						callback.onPushFailed();
2705					}
2706				}
2707			}
2708		});
2709	}
2710
2711	public void pushSubjectToConference(final Conversation conference, final String subject) {
2712		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
2713		this.sendMessagePacket(conference.getAccount(), packet);
2714	}
2715
2716	public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2717		final Jid jid = user.asBareJid();
2718		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2719		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2720			@Override
2721			public void onIqPacketReceived(Account account, IqPacket packet) {
2722				if (packet.getType() == IqPacket.TYPE.RESULT) {
2723					conference.getMucOptions().changeAffiliation(jid, affiliation);
2724					getAvatarService().clear(conference);
2725					callback.onAffiliationChangedSuccessful(jid);
2726				} else {
2727					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2728				}
2729			}
2730		});
2731	}
2732
2733	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2734		List<Jid> jids = new ArrayList<>();
2735		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2736			if (user.getAffiliation() == before && user.getRealJid() != null) {
2737				jids.add(user.getRealJid());
2738			}
2739		}
2740		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2741		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2742	}
2743
2744	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2745		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2746		Log.d(Config.LOGTAG, request.toString());
2747		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2748			@Override
2749			public void onIqPacketReceived(Account account, IqPacket packet) {
2750				Log.d(Config.LOGTAG, packet.toString());
2751				if (packet.getType() == IqPacket.TYPE.RESULT) {
2752					callback.onRoleChangedSuccessful(nick);
2753				} else {
2754					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2755				}
2756			}
2757		});
2758	}
2759
2760	private void disconnect(Account account, boolean force) {
2761		if ((account.getStatus() == Account.State.ONLINE)
2762				|| (account.getStatus() == Account.State.DISABLED)) {
2763			final XmppConnection connection = account.getXmppConnection();
2764			if (!force) {
2765				List<Conversation> conversations = getConversations();
2766				for (Conversation conversation : conversations) {
2767					if (conversation.getAccount() == account) {
2768						if (conversation.getMode() == Conversation.MODE_MULTI) {
2769							leaveMuc(conversation, true);
2770						}
2771					}
2772				}
2773				sendOfflinePresence(account);
2774			}
2775			connection.disconnect(force);
2776		}
2777	}
2778
2779	@Override
2780	public IBinder onBind(Intent intent) {
2781		return mBinder;
2782	}
2783
2784	public void updateMessage(Message message) {
2785		updateMessage(message, true);
2786	}
2787
2788	public void updateMessage(Message message, boolean includeBody) {
2789		databaseBackend.updateMessage(message, includeBody);
2790		updateConversationUi();
2791	}
2792
2793	public void updateMessage(Message message, String uuid) {
2794		databaseBackend.updateMessage(message, uuid);
2795		updateConversationUi();
2796	}
2797
2798	protected void syncDirtyContacts(Account account) {
2799		for (Contact contact : account.getRoster().getContacts()) {
2800			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2801				pushContactToServer(contact);
2802			}
2803			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2804				deleteContactOnServer(contact);
2805			}
2806		}
2807	}
2808
2809	public void createContact(Contact contact, boolean autoGrant) {
2810		if (autoGrant) {
2811			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2812			contact.setOption(Contact.Options.ASKING);
2813		}
2814		pushContactToServer(contact);
2815	}
2816
2817	public void pushContactToServer(final Contact contact) {
2818		contact.resetOption(Contact.Options.DIRTY_DELETE);
2819		contact.setOption(Contact.Options.DIRTY_PUSH);
2820		final Account account = contact.getAccount();
2821		if (account.getStatus() == Account.State.ONLINE) {
2822			final boolean ask = contact.getOption(Contact.Options.ASKING);
2823			final boolean sendUpdates = contact
2824					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2825					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2826			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2827			iq.query(Namespace.ROSTER).addChild(contact.asElement());
2828			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2829			if (sendUpdates) {
2830				sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
2831			}
2832			if (ask) {
2833				sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2834			}
2835		} else {
2836			syncRoster(contact.getAccount());
2837		}
2838	}
2839
2840	public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
2841		new Thread(() -> {
2842			final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2843			final int size = Config.AVATAR_SIZE;
2844			final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2845			if (avatar != null) {
2846				if (!getFileBackend().save(avatar)) {
2847					callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
2848					return;
2849				}
2850				avatar.owner = conversation.getJid().asBareJid();
2851				publishMucAvatar(conversation, avatar, callback);
2852			} else {
2853				callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
2854			}
2855		}).start();
2856	}
2857
2858	public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
2859		new Thread(() -> {
2860			final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2861			final int size = Config.AVATAR_SIZE;
2862			final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2863			if (avatar != null) {
2864				if (!getFileBackend().save(avatar)) {
2865					Log.d(Config.LOGTAG,"unable to save vcard");
2866					callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
2867					return;
2868				}
2869				publishAvatar(account, avatar, callback);
2870			} else {
2871				callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
2872			}
2873		}).start();
2874
2875	}
2876
2877	private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
2878		final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
2879		sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
2880			boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
2881			if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
2882				Element vcard = response.findChild("vCard", "vcard-temp");
2883				if (vcard == null) {
2884					vcard = new Element("vCard", "vcard-temp");
2885				}
2886				Element photo = vcard.findChild("PHOTO");
2887				if (photo == null) {
2888					photo = vcard.addChild("PHOTO");
2889				}
2890				photo.clearChildren();
2891				photo.addChild("TYPE").setContent(avatar.type);
2892				photo.addChild("BINVAL").setContent(avatar.image);
2893				IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
2894				publication.setTo(conversation.getJid().asBareJid());
2895				publication.addChild(vcard);
2896				sendIqPacket(account, publication, (a1, publicationResponse) -> {
2897					if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
2898						callback.onAvatarPublicationSucceeded();
2899					} else {
2900						Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getError());
2901						callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
2902					}
2903				});
2904			} else {
2905				Log.d(Config.LOGTAG, "failed to request vcard " + response.toString());
2906				callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
2907			}
2908		});
2909	}
2910
2911	public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
2912		IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2913		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2914
2915			@Override
2916			public void onIqPacketReceived(Account account, IqPacket result) {
2917				if (result.getType() == IqPacket.TYPE.RESULT) {
2918					final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar);
2919					sendIqPacket(account, packet, new OnIqPacketReceived() {
2920						@Override
2921						public void onIqPacketReceived(Account account, IqPacket result) {
2922							if (result.getType() == IqPacket.TYPE.RESULT) {
2923								if (account.setAvatar(avatar.getFilename())) {
2924									getAvatarService().clear(account);
2925									databaseBackend.updateAccount(account);
2926								}
2927								Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
2928								if (callback != null) {
2929									callback.onAvatarPublicationSucceeded();
2930								}
2931							} else {
2932								if (callback != null) {
2933									callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
2934								}
2935							}
2936						}
2937					});
2938				} else {
2939					Element error = result.findChild("error");
2940					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
2941					if (callback != null) {
2942						callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
2943					}
2944				}
2945			}
2946		});
2947	}
2948
2949	public void republishAvatarIfNeeded(Account account) {
2950		if (account.getAxolotlService().isPepBroken()) {
2951			Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
2952			return;
2953		}
2954		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2955		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2956
2957			private Avatar parseAvatar(IqPacket packet) {
2958				Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2959				if (pubsub != null) {
2960					Element items = pubsub.findChild("items");
2961					if (items != null) {
2962						return Avatar.parseMetadata(items);
2963					}
2964				}
2965				return null;
2966			}
2967
2968			private boolean errorIsItemNotFound(IqPacket packet) {
2969				Element error = packet.findChild("error");
2970				return packet.getType() == IqPacket.TYPE.ERROR
2971						&& error != null
2972						&& error.hasChild("item-not-found");
2973			}
2974
2975			@Override
2976			public void onIqPacketReceived(Account account, IqPacket packet) {
2977				if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2978					Avatar serverAvatar = parseAvatar(packet);
2979					if (serverAvatar == null && account.getAvatar() != null) {
2980						Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2981						if (avatar != null) {
2982							Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
2983							publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2984						} else {
2985							Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
2986						}
2987					}
2988				}
2989			}
2990		});
2991	}
2992
2993	public void fetchAvatar(Account account, Avatar avatar) {
2994		fetchAvatar(account, avatar, null);
2995	}
2996
2997	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2998		final String KEY = generateFetchKey(account, avatar);
2999		synchronized (this.mInProgressAvatarFetches) {
3000			if (!this.mInProgressAvatarFetches.contains(KEY)) {
3001				switch (avatar.origin) {
3002					case PEP:
3003						this.mInProgressAvatarFetches.add(KEY);
3004						fetchAvatarPep(account, avatar, callback);
3005						break;
3006					case VCARD:
3007						this.mInProgressAvatarFetches.add(KEY);
3008						fetchAvatarVcard(account, avatar, callback);
3009						break;
3010				}
3011			}
3012		}
3013	}
3014
3015	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3016		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
3017		sendIqPacket(account, packet, (a, result) -> {
3018			synchronized (mInProgressAvatarFetches) {
3019				mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
3020			}
3021			final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
3022			if (result.getType() == IqPacket.TYPE.RESULT) {
3023				avatar.image = mIqParser.avatarData(result);
3024				if (avatar.image != null) {
3025					if (getFileBackend().save(avatar)) {
3026						if (a.getJid().asBareJid().equals(avatar.owner)) {
3027							if (a.setAvatar(avatar.getFilename())) {
3028								databaseBackend.updateAccount(a);
3029							}
3030							getAvatarService().clear(a);
3031							updateConversationUi();
3032							updateAccountUi();
3033						} else {
3034							Contact contact = a.getRoster().getContact(avatar.owner);
3035							if (contact.setAvatar(avatar)) {
3036								syncRoster(account);
3037								getAvatarService().clear(contact);
3038								updateConversationUi();
3039								updateRosterUi();
3040							}
3041						}
3042						if (callback != null) {
3043							callback.success(avatar);
3044						}
3045						Log.d(Config.LOGTAG, a.getJid().asBareJid()
3046								+ ": successfully fetched pep avatar for " + avatar.owner);
3047						return;
3048					}
3049				} else {
3050
3051					Log.d(Config.LOGTAG, ERROR + "(parsing error)");
3052				}
3053			} else {
3054				Element error = result.findChild("error");
3055				if (error == null) {
3056					Log.d(Config.LOGTAG, ERROR + "(server error)");
3057				} else {
3058					Log.d(Config.LOGTAG, ERROR + error.toString());
3059				}
3060			}
3061			if (callback != null) {
3062				callback.error(0, null);
3063			}
3064
3065		});
3066	}
3067
3068	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3069		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
3070		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3071			@Override
3072			public void onIqPacketReceived(Account account, IqPacket packet) {
3073				synchronized (mInProgressAvatarFetches) {
3074					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
3075				}
3076				if (packet.getType() == IqPacket.TYPE.RESULT) {
3077					Element vCard = packet.findChild("vCard", "vcard-temp");
3078					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
3079					String image = photo != null ? photo.findChildContent("BINVAL") : null;
3080					if (image != null) {
3081						avatar.image = image;
3082						if (getFileBackend().save(avatar)) {
3083							Log.d(Config.LOGTAG, account.getJid().asBareJid()
3084									+ ": successfully fetched vCard avatar for " + avatar.owner);
3085							if (avatar.owner.isBareJid()) {
3086								if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
3087									Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
3088									account.setAvatar(avatar.getFilename());
3089									databaseBackend.updateAccount(account);
3090									getAvatarService().clear(account);
3091									updateAccountUi();
3092								} else {
3093									Contact contact = account.getRoster().getContact(avatar.owner);
3094									if (contact.setAvatar(avatar)) {
3095										syncRoster(account);
3096										getAvatarService().clear(contact);
3097										updateRosterUi();
3098									}
3099								}
3100								updateConversationUi();
3101							} else {
3102								Conversation conversation = find(account, avatar.owner.asBareJid());
3103								if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
3104									MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
3105									if (user != null) {
3106										if (user.setAvatar(avatar)) {
3107											getAvatarService().clear(user);
3108											updateConversationUi();
3109											updateMucRosterUi();
3110										}
3111										if (user.getRealJid() != null) {
3112										    Contact contact = account.getRoster().getContact(user.getRealJid());
3113										    if (contact.setAvatar(avatar)) {
3114                                                syncRoster(account);
3115                                                getAvatarService().clear(contact);
3116                                                updateRosterUi();
3117                                            }
3118                                        }
3119									}
3120								}
3121							}
3122						}
3123					}
3124				}
3125			}
3126		});
3127	}
3128
3129	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
3130		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3131		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3132
3133			@Override
3134			public void onIqPacketReceived(Account account, IqPacket packet) {
3135				if (packet.getType() == IqPacket.TYPE.RESULT) {
3136					Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3137					if (pubsub != null) {
3138						Element items = pubsub.findChild("items");
3139						if (items != null) {
3140							Avatar avatar = Avatar.parseMetadata(items);
3141							if (avatar != null) {
3142								avatar.owner = account.getJid().asBareJid();
3143								if (fileBackend.isAvatarCached(avatar)) {
3144									if (account.setAvatar(avatar.getFilename())) {
3145										databaseBackend.updateAccount(account);
3146									}
3147									getAvatarService().clear(account);
3148									callback.success(avatar);
3149								} else {
3150									fetchAvatarPep(account, avatar, callback);
3151								}
3152								return;
3153							}
3154						}
3155					}
3156				}
3157				callback.error(0, null);
3158			}
3159		});
3160	}
3161
3162	public void deleteContactOnServer(Contact contact) {
3163		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
3164		contact.resetOption(Contact.Options.DIRTY_PUSH);
3165		contact.setOption(Contact.Options.DIRTY_DELETE);
3166		Account account = contact.getAccount();
3167		if (account.getStatus() == Account.State.ONLINE) {
3168			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3169			Element item = iq.query(Namespace.ROSTER).addChild("item");
3170			item.setAttribute("jid", contact.getJid().toString());
3171			item.setAttribute("subscription", "remove");
3172			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3173		}
3174	}
3175
3176	public void updateConversation(final Conversation conversation) {
3177		mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
3178	}
3179
3180	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
3181		synchronized (account) {
3182			XmppConnection connection = account.getXmppConnection();
3183			if (connection == null) {
3184				connection = createConnection(account);
3185				account.setXmppConnection(connection);
3186			}
3187			boolean hasInternet = hasInternetConnection();
3188			if (account.isEnabled() && hasInternet) {
3189				if (!force) {
3190					disconnect(account, false);
3191				}
3192				Thread thread = new Thread(connection);
3193				connection.setInteractive(interactive);
3194				connection.prepareNewConnection();
3195				connection.interrupt();
3196				thread.start();
3197				scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
3198			} else {
3199				disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
3200				account.getRoster().clearPresences();
3201				connection.resetEverything();
3202				final AxolotlService axolotlService = account.getAxolotlService();
3203				if (axolotlService != null) {
3204					axolotlService.resetBrokenness();
3205				}
3206				if (!hasInternet) {
3207					account.setStatus(Account.State.NO_INTERNET);
3208				}
3209			}
3210		}
3211	}
3212
3213	public void reconnectAccountInBackground(final Account account) {
3214		new Thread(() -> reconnectAccount(account, false, true)).start();
3215	}
3216
3217	public void invite(Conversation conversation, Jid contact) {
3218		Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
3219		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
3220		sendMessagePacket(conversation.getAccount(), packet);
3221	}
3222
3223	public void directInvite(Conversation conversation, Jid jid) {
3224		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
3225		sendMessagePacket(conversation.getAccount(), packet);
3226	}
3227
3228	public void resetSendingToWaiting(Account account) {
3229		for (Conversation conversation : getConversations()) {
3230			if (conversation.getAccount() == account) {
3231				conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
3232			}
3233		}
3234	}
3235
3236	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
3237		return markMessage(account, recipient, uuid, status, null);
3238	}
3239
3240	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
3241		if (uuid == null) {
3242			return null;
3243		}
3244		for (Conversation conversation : getConversations()) {
3245			if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
3246				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
3247				if (message != null) {
3248					markMessage(message, status, errorMessage);
3249				}
3250				return message;
3251			}
3252		}
3253		return null;
3254	}
3255
3256	public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) {
3257		if (uuid == null) {
3258			return false;
3259		} else {
3260			Message message = conversation.findSentMessageWithUuid(uuid);
3261			if (message != null) {
3262				if (message.getServerMsgId() == null) {
3263					message.setServerMsgId(serverMessageId);
3264				}
3265				markMessage(message, status);
3266				return true;
3267			} else {
3268				return false;
3269			}
3270		}
3271	}
3272
3273	public void markMessage(Message message, int status) {
3274		markMessage(message, status, null);
3275	}
3276
3277
3278	public void markMessage(Message message, int status, String errorMessage) {
3279		final int c = message.getStatus();
3280		if (status == Message.STATUS_SEND_FAILED && (c == Message.STATUS_SEND_RECEIVED || c == Message.STATUS_SEND_DISPLAYED)) {
3281			return;
3282		}
3283		if (status == Message.STATUS_SEND_RECEIVED && c == Message.STATUS_SEND_DISPLAYED) {
3284			return;
3285		}
3286		message.setErrorMessage(errorMessage);
3287		message.setStatus(status);
3288		databaseBackend.updateMessage(message, false);
3289		updateConversationUi();
3290	}
3291
3292	private SharedPreferences getPreferences() {
3293		return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
3294	}
3295
3296	public long getAutomaticMessageDeletionDate() {
3297		final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
3298		return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
3299	}
3300
3301	public long getLongPreference(String name, @IntegerRes int res) {
3302		long defaultValue = getResources().getInteger(res);
3303		try {
3304			return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
3305		} catch (NumberFormatException e) {
3306			return defaultValue;
3307		}
3308	}
3309
3310	public boolean getBooleanPreference(String name, @BoolRes int res) {
3311		return getPreferences().getBoolean(name, getResources().getBoolean(res));
3312	}
3313
3314	public boolean confirmMessages() {
3315		return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
3316	}
3317
3318	public boolean allowMessageCorrection() {
3319		return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
3320	}
3321
3322	public boolean sendChatStates() {
3323		return getBooleanPreference("chat_states", R.bool.chat_states);
3324	}
3325
3326	private boolean respectAutojoin() {
3327		return getBooleanPreference("autojoin", R.bool.autojoin);
3328	}
3329
3330	public boolean indicateReceived() {
3331		return getBooleanPreference("indicate_received", R.bool.indicate_received);
3332	}
3333
3334	public boolean useTorToConnect() {
3335		return Config.FORCE_ORBOT || getBooleanPreference("use_tor", R.bool.use_tor);
3336	}
3337
3338	public boolean showExtendedConnectionOptions() {
3339		return getBooleanPreference("show_connection_options", R.bool.show_connection_options);
3340	}
3341
3342	public boolean broadcastLastActivity() {
3343		return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
3344	}
3345
3346	public int unreadCount() {
3347		int count = 0;
3348		for (Conversation conversation : getConversations()) {
3349			count += conversation.unreadCount();
3350		}
3351		return count;
3352	}
3353
3354
3355	private <T> List<T> threadSafeList(Set<T> set) {
3356		synchronized (LISTENER_LOCK) {
3357			return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
3358		}
3359	}
3360
3361	public void showErrorToastInUi(int resId) {
3362		for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
3363			listener.onShowErrorToast(resId);
3364		}
3365	}
3366
3367	public void updateConversationUi() {
3368		for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
3369			listener.onConversationUpdate();
3370		}
3371	}
3372
3373	public void updateAccountUi() {
3374		for (OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
3375			listener.onAccountUpdate();
3376		}
3377	}
3378
3379	public void updateRosterUi() {
3380		for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
3381			listener.onRosterUpdate();
3382		}
3383	}
3384
3385	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3386		if (mOnCaptchaRequested.size() > 0) {
3387			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3388			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3389					(int) (captcha.getHeight() * metrics.scaledDensity), false);
3390			for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
3391				listener.onCaptchaRequested(account, id, data, scaled);
3392			}
3393			return true;
3394		}
3395		return false;
3396	}
3397
3398	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3399		for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
3400			listener.OnUpdateBlocklist(status);
3401		}
3402	}
3403
3404	public void updateMucRosterUi() {
3405		for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
3406			listener.onMucRosterUpdate();
3407		}
3408	}
3409
3410	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3411		for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
3412			listener.onKeyStatusUpdated(report);
3413		}
3414	}
3415
3416	public Account findAccountByJid(final Jid accountJid) {
3417		for (Account account : this.accounts) {
3418			if (account.getJid().asBareJid().equals(accountJid.asBareJid())) {
3419				return account;
3420			}
3421		}
3422		return null;
3423	}
3424
3425	public Account findAccountByUuid(final String uuid) {
3426		for(Account account : this.accounts) {
3427			if (account.getUuid().equals(uuid)) {
3428				return account;
3429			}
3430		}
3431		return null;
3432	}
3433
3434	public Conversation findConversationByUuid(String uuid) {
3435		for (Conversation conversation : getConversations()) {
3436			if (conversation.getUuid().equals(uuid)) {
3437				return conversation;
3438			}
3439		}
3440		return null;
3441	}
3442
3443	public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
3444		List<Conversation> findings = new ArrayList<>();
3445		for (Conversation c : getConversations()) {
3446			if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
3447				findings.add(c);
3448			}
3449		}
3450		return findings.size() == 1 ? findings.get(0) : null;
3451	}
3452
3453	public boolean markRead(final Conversation conversation, boolean dismiss) {
3454		return markRead(conversation, null, dismiss).size() > 0;
3455	}
3456
3457	public void markRead(final Conversation conversation) {
3458		markRead(conversation, null, true);
3459	}
3460
3461	public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
3462		if (dismiss) {
3463			mNotificationService.clear(conversation);
3464		}
3465		final List<Message> readMessages = conversation.markRead(upToUuid);
3466		if (readMessages.size() > 0) {
3467			Runnable runnable = () -> {
3468				for (Message message : readMessages) {
3469					databaseBackend.updateMessage(message, false);
3470				}
3471			};
3472			mDatabaseWriterExecutor.execute(runnable);
3473			updateUnreadCountBadge();
3474			return readMessages;
3475		} else {
3476			return readMessages;
3477		}
3478	}
3479
3480	public synchronized void updateUnreadCountBadge() {
3481		int count = unreadCount();
3482		if (unreadCount != count) {
3483			Log.d(Config.LOGTAG, "update unread count to " + count);
3484			if (count > 0) {
3485				ShortcutBadger.applyCount(getApplicationContext(), count);
3486			} else {
3487				ShortcutBadger.removeCount(getApplicationContext());
3488			}
3489			unreadCount = count;
3490		}
3491	}
3492
3493	public void sendReadMarker(final Conversation conversation, String upToUuid) {
3494		final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
3495		final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
3496		if (readMessages.size() > 0) {
3497			updateConversationUi();
3498		}
3499		final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
3500		if (confirmMessages()
3501				&& markable != null
3502				&& (markable.trusted() || isPrivateAndNonAnonymousMuc)
3503				&& markable.getRemoteMsgId() != null) {
3504			Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
3505			Account account = conversation.getAccount();
3506			final Jid to = markable.getCounterpart();
3507			final boolean groupChat = conversation.getMode() == Conversation.MODE_MULTI;
3508			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId(), markable.getCounterpart(), groupChat);
3509			this.sendMessagePacket(conversation.getAccount(), packet);
3510		}
3511	}
3512
3513	public SecureRandom getRNG() {
3514		return this.mRandom;
3515	}
3516
3517	public MemorizingTrustManager getMemorizingTrustManager() {
3518		return this.mMemorizingTrustManager;
3519	}
3520
3521	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
3522		this.mMemorizingTrustManager = trustManager;
3523	}
3524
3525	public void updateMemorizingTrustmanager() {
3526		final MemorizingTrustManager tm;
3527		final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
3528		if (dontTrustSystemCAs) {
3529			tm = new MemorizingTrustManager(getApplicationContext(), null);
3530		} else {
3531			tm = new MemorizingTrustManager(getApplicationContext());
3532		}
3533		setMemorizingTrustManager(tm);
3534	}
3535
3536	public LruCache<String, Bitmap> getBitmapCache() {
3537		return this.mBitmapCache;
3538	}
3539
3540	public Collection<String> getKnownHosts() {
3541		final Set<String> hosts = new HashSet<>();
3542		for (final Account account : getAccounts()) {
3543			hosts.add(account.getServer());
3544			for (final Contact contact : account.getRoster().getContacts()) {
3545				if (contact.showInRoster()) {
3546					final String server = contact.getServer();
3547					if (server != null && !hosts.contains(server)) {
3548						hosts.add(server);
3549					}
3550				}
3551			}
3552		}
3553		if (Config.DOMAIN_LOCK != null) {
3554			hosts.add(Config.DOMAIN_LOCK);
3555		}
3556		if (Config.MAGIC_CREATE_DOMAIN != null) {
3557			hosts.add(Config.MAGIC_CREATE_DOMAIN);
3558		}
3559		return hosts;
3560	}
3561
3562	public Collection<String> getKnownConferenceHosts() {
3563		final Set<String> mucServers = new HashSet<>();
3564		for (final Account account : accounts) {
3565			if (account.getXmppConnection() != null) {
3566				mucServers.addAll(account.getXmppConnection().getMucServers());
3567				for (Bookmark bookmark : account.getBookmarks()) {
3568					final Jid jid = bookmark.getJid();
3569					final String s = jid == null ? null : jid.getDomain();
3570					if (s != null) {
3571						mucServers.add(s);
3572					}
3573				}
3574			}
3575		}
3576		return mucServers;
3577	}
3578
3579	public void sendMessagePacket(Account account, MessagePacket packet) {
3580		XmppConnection connection = account.getXmppConnection();
3581		if (connection != null) {
3582			connection.sendMessagePacket(packet);
3583		}
3584	}
3585
3586	public void sendPresencePacket(Account account, PresencePacket packet) {
3587		XmppConnection connection = account.getXmppConnection();
3588		if (connection != null) {
3589			connection.sendPresencePacket(packet);
3590		}
3591	}
3592
3593	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3594		final XmppConnection connection = account.getXmppConnection();
3595		if (connection != null) {
3596			IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3597			connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
3598		}
3599	}
3600
3601	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3602		final XmppConnection connection = account.getXmppConnection();
3603		if (connection != null) {
3604			connection.sendIqPacket(packet, callback);
3605		} else if (callback != null) {
3606		    callback.onIqPacketReceived(account,new IqPacket(IqPacket.TYPE.TIMEOUT));
3607        }
3608	}
3609
3610	public void sendPresence(final Account account) {
3611		sendPresence(account, checkListeners() && broadcastLastActivity());
3612	}
3613
3614	private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3615		Presence.Status status;
3616		if (manuallyChangePresence()) {
3617			status = account.getPresenceStatus();
3618		} else {
3619			status = getTargetPresence();
3620		}
3621		PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
3622		String message = account.getPresenceStatusMessage();
3623		if (message != null && !message.isEmpty()) {
3624			packet.addChild(new Element("status").setContent(message));
3625		}
3626		if (mLastActivity > 0 && includeIdleTimestamp) {
3627			long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3628			packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
3629		}
3630		sendPresencePacket(account, packet);
3631	}
3632
3633	private void deactivateGracePeriod() {
3634		for (Account account : getAccounts()) {
3635			account.deactivateGracePeriod();
3636		}
3637	}
3638
3639	public void refreshAllPresences() {
3640		boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3641		for (Account account : getAccounts()) {
3642			if (account.isEnabled()) {
3643				sendPresence(account, includeIdleTimestamp);
3644			}
3645		}
3646	}
3647
3648	private void refreshAllFcmTokens() {
3649		for (Account account : getAccounts()) {
3650			if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3651				mPushManagementService.registerPushTokenOnServer(account);
3652			}
3653		}
3654	}
3655
3656	private void sendOfflinePresence(final Account account) {
3657		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
3658		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3659	}
3660
3661	public MessageGenerator getMessageGenerator() {
3662		return this.mMessageGenerator;
3663	}
3664
3665	public PresenceGenerator getPresenceGenerator() {
3666		return this.mPresenceGenerator;
3667	}
3668
3669	public IqGenerator getIqGenerator() {
3670		return this.mIqGenerator;
3671	}
3672
3673	public IqParser getIqParser() {
3674		return this.mIqParser;
3675	}
3676
3677	public JingleConnectionManager getJingleConnectionManager() {
3678		return this.mJingleConnectionManager;
3679	}
3680
3681	public MessageArchiveService getMessageArchiveService() {
3682		return this.mMessageArchiveService;
3683	}
3684
3685	public QuickConversationsService getQuickConversationsService() {
3686        return this.mQuickConversationsService;
3687    }
3688
3689	public List<Contact> findContacts(Jid jid, String accountJid) {
3690		ArrayList<Contact> contacts = new ArrayList<>();
3691		for (Account account : getAccounts()) {
3692			if ((account.isEnabled() || accountJid != null)
3693					&& (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
3694				Contact contact = account.getRoster().getContactFromRoster(jid);
3695				if (contact != null) {
3696					contacts.add(contact);
3697				}
3698			}
3699		}
3700		return contacts;
3701	}
3702
3703	public Conversation findFirstMuc(Jid jid) {
3704		for (Conversation conversation : getConversations()) {
3705			if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
3706				return conversation;
3707			}
3708		}
3709		return null;
3710	}
3711
3712	public NotificationService getNotificationService() {
3713		return this.mNotificationService;
3714	}
3715
3716	public HttpConnectionManager getHttpConnectionManager() {
3717		return this.mHttpConnectionManager;
3718	}
3719
3720	public void resendFailedMessages(final Message message) {
3721		final Collection<Message> messages = new ArrayList<>();
3722		Message current = message;
3723		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3724			messages.add(current);
3725			if (current.mergeable(current.next())) {
3726				current = current.next();
3727			} else {
3728				break;
3729			}
3730		}
3731		for (final Message msg : messages) {
3732			msg.setTime(System.currentTimeMillis());
3733			markMessage(msg, Message.STATUS_WAITING);
3734			this.resendMessage(msg, false);
3735		}
3736		if (message.getConversation() instanceof Conversation) {
3737			((Conversation) message.getConversation()).sort();
3738		}
3739		updateConversationUi();
3740	}
3741
3742	public void clearConversationHistory(final Conversation conversation) {
3743		final long clearDate;
3744		final String reference;
3745		if (conversation.countMessages() > 0) {
3746			Message latestMessage = conversation.getLatestMessage();
3747			clearDate = latestMessage.getTimeSent() + 1000;
3748			reference = latestMessage.getServerMsgId();
3749		} else {
3750			clearDate = System.currentTimeMillis();
3751			reference = null;
3752		}
3753		conversation.clearMessages();
3754		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3755		conversation.setLastClearHistory(clearDate, reference);
3756		Runnable runnable = () -> {
3757			databaseBackend.deleteMessagesInConversation(conversation);
3758			databaseBackend.updateConversation(conversation);
3759		};
3760		mDatabaseWriterExecutor.execute(runnable);
3761	}
3762
3763	public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
3764		if (blockable != null && blockable.getBlockedJid() != null) {
3765			final Jid jid = blockable.getBlockedJid();
3766			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), new OnIqPacketReceived() {
3767
3768				@Override
3769				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3770					if (packet.getType() == IqPacket.TYPE.RESULT) {
3771						account.getBlocklist().add(jid);
3772						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3773					}
3774				}
3775			});
3776			if (removeBlockedConversations(blockable.getAccount(), jid)) {
3777				updateConversationUi();
3778				return true;
3779			} else {
3780				return false;
3781			}
3782		} else {
3783			return false;
3784		}
3785	}
3786
3787	public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
3788		boolean removed = false;
3789		synchronized (this.conversations) {
3790			boolean domainJid = blockedJid.getLocal() == null;
3791			for (Conversation conversation : this.conversations) {
3792				boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
3793						|| blockedJid.equals(conversation.getJid().asBareJid());
3794				if (conversation.getAccount() == account
3795						&& conversation.getMode() == Conversation.MODE_SINGLE
3796						&& jidMatches) {
3797					this.conversations.remove(conversation);
3798					markRead(conversation);
3799					conversation.setStatus(Conversation.STATUS_ARCHIVED);
3800					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
3801					updateConversation(conversation);
3802					removed = true;
3803				}
3804			}
3805		}
3806		return removed;
3807	}
3808
3809	public void sendUnblockRequest(final Blockable blockable) {
3810		if (blockable != null && blockable.getJid() != null) {
3811			final Jid jid = blockable.getBlockedJid();
3812			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3813				@Override
3814				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3815					if (packet.getType() == IqPacket.TYPE.RESULT) {
3816						account.getBlocklist().remove(jid);
3817						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3818					}
3819				}
3820			});
3821		}
3822	}
3823
3824	public void publishDisplayName(Account account) {
3825		String displayName = account.getDisplayName();
3826		if (displayName != null && !displayName.isEmpty()) {
3827			IqPacket publish = mIqGenerator.publishNick(displayName);
3828			sendIqPacket(account, publish, (account1, packet) -> {
3829				if (packet.getType() == IqPacket.TYPE.ERROR) {
3830					Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": could not publish nick");
3831				}
3832			});
3833		}
3834	}
3835
3836	public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
3837		ServiceDiscoveryResult result = discoCache.get(key);
3838		if (result != null) {
3839			return result;
3840		} else {
3841			result = databaseBackend.findDiscoveryResult(key.first, key.second);
3842			if (result != null) {
3843				discoCache.put(key, result);
3844			}
3845			return result;
3846		}
3847	}
3848
3849	public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3850		final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
3851		ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3852		if (disco != null) {
3853			presence.setServiceDiscoveryResult(disco);
3854		} else {
3855			if (!account.inProgressDiscoFetches.contains(key)) {
3856				account.inProgressDiscoFetches.add(key);
3857				IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3858				request.setTo(jid);
3859				final String node = presence.getNode();
3860				final String ver = presence.getVer();
3861				final Element query = request.query("http://jabber.org/protocol/disco#info");
3862				if (node != null && ver != null) {
3863					query.setAttribute("node",node+"#"+ver);
3864				}
3865				Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
3866				sendIqPacket(account, request, (a, response) -> {
3867					if (response.getType() == IqPacket.TYPE.RESULT) {
3868						ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
3869						if (presence.getVer().equals(discoveryResult.getVer())) {
3870							databaseBackend.insertDiscoveryResult(discoveryResult);
3871							injectServiceDiscoveryResult(a.getRoster(), presence.getHash(), presence.getVer(), discoveryResult);
3872						} else {
3873							Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
3874						}
3875					}
3876					a.inProgressDiscoFetches.remove(key);
3877				});
3878			}
3879		}
3880	}
3881
3882	private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3883		for (Contact contact : roster.getContacts()) {
3884			for (Presence presence : contact.getPresences().getPresences().values()) {
3885				if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3886					presence.setServiceDiscoveryResult(disco);
3887				}
3888			}
3889		}
3890	}
3891
3892	public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3893		final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
3894		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3895		request.addChild("prefs", version.namespace);
3896		sendIqPacket(account, request, (account1, packet) -> {
3897			Element prefs = packet.findChild("prefs", version.namespace);
3898			if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3899				callback.onPreferencesFetched(prefs);
3900			} else {
3901				callback.onPreferencesFetchFailed();
3902			}
3903		});
3904	}
3905
3906	public PushManagementService getPushManagementService() {
3907		return mPushManagementService;
3908	}
3909
3910	public void changeStatus(Account account, PresenceTemplate template, String signature) {
3911		if (!template.getStatusMessage().isEmpty()) {
3912			databaseBackend.insertPresenceTemplate(template);
3913		}
3914		account.setPgpSignature(signature);
3915		account.setPresenceStatus(template.getStatus());
3916		account.setPresenceStatusMessage(template.getStatusMessage());
3917		databaseBackend.updateAccount(account);
3918		sendPresence(account);
3919	}
3920
3921	public List<PresenceTemplate> getPresenceTemplates(Account account) {
3922		List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3923		for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3924			if (!templates.contains(template)) {
3925				templates.add(0, template);
3926			}
3927		}
3928		return templates;
3929	}
3930
3931	public void saveConversationAsBookmark(Conversation conversation, String name) {
3932		Account account = conversation.getAccount();
3933		Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
3934		if (!conversation.getJid().isBareJid()) {
3935			bookmark.setNick(conversation.getJid().getResource());
3936		}
3937		if (!TextUtils.isEmpty(name)) {
3938			bookmark.setBookmarkName(name);
3939		}
3940		bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
3941		account.getBookmarks().add(bookmark);
3942		pushBookmarks(account);
3943		bookmark.setConversation(conversation);
3944	}
3945
3946	public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
3947		boolean performedVerification = false;
3948		final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
3949		for (XmppUri.Fingerprint fp : fingerprints) {
3950			if (fp.type == XmppUri.FingerprintType.OMEMO) {
3951				String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
3952				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3953				if (fingerprintStatus != null) {
3954					if (!fingerprintStatus.isVerified()) {
3955						performedVerification = true;
3956						axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
3957					}
3958				} else {
3959					axolotlService.preVerifyFingerprint(contact, fingerprint);
3960				}
3961			}
3962		}
3963		return performedVerification;
3964	}
3965
3966	public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
3967		final AxolotlService axolotlService = account.getAxolotlService();
3968		boolean verifiedSomething = false;
3969		for (XmppUri.Fingerprint fp : fingerprints) {
3970			if (fp.type == XmppUri.FingerprintType.OMEMO) {
3971				String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
3972				Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
3973				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3974				if (fingerprintStatus != null) {
3975					if (!fingerprintStatus.isVerified()) {
3976						axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
3977						verifiedSomething = true;
3978					}
3979				} else {
3980					axolotlService.preVerifyFingerprint(account, fingerprint);
3981					verifiedSomething = true;
3982				}
3983			}
3984		}
3985		return verifiedSomething;
3986	}
3987
3988	public boolean blindTrustBeforeVerification() {
3989		return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
3990	}
3991
3992	public ShortcutService getShortcutService() {
3993		return mShortcutService;
3994	}
3995
3996	public void pushMamPreferences(Account account, Element prefs) {
3997		IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3998		set.addChild(prefs);
3999		sendIqPacket(account, set, null);
4000	}
4001
4002	public interface OnMamPreferencesFetched {
4003		void onPreferencesFetched(Element prefs);
4004
4005		void onPreferencesFetchFailed();
4006	}
4007
4008	public interface OnAccountCreated {
4009		void onAccountCreated(Account account);
4010
4011		void informUser(int r);
4012	}
4013
4014	public interface OnMoreMessagesLoaded {
4015		void onMoreMessagesLoaded(int count, Conversation conversation);
4016
4017		void informUser(int r);
4018	}
4019
4020	public interface OnAccountPasswordChanged {
4021		void onPasswordChangeSucceeded();
4022
4023		void onPasswordChangeFailed();
4024	}
4025
4026	public interface OnAffiliationChanged {
4027		void onAffiliationChangedSuccessful(Jid jid);
4028
4029		void onAffiliationChangeFailed(Jid jid, int resId);
4030	}
4031
4032	public interface OnRoleChanged {
4033		void onRoleChangedSuccessful(String nick);
4034
4035		void onRoleChangeFailed(String nick, int resid);
4036	}
4037
4038	public interface OnConversationUpdate {
4039		void onConversationUpdate();
4040	}
4041
4042	public interface OnAccountUpdate {
4043		void onAccountUpdate();
4044	}
4045
4046	public interface OnCaptchaRequested {
4047		void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
4048	}
4049
4050	public interface OnRosterUpdate {
4051		void onRosterUpdate();
4052	}
4053
4054	public interface OnMucRosterUpdate {
4055		void onMucRosterUpdate();
4056	}
4057
4058	public interface OnConferenceConfigurationFetched {
4059		void onConferenceConfigurationFetched(Conversation conversation);
4060
4061		void onFetchFailed(Conversation conversation, Element error);
4062	}
4063
4064	public interface OnConferenceJoined {
4065		void onConferenceJoined(Conversation conversation);
4066	}
4067
4068	public interface OnConfigurationPushed {
4069		void onPushSucceeded();
4070
4071		void onPushFailed();
4072	}
4073
4074	public interface OnShowErrorToast {
4075		void onShowErrorToast(int resId);
4076	}
4077
4078	public class XmppConnectionBinder extends Binder {
4079		public XmppConnectionService getService() {
4080			return XmppConnectionService.this;
4081		}
4082	}
4083
4084	private class InternalEventReceiver extends BroadcastReceiver {
4085
4086        @Override
4087        public void onReceive(Context context, Intent intent) {
4088            onStartCommand(intent,0,0);
4089        }
4090    }
4091}