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