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