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		for (Account account : this.accounts) {
2542			if (account.isEnabled()) {
2543				return true;
2544			}
2545		}
2546		return false;
2547	}
2548
2549
2550	public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
2551        getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
2552    }
2553
2554    public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2555        getAttachments(account.getUuid(),jid.asBareJid(),limit, onMediaLoaded);
2556    }
2557
2558
2559	public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2560        new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
2561    }
2562
2563	public void persistSelfNick(MucOptions.User self) {
2564		final Conversation conversation = self.getConversation();
2565		final boolean tookProposedNickFromBookmark = conversation.getMucOptions().isTookProposedNickFromBookmark();
2566		Jid full = self.getFullJid();
2567		if (!full.equals(conversation.getJid())) {
2568			Log.d(Config.LOGTAG, "nick changed. updating");
2569			conversation.setContactJid(full);
2570			databaseBackend.updateConversation(conversation);
2571		}
2572
2573		final Bookmark bookmark = conversation.getBookmark();
2574		final String bookmarkedNick = bookmark == null ? null : bookmark.getNick();
2575        if (bookmark != null && (tookProposedNickFromBookmark || TextUtils.isEmpty(bookmarkedNick)) && !full.getResource().equals(bookmarkedNick)) {
2576            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": persist nick '" + full.getResource() + "' into bookmark for " + conversation.getJid().asBareJid());
2577            bookmark.setNick(full.getResource());
2578            pushBookmarks(bookmark.getAccount());
2579        }
2580	}
2581
2582	public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2583		final MucOptions options = conversation.getMucOptions();
2584		final Jid joinJid = options.createJoinJid(nick);
2585		if (joinJid == null) {
2586			return false;
2587		}
2588		if (options.online()) {
2589			Account account = conversation.getAccount();
2590			options.setOnRenameListener(new OnRenameListener() {
2591
2592				@Override
2593				public void onSuccess() {
2594					callback.success(conversation);
2595				}
2596
2597				@Override
2598				public void onFailure() {
2599					callback.error(R.string.nick_in_use, conversation);
2600				}
2601			});
2602
2603			PresencePacket packet = new PresencePacket();
2604			packet.setTo(joinJid);
2605			packet.setFrom(conversation.getAccount().getJid());
2606
2607			String sig = account.getPgpSignature();
2608			if (sig != null) {
2609				packet.addChild("status").setContent("online");
2610				packet.addChild("x", "jabber:x:signed").setContent(sig);
2611			}
2612			sendPresencePacket(account, packet);
2613		} else {
2614			conversation.setContactJid(joinJid);
2615			databaseBackend.updateConversation(conversation);
2616			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2617				Bookmark bookmark = conversation.getBookmark();
2618				if (bookmark != null) {
2619					bookmark.setNick(nick);
2620					pushBookmarks(bookmark.getAccount());
2621				}
2622				joinMuc(conversation);
2623			}
2624		}
2625		return true;
2626	}
2627
2628	public void leaveMuc(Conversation conversation) {
2629		leaveMuc(conversation, false);
2630	}
2631
2632	private void leaveMuc(Conversation conversation, boolean now) {
2633		Account account = conversation.getAccount();
2634		account.pendingConferenceJoins.remove(conversation);
2635		account.pendingConferenceLeaves.remove(conversation);
2636		if (account.getStatus() == Account.State.ONLINE || now) {
2637			sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
2638			conversation.getMucOptions().setOffline();
2639			Bookmark bookmark = conversation.getBookmark();
2640			if (bookmark != null) {
2641				bookmark.setConversation(null);
2642			}
2643			Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
2644		} else {
2645			account.pendingConferenceLeaves.add(conversation);
2646		}
2647	}
2648
2649	public String findConferenceServer(final Account account) {
2650		String server;
2651		if (account.getXmppConnection() != null) {
2652			server = account.getXmppConnection().getMucServer();
2653			if (server != null) {
2654				return server;
2655			}
2656		}
2657		for (Account other : getAccounts()) {
2658			if (other != account && other.getXmppConnection() != null) {
2659				server = other.getXmppConnection().getMucServer();
2660				if (server != null) {
2661					return server;
2662				}
2663			}
2664		}
2665		return null;
2666	}
2667
2668	public boolean createAdhocConference(final Account account,
2669	                                     final String name,
2670	                                     final Iterable<Jid> jids,
2671	                                     final UiCallback<Conversation> callback) {
2672		Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2673		if (account.getStatus() == Account.State.ONLINE) {
2674			try {
2675				String server = findConferenceServer(account);
2676				if (server == null) {
2677					if (callback != null) {
2678						callback.error(R.string.no_conference_server_found, null);
2679					}
2680					return false;
2681				}
2682				final Jid jid = Jid.of(CryptoHelper.pronounceable(getRNG()), server, null);
2683				final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
2684				joinMuc(conversation, new OnConferenceJoined() {
2685					@Override
2686					public void onConferenceJoined(final Conversation conversation) {
2687						final Bundle configuration = IqGenerator.defaultRoomConfiguration();
2688						if (!TextUtils.isEmpty(name)) {
2689							configuration.putString("muc#roomconfig_roomname", name);
2690						}
2691						pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
2692							@Override
2693							public void onPushSucceeded() {
2694								for (Jid invite : jids) {
2695									invite(conversation, invite);
2696								}
2697								if (account.countPresences() > 1) {
2698									directInvite(conversation, account.getJid().asBareJid());
2699								}
2700								saveConversationAsBookmark(conversation, name);
2701								if (callback != null) {
2702									callback.success(conversation);
2703								}
2704							}
2705
2706							@Override
2707							public void onPushFailed() {
2708								archiveConversation(conversation);
2709								if (callback != null) {
2710									callback.error(R.string.conference_creation_failed, conversation);
2711								}
2712							}
2713						});
2714					}
2715				});
2716				return true;
2717			} catch (IllegalArgumentException e) {
2718				if (callback != null) {
2719					callback.error(R.string.conference_creation_failed, null);
2720				}
2721				return false;
2722			}
2723		} else {
2724			if (callback != null) {
2725				callback.error(R.string.not_connected_try_again, null);
2726			}
2727			return false;
2728		}
2729	}
2730
2731	public void fetchConferenceConfiguration(final Conversation conversation) {
2732		fetchConferenceConfiguration(conversation, null);
2733	}
2734
2735	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2736		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2737		request.setTo(conversation.getJid().asBareJid());
2738		request.query("http://jabber.org/protocol/disco#info");
2739		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2740			@Override
2741			public void onIqPacketReceived(Account account, IqPacket packet) {
2742				if (packet.getType() == IqPacket.TYPE.RESULT) {
2743
2744					final MucOptions mucOptions = conversation.getMucOptions();
2745					final Bookmark bookmark = conversation.getBookmark();
2746					final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
2747
2748					if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
2749						Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
2750						updateConversation(conversation);
2751					}
2752
2753					if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
2754						if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
2755							pushBookmarks(account);
2756						}
2757					}
2758
2759
2760					if (callback != null) {
2761						callback.onConferenceConfigurationFetched(conversation);
2762					}
2763
2764
2765
2766					updateConversationUi();
2767				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
2768					if (callback != null) {
2769						callback.onFetchFailed(conversation, packet.getError());
2770					}
2771				}
2772			}
2773		});
2774	}
2775
2776	public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
2777		pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
2778	}
2779
2780	public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
2781        Log.d(Config.LOGTAG,"pushing node configuration");
2782		sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
2783			@Override
2784			public void onIqPacketReceived(Account account, IqPacket packet) {
2785				if (packet.getType() == IqPacket.TYPE.RESULT) {
2786					Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
2787					Element configuration = pubsub == null ? null : pubsub.findChild("configure");
2788					Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
2789					if (x != null) {
2790						Data data = Data.parse(x);
2791						data.submit(options);
2792						sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
2793							@Override
2794							public void onIqPacketReceived(Account account, IqPacket packet) {
2795								if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
2796									Log.d(Config.LOGTAG,account.getJid().asBareJid()+": successfully changed node configuration for node "+node);
2797									callback.onPushSucceeded();
2798								} else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
2799									callback.onPushFailed();
2800								}
2801							}
2802						});
2803					} else if (callback != null) {
2804						callback.onPushFailed();
2805					}
2806				} else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
2807					callback.onPushFailed();
2808				}
2809			}
2810		});
2811	}
2812
2813	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
2814		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2815		request.setTo(conversation.getJid().asBareJid());
2816		request.query("http://jabber.org/protocol/muc#owner");
2817		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2818			@Override
2819			public void onIqPacketReceived(Account account, IqPacket packet) {
2820				if (packet.getType() == IqPacket.TYPE.RESULT) {
2821					Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
2822					data.submit(options);
2823					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2824					set.setTo(conversation.getJid().asBareJid());
2825					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2826					sendIqPacket(account, set, new OnIqPacketReceived() {
2827						@Override
2828						public void onIqPacketReceived(Account account, IqPacket packet) {
2829							if (callback != null) {
2830								if (packet.getType() == IqPacket.TYPE.RESULT) {
2831									callback.onPushSucceeded();
2832								} else {
2833									callback.onPushFailed();
2834								}
2835							}
2836						}
2837					});
2838				} else {
2839					if (callback != null) {
2840						callback.onPushFailed();
2841					}
2842				}
2843			}
2844		});
2845	}
2846
2847	public void pushSubjectToConference(final Conversation conference, final String subject) {
2848		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
2849		this.sendMessagePacket(conference.getAccount(), packet);
2850	}
2851
2852	public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2853		final Jid jid = user.asBareJid();
2854		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2855		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2856			@Override
2857			public void onIqPacketReceived(Account account, IqPacket packet) {
2858				if (packet.getType() == IqPacket.TYPE.RESULT) {
2859					conference.getMucOptions().changeAffiliation(jid, affiliation);
2860					getAvatarService().clear(conference);
2861					callback.onAffiliationChangedSuccessful(jid);
2862				} else {
2863					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2864				}
2865			}
2866		});
2867	}
2868
2869	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2870		List<Jid> jids = new ArrayList<>();
2871		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2872			if (user.getAffiliation() == before && user.getRealJid() != null) {
2873				jids.add(user.getRealJid());
2874			}
2875		}
2876		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2877		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2878	}
2879
2880	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2881		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2882		Log.d(Config.LOGTAG, request.toString());
2883		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2884			@Override
2885			public void onIqPacketReceived(Account account, IqPacket packet) {
2886				Log.d(Config.LOGTAG, packet.toString());
2887				if (packet.getType() == IqPacket.TYPE.RESULT) {
2888					callback.onRoleChangedSuccessful(nick);
2889				} else {
2890					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2891				}
2892			}
2893		});
2894	}
2895
2896    public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
2897        IqPacket request = new IqPacket(IqPacket.TYPE.SET);
2898        request.setTo(conversation.getJid().asBareJid());
2899        request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
2900        sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2901            @Override
2902            public void onIqPacketReceived(Account account, IqPacket packet) {
2903                if (packet.getType() == IqPacket.TYPE.RESULT) {
2904                    if (callback != null) {
2905                        callback.onRoomDestroySucceeded();
2906                    }
2907                } else if (packet.getType() == IqPacket.TYPE.ERROR) {
2908                    if (callback != null) {
2909                        callback.onRoomDestroyFailed();
2910                    }
2911                }
2912            }
2913        });
2914    }
2915
2916	private void disconnect(Account account, boolean force) {
2917		if ((account.getStatus() == Account.State.ONLINE)
2918				|| (account.getStatus() == Account.State.DISABLED)) {
2919			final XmppConnection connection = account.getXmppConnection();
2920			if (!force) {
2921				List<Conversation> conversations = getConversations();
2922				for (Conversation conversation : conversations) {
2923					if (conversation.getAccount() == account) {
2924						if (conversation.getMode() == Conversation.MODE_MULTI) {
2925							leaveMuc(conversation, true);
2926						}
2927					}
2928				}
2929				sendOfflinePresence(account);
2930			}
2931			connection.disconnect(force);
2932		}
2933	}
2934
2935	@Override
2936	public IBinder onBind(Intent intent) {
2937		return mBinder;
2938	}
2939
2940	public void updateMessage(Message message) {
2941		updateMessage(message, true);
2942	}
2943
2944	public void updateMessage(Message message, boolean includeBody) {
2945		databaseBackend.updateMessage(message, includeBody);
2946		updateConversationUi();
2947	}
2948
2949	public void updateMessage(Message message, String uuid) {
2950		if (!databaseBackend.updateMessage(message, uuid)) {
2951            Log.e(Config.LOGTAG,"error updated message in DB after edit");
2952        }
2953		updateConversationUi();
2954	}
2955
2956	protected void syncDirtyContacts(Account account) {
2957		for (Contact contact : account.getRoster().getContacts()) {
2958			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2959				pushContactToServer(contact);
2960			}
2961			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2962				deleteContactOnServer(contact);
2963			}
2964		}
2965	}
2966
2967	public void createContact(Contact contact, boolean autoGrant) {
2968		if (autoGrant) {
2969			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2970			contact.setOption(Contact.Options.ASKING);
2971		}
2972		pushContactToServer(contact);
2973	}
2974
2975	public void pushContactToServer(final Contact contact) {
2976		contact.resetOption(Contact.Options.DIRTY_DELETE);
2977		contact.setOption(Contact.Options.DIRTY_PUSH);
2978		final Account account = contact.getAccount();
2979		if (account.getStatus() == Account.State.ONLINE) {
2980			final boolean ask = contact.getOption(Contact.Options.ASKING);
2981			final boolean sendUpdates = contact
2982					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2983					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2984			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2985			iq.query(Namespace.ROSTER).addChild(contact.asElement());
2986			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2987			if (sendUpdates) {
2988				sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
2989			}
2990			if (ask) {
2991				sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2992			}
2993		} else {
2994			syncRoster(contact.getAccount());
2995		}
2996	}
2997
2998	public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
2999		new Thread(() -> {
3000			final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3001			final int size = Config.AVATAR_SIZE;
3002			final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3003			if (avatar != null) {
3004				if (!getFileBackend().save(avatar)) {
3005					callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3006					return;
3007				}
3008				avatar.owner = conversation.getJid().asBareJid();
3009				publishMucAvatar(conversation, avatar, callback);
3010			} else {
3011				callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3012			}
3013		}).start();
3014	}
3015
3016	public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
3017		new Thread(() -> {
3018			final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3019			final int size = Config.AVATAR_SIZE;
3020			final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3021			if (avatar != null) {
3022				if (!getFileBackend().save(avatar)) {
3023					Log.d(Config.LOGTAG,"unable to save vcard");
3024					callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3025					return;
3026				}
3027				publishAvatar(account, avatar, callback);
3028			} else {
3029				callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3030			}
3031		}).start();
3032
3033	}
3034
3035	private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
3036		final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
3037		sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
3038			boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
3039			if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
3040				Element vcard = response.findChild("vCard", "vcard-temp");
3041				if (vcard == null) {
3042					vcard = new Element("vCard", "vcard-temp");
3043				}
3044				Element photo = vcard.findChild("PHOTO");
3045				if (photo == null) {
3046					photo = vcard.addChild("PHOTO");
3047				}
3048				photo.clearChildren();
3049				photo.addChild("TYPE").setContent(avatar.type);
3050				photo.addChild("BINVAL").setContent(avatar.image);
3051				IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3052				publication.setTo(conversation.getJid().asBareJid());
3053				publication.addChild(vcard);
3054				sendIqPacket(account, publication, (a1, publicationResponse) -> {
3055					if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3056						callback.onAvatarPublicationSucceeded();
3057					} else {
3058						Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getError());
3059						callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3060					}
3061				});
3062			} else {
3063				Log.d(Config.LOGTAG, "failed to request vcard " + response.toString());
3064				callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
3065			}
3066		});
3067	}
3068
3069    public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
3070        final Bundle options;
3071        if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
3072            options = PublishOptions.openAccess();
3073        } else {
3074            options = null;
3075        }
3076        publishAvatar(account, avatar, options, true, callback);
3077    }
3078
3079	public void publishAvatar(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3080        Log.d(Config.LOGTAG,account.getJid().asBareJid()+": publishing avatar. options="+options);
3081		IqPacket packet = this.mIqGenerator.publishAvatar(avatar, options);
3082		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3083
3084			@Override
3085			public void onIqPacketReceived(Account account, IqPacket result) {
3086				if (result.getType() == IqPacket.TYPE.RESULT) {
3087                    publishAvatarMetadata(account, avatar, options,true, callback);
3088                } else if (retry && PublishOptions.preconditionNotMet(result)) {
3089				    pushNodeConfiguration(account, "urn:xmpp:avatar:data", options, new OnConfigurationPushed() {
3090                        @Override
3091                        public void onPushSucceeded() {
3092                            Log.d(Config.LOGTAG,account.getJid().asBareJid()+": changed node configuration for avatar node");
3093                            publishAvatar(account, avatar, options, false, callback);
3094                        }
3095
3096                        @Override
3097                        public void onPushFailed() {
3098                            Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to change node configuration for avatar node");
3099                            publishAvatar(account, avatar, null, false, callback);
3100                        }
3101                    });
3102				} else {
3103					Element error = result.findChild("error");
3104					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
3105					if (callback != null) {
3106						callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3107					}
3108				}
3109			}
3110		});
3111	}
3112
3113	public void publishAvatarMetadata(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3114        final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
3115        sendIqPacket(account, packet, new OnIqPacketReceived() {
3116            @Override
3117            public void onIqPacketReceived(Account account, IqPacket result) {
3118                if (result.getType() == IqPacket.TYPE.RESULT) {
3119                    if (account.setAvatar(avatar.getFilename())) {
3120                        getAvatarService().clear(account);
3121                        databaseBackend.updateAccount(account);
3122                    }
3123                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
3124                    if (callback != null) {
3125                        callback.onAvatarPublicationSucceeded();
3126                    }
3127                } else if (retry && PublishOptions.preconditionNotMet(result)) {
3128                    pushNodeConfiguration(account, "urn:xmpp:avatar:metadata", options, new OnConfigurationPushed() {
3129                        @Override
3130                        public void onPushSucceeded() {
3131                            Log.d(Config.LOGTAG,account.getJid().asBareJid()+": changed node configuration for avatar meta data node");
3132                            publishAvatarMetadata(account, avatar, options,false, callback);
3133                        }
3134
3135                        @Override
3136                        public void onPushFailed() {
3137                            Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to change node configuration for avatar meta data node");
3138                            publishAvatarMetadata(account, avatar,  null,false, callback);
3139                        }
3140                    });
3141                } else {
3142                    if (callback != null) {
3143                        callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3144                    }
3145                }
3146            }
3147        });
3148    }
3149
3150	public void republishAvatarIfNeeded(Account account) {
3151		if (account.getAxolotlService().isPepBroken()) {
3152			Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
3153			return;
3154		}
3155		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3156		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3157
3158			private Avatar parseAvatar(IqPacket packet) {
3159				Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3160				if (pubsub != null) {
3161					Element items = pubsub.findChild("items");
3162					if (items != null) {
3163						return Avatar.parseMetadata(items);
3164					}
3165				}
3166				return null;
3167			}
3168
3169			private boolean errorIsItemNotFound(IqPacket packet) {
3170				Element error = packet.findChild("error");
3171				return packet.getType() == IqPacket.TYPE.ERROR
3172						&& error != null
3173						&& error.hasChild("item-not-found");
3174			}
3175
3176			@Override
3177			public void onIqPacketReceived(Account account, IqPacket packet) {
3178				if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
3179					Avatar serverAvatar = parseAvatar(packet);
3180					if (serverAvatar == null && account.getAvatar() != null) {
3181						Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
3182						if (avatar != null) {
3183							Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
3184							publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
3185						} else {
3186							Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
3187						}
3188					}
3189				}
3190			}
3191		});
3192	}
3193
3194	public void fetchAvatar(Account account, Avatar avatar) {
3195		fetchAvatar(account, avatar, null);
3196	}
3197
3198	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3199		final String KEY = generateFetchKey(account, avatar);
3200		synchronized (this.mInProgressAvatarFetches) {
3201			if (!this.mInProgressAvatarFetches.contains(KEY)) {
3202				switch (avatar.origin) {
3203					case PEP:
3204						this.mInProgressAvatarFetches.add(KEY);
3205						fetchAvatarPep(account, avatar, callback);
3206						break;
3207					case VCARD:
3208						this.mInProgressAvatarFetches.add(KEY);
3209						fetchAvatarVcard(account, avatar, callback);
3210						break;
3211				}
3212			}
3213		}
3214	}
3215
3216	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3217		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
3218		sendIqPacket(account, packet, (a, result) -> {
3219			synchronized (mInProgressAvatarFetches) {
3220				mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
3221			}
3222			final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
3223			if (result.getType() == IqPacket.TYPE.RESULT) {
3224				avatar.image = mIqParser.avatarData(result);
3225				if (avatar.image != null) {
3226					if (getFileBackend().save(avatar)) {
3227						if (a.getJid().asBareJid().equals(avatar.owner)) {
3228							if (a.setAvatar(avatar.getFilename())) {
3229								databaseBackend.updateAccount(a);
3230							}
3231							getAvatarService().clear(a);
3232							updateConversationUi();
3233							updateAccountUi();
3234						} else {
3235							Contact contact = a.getRoster().getContact(avatar.owner);
3236							if (contact.setAvatar(avatar)) {
3237								syncRoster(account);
3238								getAvatarService().clear(contact);
3239								updateConversationUi();
3240								updateRosterUi();
3241							}
3242						}
3243						if (callback != null) {
3244							callback.success(avatar);
3245						}
3246						Log.d(Config.LOGTAG, a.getJid().asBareJid()
3247								+ ": successfully fetched pep avatar for " + avatar.owner);
3248						return;
3249					}
3250				} else {
3251
3252					Log.d(Config.LOGTAG, ERROR + "(parsing error)");
3253				}
3254			} else {
3255				Element error = result.findChild("error");
3256				if (error == null) {
3257					Log.d(Config.LOGTAG, ERROR + "(server error)");
3258				} else {
3259					Log.d(Config.LOGTAG, ERROR + error.toString());
3260				}
3261			}
3262			if (callback != null) {
3263				callback.error(0, null);
3264			}
3265
3266		});
3267	}
3268
3269	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3270		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
3271		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3272			@Override
3273			public void onIqPacketReceived(Account account, IqPacket packet) {
3274				synchronized (mInProgressAvatarFetches) {
3275					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
3276				}
3277				if (packet.getType() == IqPacket.TYPE.RESULT) {
3278					Element vCard = packet.findChild("vCard", "vcard-temp");
3279					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
3280					String image = photo != null ? photo.findChildContent("BINVAL") : null;
3281					if (image != null) {
3282						avatar.image = image;
3283						if (getFileBackend().save(avatar)) {
3284							Log.d(Config.LOGTAG, account.getJid().asBareJid()
3285									+ ": successfully fetched vCard avatar for " + avatar.owner);
3286							if (avatar.owner.isBareJid()) {
3287								if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
3288									Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
3289									account.setAvatar(avatar.getFilename());
3290									databaseBackend.updateAccount(account);
3291									getAvatarService().clear(account);
3292									updateAccountUi();
3293								} else {
3294									Contact contact = account.getRoster().getContact(avatar.owner);
3295									if (contact.setAvatar(avatar)) {
3296										syncRoster(account);
3297										getAvatarService().clear(contact);
3298										updateRosterUi();
3299									}
3300								}
3301								updateConversationUi();
3302							} else {
3303								Conversation conversation = find(account, avatar.owner.asBareJid());
3304								if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
3305									MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
3306									if (user != null) {
3307										if (user.setAvatar(avatar)) {
3308											getAvatarService().clear(user);
3309											updateConversationUi();
3310											updateMucRosterUi();
3311										}
3312										if (user.getRealJid() != null) {
3313										    Contact contact = account.getRoster().getContact(user.getRealJid());
3314										    if (contact.setAvatar(avatar)) {
3315                                                syncRoster(account);
3316                                                getAvatarService().clear(contact);
3317                                                updateRosterUi();
3318                                            }
3319                                        }
3320									}
3321								}
3322							}
3323						}
3324					}
3325				}
3326			}
3327		});
3328	}
3329
3330	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
3331		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3332		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3333
3334			@Override
3335			public void onIqPacketReceived(Account account, IqPacket packet) {
3336				if (packet.getType() == IqPacket.TYPE.RESULT) {
3337					Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3338					if (pubsub != null) {
3339						Element items = pubsub.findChild("items");
3340						if (items != null) {
3341							Avatar avatar = Avatar.parseMetadata(items);
3342							if (avatar != null) {
3343								avatar.owner = account.getJid().asBareJid();
3344								if (fileBackend.isAvatarCached(avatar)) {
3345									if (account.setAvatar(avatar.getFilename())) {
3346										databaseBackend.updateAccount(account);
3347									}
3348									getAvatarService().clear(account);
3349									callback.success(avatar);
3350								} else {
3351									fetchAvatarPep(account, avatar, callback);
3352								}
3353								return;
3354							}
3355						}
3356					}
3357				}
3358				callback.error(0, null);
3359			}
3360		});
3361	}
3362
3363	public void deleteContactOnServer(Contact contact) {
3364		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
3365		contact.resetOption(Contact.Options.DIRTY_PUSH);
3366		contact.setOption(Contact.Options.DIRTY_DELETE);
3367		Account account = contact.getAccount();
3368		if (account.getStatus() == Account.State.ONLINE) {
3369			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3370			Element item = iq.query(Namespace.ROSTER).addChild("item");
3371			item.setAttribute("jid", contact.getJid().toString());
3372			item.setAttribute("subscription", "remove");
3373			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3374		}
3375	}
3376
3377	public void updateConversation(final Conversation conversation) {
3378		mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
3379	}
3380
3381	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
3382		synchronized (account) {
3383			XmppConnection connection = account.getXmppConnection();
3384			if (connection == null) {
3385				connection = createConnection(account);
3386				account.setXmppConnection(connection);
3387			}
3388			boolean hasInternet = hasInternetConnection();
3389			if (account.isEnabled() && hasInternet) {
3390				if (!force) {
3391					disconnect(account, false);
3392				}
3393				Thread thread = new Thread(connection);
3394				connection.setInteractive(interactive);
3395				connection.prepareNewConnection();
3396				connection.interrupt();
3397				thread.start();
3398				scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
3399			} else {
3400				disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
3401				account.getRoster().clearPresences();
3402				connection.resetEverything();
3403				final AxolotlService axolotlService = account.getAxolotlService();
3404				if (axolotlService != null) {
3405					axolotlService.resetBrokenness();
3406				}
3407				if (!hasInternet) {
3408					account.setStatus(Account.State.NO_INTERNET);
3409				}
3410			}
3411		}
3412	}
3413
3414	public void reconnectAccountInBackground(final Account account) {
3415		new Thread(() -> reconnectAccount(account, false, true)).start();
3416	}
3417
3418	public void invite(Conversation conversation, Jid contact) {
3419		Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
3420		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
3421		sendMessagePacket(conversation.getAccount(), packet);
3422	}
3423
3424	public void directInvite(Conversation conversation, Jid jid) {
3425		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
3426		sendMessagePacket(conversation.getAccount(), packet);
3427	}
3428
3429	public void resetSendingToWaiting(Account account) {
3430		for (Conversation conversation : getConversations()) {
3431			if (conversation.getAccount() == account) {
3432				conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
3433			}
3434		}
3435	}
3436
3437	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
3438		return markMessage(account, recipient, uuid, status, null);
3439	}
3440
3441	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
3442		if (uuid == null) {
3443			return null;
3444		}
3445		for (Conversation conversation : getConversations()) {
3446			if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
3447				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
3448				if (message != null) {
3449					markMessage(message, status, errorMessage);
3450				}
3451				return message;
3452			}
3453		}
3454		return null;
3455	}
3456
3457	public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) {
3458		if (uuid == null) {
3459			return false;
3460		} else {
3461			Message message = conversation.findSentMessageWithUuid(uuid);
3462			if (message != null) {
3463				if (message.getServerMsgId() == null) {
3464					message.setServerMsgId(serverMessageId);
3465				}
3466				markMessage(message, status);
3467				return true;
3468			} else {
3469				return false;
3470			}
3471		}
3472	}
3473
3474	public void markMessage(Message message, int status) {
3475		markMessage(message, status, null);
3476	}
3477
3478
3479	public void markMessage(Message message, int status, String errorMessage) {
3480		final int c = message.getStatus();
3481		if (status == Message.STATUS_SEND_FAILED && (c == Message.STATUS_SEND_RECEIVED || c == Message.STATUS_SEND_DISPLAYED)) {
3482			return;
3483		}
3484		if (status == Message.STATUS_SEND_RECEIVED && c == Message.STATUS_SEND_DISPLAYED) {
3485			return;
3486		}
3487		message.setErrorMessage(errorMessage);
3488		message.setStatus(status);
3489		databaseBackend.updateMessage(message, false);
3490		updateConversationUi();
3491	}
3492
3493	private SharedPreferences getPreferences() {
3494		return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
3495	}
3496
3497	public long getAutomaticMessageDeletionDate() {
3498		final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
3499		return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
3500	}
3501
3502	public long getLongPreference(String name, @IntegerRes int res) {
3503		long defaultValue = getResources().getInteger(res);
3504		try {
3505			return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
3506		} catch (NumberFormatException e) {
3507			return defaultValue;
3508		}
3509	}
3510
3511	public boolean getBooleanPreference(String name, @BoolRes int res) {
3512		return getPreferences().getBoolean(name, getResources().getBoolean(res));
3513	}
3514
3515	public boolean confirmMessages() {
3516		return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
3517	}
3518
3519	public boolean allowMessageCorrection() {
3520		return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
3521	}
3522
3523	public boolean sendChatStates() {
3524		return getBooleanPreference("chat_states", R.bool.chat_states);
3525	}
3526
3527	private boolean synchronizeWithBookmarks() {
3528		return getBooleanPreference("autojoin", R.bool.autojoin);
3529	}
3530
3531	public boolean indicateReceived() {
3532		return getBooleanPreference("indicate_received", R.bool.indicate_received);
3533	}
3534
3535	public boolean useTorToConnect() {
3536		return QuickConversationsService.isConversations() && getBooleanPreference("use_tor", R.bool.use_tor);
3537	}
3538
3539	public boolean showExtendedConnectionOptions() {
3540		return QuickConversationsService.isConversations() && getBooleanPreference("show_connection_options", R.bool.show_connection_options);
3541	}
3542
3543	public boolean broadcastLastActivity() {
3544		return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
3545	}
3546
3547	public int unreadCount() {
3548		int count = 0;
3549		for (Conversation conversation : getConversations()) {
3550			count += conversation.unreadCount();
3551		}
3552		return count;
3553	}
3554
3555
3556	private <T> List<T> threadSafeList(Set<T> set) {
3557		synchronized (LISTENER_LOCK) {
3558			return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
3559		}
3560	}
3561
3562	public void showErrorToastInUi(int resId) {
3563		for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
3564			listener.onShowErrorToast(resId);
3565		}
3566	}
3567
3568	public void updateConversationUi() {
3569		for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
3570			listener.onConversationUpdate();
3571		}
3572	}
3573
3574	public void updateAccountUi() {
3575		for (OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
3576			listener.onAccountUpdate();
3577		}
3578	}
3579
3580	public void updateRosterUi() {
3581		for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
3582			listener.onRosterUpdate();
3583		}
3584	}
3585
3586	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3587		if (mOnCaptchaRequested.size() > 0) {
3588			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3589			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3590					(int) (captcha.getHeight() * metrics.scaledDensity), false);
3591			for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
3592				listener.onCaptchaRequested(account, id, data, scaled);
3593			}
3594			return true;
3595		}
3596		return false;
3597	}
3598
3599	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3600		for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
3601			listener.OnUpdateBlocklist(status);
3602		}
3603	}
3604
3605	public void updateMucRosterUi() {
3606		for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
3607			listener.onMucRosterUpdate();
3608		}
3609	}
3610
3611	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3612		for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
3613			listener.onKeyStatusUpdated(report);
3614		}
3615	}
3616
3617	public Account findAccountByJid(final Jid accountJid) {
3618		for (Account account : this.accounts) {
3619			if (account.getJid().asBareJid().equals(accountJid.asBareJid())) {
3620				return account;
3621			}
3622		}
3623		return null;
3624	}
3625
3626	public Account findAccountByUuid(final String uuid) {
3627		for(Account account : this.accounts) {
3628			if (account.getUuid().equals(uuid)) {
3629				return account;
3630			}
3631		}
3632		return null;
3633	}
3634
3635	public Conversation findConversationByUuid(String uuid) {
3636		for (Conversation conversation : getConversations()) {
3637			if (conversation.getUuid().equals(uuid)) {
3638				return conversation;
3639			}
3640		}
3641		return null;
3642	}
3643
3644	public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
3645		List<Conversation> findings = new ArrayList<>();
3646		for (Conversation c : getConversations()) {
3647			if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
3648				findings.add(c);
3649			}
3650		}
3651		return findings.size() == 1 ? findings.get(0) : null;
3652	}
3653
3654	public boolean markRead(final Conversation conversation, boolean dismiss) {
3655		return markRead(conversation, null, dismiss).size() > 0;
3656	}
3657
3658	public void markRead(final Conversation conversation) {
3659		markRead(conversation, null, true);
3660	}
3661
3662	public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
3663		if (dismiss) {
3664			mNotificationService.clear(conversation);
3665		}
3666		final List<Message> readMessages = conversation.markRead(upToUuid);
3667		if (readMessages.size() > 0) {
3668			Runnable runnable = () -> {
3669				for (Message message : readMessages) {
3670					databaseBackend.updateMessage(message, false);
3671				}
3672			};
3673			mDatabaseWriterExecutor.execute(runnable);
3674			updateUnreadCountBadge();
3675			return readMessages;
3676		} else {
3677			return readMessages;
3678		}
3679	}
3680
3681	public synchronized void updateUnreadCountBadge() {
3682		int count = unreadCount();
3683		if (unreadCount != count) {
3684			Log.d(Config.LOGTAG, "update unread count to " + count);
3685			if (count > 0) {
3686				ShortcutBadger.applyCount(getApplicationContext(), count);
3687			} else {
3688				ShortcutBadger.removeCount(getApplicationContext());
3689			}
3690			unreadCount = count;
3691		}
3692	}
3693
3694	public void sendReadMarker(final Conversation conversation, String upToUuid) {
3695		final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
3696		final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
3697		if (readMessages.size() > 0) {
3698			updateConversationUi();
3699		}
3700		final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
3701		if (confirmMessages()
3702				&& markable != null
3703				&& (markable.trusted() || isPrivateAndNonAnonymousMuc)
3704				&& markable.getRemoteMsgId() != null) {
3705			Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
3706			Account account = conversation.getAccount();
3707			final Jid to = markable.getCounterpart();
3708			final boolean groupChat = conversation.getMode() == Conversation.MODE_MULTI;
3709			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId(), markable.getCounterpart(), groupChat);
3710			this.sendMessagePacket(conversation.getAccount(), packet);
3711		}
3712	}
3713
3714	public SecureRandom getRNG() {
3715		return this.mRandom;
3716	}
3717
3718	public MemorizingTrustManager getMemorizingTrustManager() {
3719		return this.mMemorizingTrustManager;
3720	}
3721
3722	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
3723		this.mMemorizingTrustManager = trustManager;
3724	}
3725
3726	public void updateMemorizingTrustmanager() {
3727		final MemorizingTrustManager tm;
3728		final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
3729		if (dontTrustSystemCAs) {
3730			tm = new MemorizingTrustManager(getApplicationContext(), null);
3731		} else {
3732			tm = new MemorizingTrustManager(getApplicationContext());
3733		}
3734		setMemorizingTrustManager(tm);
3735	}
3736
3737	public LruCache<String, Bitmap> getBitmapCache() {
3738		return this.mBitmapCache;
3739	}
3740
3741	public Collection<String> getKnownHosts() {
3742		final Set<String> hosts = new HashSet<>();
3743		for (final Account account : getAccounts()) {
3744			hosts.add(account.getServer());
3745			for (final Contact contact : account.getRoster().getContacts()) {
3746				if (contact.showInRoster()) {
3747					final String server = contact.getServer();
3748					if (server != null) {
3749						hosts.add(server);
3750					}
3751				}
3752			}
3753		}
3754		if (Config.QUICKSY_DOMAIN != null) {
3755		    hosts.remove(Config.QUICKSY_DOMAIN); //we only want to show this when we type a e164 number
3756        }
3757		if (Config.DOMAIN_LOCK != null) {
3758			hosts.add(Config.DOMAIN_LOCK);
3759		}
3760		if (Config.MAGIC_CREATE_DOMAIN != null) {
3761			hosts.add(Config.MAGIC_CREATE_DOMAIN);
3762		}
3763		return hosts;
3764	}
3765
3766	public Collection<String> getKnownConferenceHosts() {
3767		final Set<String> mucServers = new HashSet<>();
3768		for (final Account account : accounts) {
3769			if (account.getXmppConnection() != null) {
3770				mucServers.addAll(account.getXmppConnection().getMucServers());
3771				for (Bookmark bookmark : account.getBookmarks()) {
3772					final Jid jid = bookmark.getJid();
3773					final String s = jid == null ? null : jid.getDomain();
3774					if (s != null) {
3775						mucServers.add(s);
3776					}
3777				}
3778			}
3779		}
3780		return mucServers;
3781	}
3782
3783	public void sendMessagePacket(Account account, MessagePacket packet) {
3784		XmppConnection connection = account.getXmppConnection();
3785		if (connection != null) {
3786			connection.sendMessagePacket(packet);
3787		}
3788	}
3789
3790	public void sendPresencePacket(Account account, PresencePacket packet) {
3791		XmppConnection connection = account.getXmppConnection();
3792		if (connection != null) {
3793			connection.sendPresencePacket(packet);
3794		}
3795	}
3796
3797	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3798		final XmppConnection connection = account.getXmppConnection();
3799		if (connection != null) {
3800			IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3801			connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
3802		}
3803	}
3804
3805	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3806		final XmppConnection connection = account.getXmppConnection();
3807		if (connection != null) {
3808			connection.sendIqPacket(packet, callback);
3809		} else if (callback != null) {
3810		    callback.onIqPacketReceived(account,new IqPacket(IqPacket.TYPE.TIMEOUT));
3811        }
3812	}
3813
3814	public void sendPresence(final Account account) {
3815		sendPresence(account, checkListeners() && broadcastLastActivity());
3816	}
3817
3818	private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3819		Presence.Status status;
3820		if (manuallyChangePresence()) {
3821			status = account.getPresenceStatus();
3822		} else {
3823			status = getTargetPresence();
3824		}
3825		PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
3826		String message = account.getPresenceStatusMessage();
3827		if (message != null && !message.isEmpty()) {
3828			packet.addChild(new Element("status").setContent(message));
3829		}
3830		if (mLastActivity > 0 && includeIdleTimestamp) {
3831			long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3832			packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
3833		}
3834		sendPresencePacket(account, packet);
3835	}
3836
3837	private void deactivateGracePeriod() {
3838		for (Account account : getAccounts()) {
3839			account.deactivateGracePeriod();
3840		}
3841	}
3842
3843	public void refreshAllPresences() {
3844		boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3845		for (Account account : getAccounts()) {
3846			if (account.isEnabled()) {
3847				sendPresence(account, includeIdleTimestamp);
3848			}
3849		}
3850	}
3851
3852	private void refreshAllFcmTokens() {
3853		for (Account account : getAccounts()) {
3854			if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3855				mPushManagementService.registerPushTokenOnServer(account);
3856			}
3857		}
3858	}
3859
3860	private void sendOfflinePresence(final Account account) {
3861		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
3862		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3863	}
3864
3865	public MessageGenerator getMessageGenerator() {
3866		return this.mMessageGenerator;
3867	}
3868
3869	public PresenceGenerator getPresenceGenerator() {
3870		return this.mPresenceGenerator;
3871	}
3872
3873	public IqGenerator getIqGenerator() {
3874		return this.mIqGenerator;
3875	}
3876
3877	public IqParser getIqParser() {
3878		return this.mIqParser;
3879	}
3880
3881	public JingleConnectionManager getJingleConnectionManager() {
3882		return this.mJingleConnectionManager;
3883	}
3884
3885	public MessageArchiveService getMessageArchiveService() {
3886		return this.mMessageArchiveService;
3887	}
3888
3889	public QuickConversationsService getQuickConversationsService() {
3890        return this.mQuickConversationsService;
3891    }
3892
3893	public List<Contact> findContacts(Jid jid, String accountJid) {
3894		ArrayList<Contact> contacts = new ArrayList<>();
3895		for (Account account : getAccounts()) {
3896			if ((account.isEnabled() || accountJid != null)
3897					&& (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
3898				Contact contact = account.getRoster().getContactFromContactList(jid);
3899				if (contact != null) {
3900					contacts.add(contact);
3901				}
3902			}
3903		}
3904		return contacts;
3905	}
3906
3907	public Conversation findFirstMuc(Jid jid) {
3908		for (Conversation conversation : getConversations()) {
3909			if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
3910				return conversation;
3911			}
3912		}
3913		return null;
3914	}
3915
3916	public NotificationService getNotificationService() {
3917		return this.mNotificationService;
3918	}
3919
3920	public HttpConnectionManager getHttpConnectionManager() {
3921		return this.mHttpConnectionManager;
3922	}
3923
3924	public void resendFailedMessages(final Message message) {
3925		final Collection<Message> messages = new ArrayList<>();
3926		Message current = message;
3927		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3928			messages.add(current);
3929			if (current.mergeable(current.next())) {
3930				current = current.next();
3931			} else {
3932				break;
3933			}
3934		}
3935		for (final Message msg : messages) {
3936			msg.setTime(System.currentTimeMillis());
3937			markMessage(msg, Message.STATUS_WAITING);
3938			this.resendMessage(msg, false);
3939		}
3940		if (message.getConversation() instanceof Conversation) {
3941			((Conversation) message.getConversation()).sort();
3942		}
3943		updateConversationUi();
3944	}
3945
3946	public void clearConversationHistory(final Conversation conversation) {
3947		final long clearDate;
3948		final String reference;
3949		if (conversation.countMessages() > 0) {
3950			Message latestMessage = conversation.getLatestMessage();
3951			clearDate = latestMessage.getTimeSent() + 1000;
3952			reference = latestMessage.getServerMsgId();
3953		} else {
3954			clearDate = System.currentTimeMillis();
3955			reference = null;
3956		}
3957		conversation.clearMessages();
3958		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3959		conversation.setLastClearHistory(clearDate, reference);
3960		Runnable runnable = () -> {
3961			databaseBackend.deleteMessagesInConversation(conversation);
3962			databaseBackend.updateConversation(conversation);
3963		};
3964		mDatabaseWriterExecutor.execute(runnable);
3965	}
3966
3967	public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
3968		if (blockable != null && blockable.getBlockedJid() != null) {
3969			final Jid jid = blockable.getBlockedJid();
3970			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), new OnIqPacketReceived() {
3971
3972				@Override
3973				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3974					if (packet.getType() == IqPacket.TYPE.RESULT) {
3975						account.getBlocklist().add(jid);
3976						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3977					}
3978				}
3979			});
3980			if (removeBlockedConversations(blockable.getAccount(), jid)) {
3981				updateConversationUi();
3982				return true;
3983			} else {
3984				return false;
3985			}
3986		} else {
3987			return false;
3988		}
3989	}
3990
3991	public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
3992		boolean removed = false;
3993		synchronized (this.conversations) {
3994			boolean domainJid = blockedJid.getLocal() == null;
3995			for (Conversation conversation : this.conversations) {
3996				boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
3997						|| blockedJid.equals(conversation.getJid().asBareJid());
3998				if (conversation.getAccount() == account
3999						&& conversation.getMode() == Conversation.MODE_SINGLE
4000						&& jidMatches) {
4001					this.conversations.remove(conversation);
4002					markRead(conversation);
4003					conversation.setStatus(Conversation.STATUS_ARCHIVED);
4004					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
4005					updateConversation(conversation);
4006					removed = true;
4007				}
4008			}
4009		}
4010		return removed;
4011	}
4012
4013	public void sendUnblockRequest(final Blockable blockable) {
4014		if (blockable != null && blockable.getJid() != null) {
4015			final Jid jid = blockable.getBlockedJid();
4016			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
4017				@Override
4018				public void onIqPacketReceived(final Account account, final IqPacket packet) {
4019					if (packet.getType() == IqPacket.TYPE.RESULT) {
4020						account.getBlocklist().remove(jid);
4021						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
4022					}
4023				}
4024			});
4025		}
4026	}
4027
4028	public void publishDisplayName(Account account) {
4029		String displayName = account.getDisplayName();
4030		final IqPacket request;
4031		if (TextUtils.isEmpty(displayName)) {
4032            request = mIqGenerator.deleteNode(Namespace.NICK);
4033		} else {
4034            request = mIqGenerator.publishNick(displayName);
4035        }
4036        mAvatarService.clear(account);
4037        sendIqPacket(account, request, (account1, packet) -> {
4038            if (packet.getType() == IqPacket.TYPE.ERROR) {
4039                Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": unable to modify nick name "+packet.toString());
4040            }
4041        });
4042	}
4043
4044	public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
4045		ServiceDiscoveryResult result = discoCache.get(key);
4046		if (result != null) {
4047			return result;
4048		} else {
4049			result = databaseBackend.findDiscoveryResult(key.first, key.second);
4050			if (result != null) {
4051				discoCache.put(key, result);
4052			}
4053			return result;
4054		}
4055	}
4056
4057	public void fetchCaps(Account account, final Jid jid, final Presence presence) {
4058		final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
4059		ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
4060		if (disco != null) {
4061			presence.setServiceDiscoveryResult(disco);
4062		} else {
4063			if (!account.inProgressDiscoFetches.contains(key)) {
4064				account.inProgressDiscoFetches.add(key);
4065				IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4066				request.setTo(jid);
4067				final String node = presence.getNode();
4068				final String ver = presence.getVer();
4069				final Element query = request.query("http://jabber.org/protocol/disco#info");
4070				if (node != null && ver != null) {
4071					query.setAttribute("node",node+"#"+ver);
4072				}
4073				Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
4074				sendIqPacket(account, request, (a, response) -> {
4075					if (response.getType() == IqPacket.TYPE.RESULT) {
4076						ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
4077						if (presence.getVer().equals(discoveryResult.getVer())) {
4078							databaseBackend.insertDiscoveryResult(discoveryResult);
4079							injectServiceDiscoveryResult(a.getRoster(), presence.getHash(), presence.getVer(), discoveryResult);
4080						} else {
4081							Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
4082						}
4083					}
4084					a.inProgressDiscoFetches.remove(key);
4085				});
4086			}
4087		}
4088	}
4089
4090	private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
4091		for (Contact contact : roster.getContacts()) {
4092			for (Presence presence : contact.getPresences().getPresences().values()) {
4093				if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
4094					presence.setServiceDiscoveryResult(disco);
4095				}
4096			}
4097		}
4098	}
4099
4100	public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
4101		final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
4102		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4103		request.addChild("prefs", version.namespace);
4104		sendIqPacket(account, request, (account1, packet) -> {
4105			Element prefs = packet.findChild("prefs", version.namespace);
4106			if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
4107				callback.onPreferencesFetched(prefs);
4108			} else {
4109				callback.onPreferencesFetchFailed();
4110			}
4111		});
4112	}
4113
4114	public PushManagementService getPushManagementService() {
4115		return mPushManagementService;
4116	}
4117
4118	public void changeStatus(Account account, PresenceTemplate template, String signature) {
4119		if (!template.getStatusMessage().isEmpty()) {
4120			databaseBackend.insertPresenceTemplate(template);
4121		}
4122		account.setPgpSignature(signature);
4123		account.setPresenceStatus(template.getStatus());
4124		account.setPresenceStatusMessage(template.getStatusMessage());
4125		databaseBackend.updateAccount(account);
4126		sendPresence(account);
4127	}
4128
4129	public List<PresenceTemplate> getPresenceTemplates(Account account) {
4130		List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
4131		for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
4132			if (!templates.contains(template)) {
4133				templates.add(0, template);
4134			}
4135		}
4136		return templates;
4137	}
4138
4139	public void saveConversationAsBookmark(Conversation conversation, String name) {
4140		Account account = conversation.getAccount();
4141		Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
4142		if (!conversation.getJid().isBareJid()) {
4143			bookmark.setNick(conversation.getJid().getResource());
4144		}
4145		if (!TextUtils.isEmpty(name)) {
4146			bookmark.setBookmarkName(name);
4147		}
4148		bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
4149		account.getBookmarks().add(bookmark);
4150		pushBookmarks(account);
4151		bookmark.setConversation(conversation);
4152	}
4153
4154	public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
4155		boolean performedVerification = false;
4156		final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
4157		for (XmppUri.Fingerprint fp : fingerprints) {
4158			if (fp.type == XmppUri.FingerprintType.OMEMO) {
4159				String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4160				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4161				if (fingerprintStatus != null) {
4162					if (!fingerprintStatus.isVerified()) {
4163						performedVerification = true;
4164						axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4165					}
4166				} else {
4167					axolotlService.preVerifyFingerprint(contact, fingerprint);
4168				}
4169			}
4170		}
4171		return performedVerification;
4172	}
4173
4174	public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
4175		final AxolotlService axolotlService = account.getAxolotlService();
4176		boolean verifiedSomething = false;
4177		for (XmppUri.Fingerprint fp : fingerprints) {
4178			if (fp.type == XmppUri.FingerprintType.OMEMO) {
4179				String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4180				Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
4181				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4182				if (fingerprintStatus != null) {
4183					if (!fingerprintStatus.isVerified()) {
4184						axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4185						verifiedSomething = true;
4186					}
4187				} else {
4188					axolotlService.preVerifyFingerprint(account, fingerprint);
4189					verifiedSomething = true;
4190				}
4191			}
4192		}
4193		return verifiedSomething;
4194	}
4195
4196	public boolean blindTrustBeforeVerification() {
4197		return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
4198	}
4199
4200	public ShortcutService getShortcutService() {
4201		return mShortcutService;
4202	}
4203
4204	public void pushMamPreferences(Account account, Element prefs) {
4205		IqPacket set = new IqPacket(IqPacket.TYPE.SET);
4206		set.addChild(prefs);
4207		sendIqPacket(account, set, null);
4208	}
4209
4210	public interface OnMamPreferencesFetched {
4211		void onPreferencesFetched(Element prefs);
4212
4213		void onPreferencesFetchFailed();
4214	}
4215
4216	public interface OnAccountCreated {
4217		void onAccountCreated(Account account);
4218
4219		void informUser(int r);
4220	}
4221
4222	public interface OnMoreMessagesLoaded {
4223		void onMoreMessagesLoaded(int count, Conversation conversation);
4224
4225		void informUser(int r);
4226	}
4227
4228	public interface OnAccountPasswordChanged {
4229		void onPasswordChangeSucceeded();
4230
4231		void onPasswordChangeFailed();
4232	}
4233
4234    public interface OnRoomDestroy {
4235        void onRoomDestroySucceeded();
4236
4237        void onRoomDestroyFailed();
4238    }
4239
4240	public interface OnAffiliationChanged {
4241		void onAffiliationChangedSuccessful(Jid jid);
4242
4243		void onAffiliationChangeFailed(Jid jid, int resId);
4244	}
4245
4246	public interface OnRoleChanged {
4247		void onRoleChangedSuccessful(String nick);
4248
4249		void onRoleChangeFailed(String nick, int resid);
4250	}
4251
4252	public interface OnConversationUpdate {
4253		void onConversationUpdate();
4254	}
4255
4256	public interface OnAccountUpdate {
4257		void onAccountUpdate();
4258	}
4259
4260	public interface OnCaptchaRequested {
4261		void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
4262	}
4263
4264	public interface OnRosterUpdate {
4265		void onRosterUpdate();
4266	}
4267
4268	public interface OnMucRosterUpdate {
4269		void onMucRosterUpdate();
4270	}
4271
4272	public interface OnConferenceConfigurationFetched {
4273		void onConferenceConfigurationFetched(Conversation conversation);
4274
4275		void onFetchFailed(Conversation conversation, Element error);
4276	}
4277
4278	public interface OnConferenceJoined {
4279		void onConferenceJoined(Conversation conversation);
4280	}
4281
4282	public interface OnConfigurationPushed {
4283		void onPushSucceeded();
4284
4285		void onPushFailed();
4286	}
4287
4288	public interface OnShowErrorToast {
4289		void onShowErrorToast(int resId);
4290	}
4291
4292	public class XmppConnectionBinder extends Binder {
4293		public XmppConnectionService getService() {
4294			return XmppConnectionService.this;
4295		}
4296	}
4297
4298	private class InternalEventReceiver extends BroadcastReceiver {
4299
4300        @Override
4301        public void onReceive(Context context, Intent intent) {
4302            onStartCommand(intent,0,0);
4303        }
4304    }
4305}