XmppConnectionService.java

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