XmppConnectionService.java

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