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                Collection<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 Collection<Bookmark> bookmarks = Bookmark.parseFromPubsub(pubsub, account);
1584                    processBookmarksInitial(account, bookmarks, true);
1585                }
1586            }
1587        });
1588    }
1589
1590    public void processBookmarksInitial(Account account, Collection<Bookmark> bookmarks, final boolean pep) {
1591        final Set<Jid> previousBookmarks = account.getBookmarkedJids();
1592        final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
1593        for (Bookmark bookmark : bookmarks) {
1594            previousBookmarks.remove(bookmark.getJid().asBareJid());
1595            Conversation conversation = find(bookmark);
1596            if (conversation != null) {
1597                if (conversation.getMode() != Conversation.MODE_MULTI) {
1598                    continue;
1599                }
1600                bookmark.setConversation(conversation);
1601                if (pep && synchronizeWithBookmarks && !bookmark.autojoin()) {
1602                    Log.d(Config.LOGTAG,account.getJid().asBareJid()+": archiving conference ("+conversation.getJid()+") after receiving pep");
1603                    archiveConversation(conversation, false);
1604                }
1605            } else if (synchronizeWithBookmarks && bookmark.autojoin()) {
1606                conversation = findOrCreateConversation(account, bookmark.getFullJid(), true, true, false);
1607                bookmark.setConversation(conversation);
1608            }
1609        }
1610        if (pep && synchronizeWithBookmarks) {
1611            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + previousBookmarks.size() + " bookmarks have been removed");
1612            for (Jid jid : previousBookmarks) {
1613                final Conversation conversation = find(account, jid);
1614                if (conversation != null && conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
1615                    Log.d(Config.LOGTAG,account.getJid().asBareJid()+": archiving destroyed conference ("+conversation.getJid()+") after receiving pep");
1616                    archiveConversation(conversation, false);
1617                }
1618            }
1619        }
1620        account.setBookmarks(new CopyOnWriteArrayList<>(bookmarks));
1621    }
1622
1623    public void createBookmark(final Account account, final Bookmark bookmark) {
1624        final XmppConnection connection = account.getXmppConnection();
1625        if (connection.getFeatures().bookmarks2()) {
1626            final Element item = mIqGenerator.publishBookmarkItem(bookmark);
1627            pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARK, item, bookmark.getJid().asBareJid().toEscapedString(), PublishOptions.persistentWhitelistAccessMaxItems());
1628        } else if (connection.getFeatures().bookmarksConversion()) {
1629            pushBookmarksPep(account);
1630        } else {
1631            pushBookmarksPrivateXml(account);
1632        }
1633    }
1634
1635    public void deleteBookmark(final Account account, final Bookmark bookmark) {
1636        final XmppConnection connection = account.getXmppConnection();
1637        if (connection.getFeatures().bookmarksConversion()) {
1638            IqPacket request = mIqGenerator.deleteItem(Namespace.BOOKMARK, bookmark.getJid().asBareJid().toEscapedString());
1639            sendIqPacket(account, request, new OnIqPacketReceived() {
1640                @Override
1641                public void onIqPacketReceived(Account account, IqPacket packet) {
1642                    Log.d(Config.LOGTAG,packet.toString());
1643                }
1644            });
1645        } else if (connection.getFeatures().bookmarksConversion()) {
1646            pushBookmarksPep(account);
1647        } else {
1648            pushBookmarksPrivateXml(account);
1649        }
1650    }
1651
1652    private void pushBookmarksPrivateXml(Account account) {
1653        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
1654        IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1655        Element query = iqPacket.query("jabber:iq:private");
1656        Element storage = query.addChild("storage", "storage:bookmarks");
1657        for (Bookmark bookmark : account.getBookmarks()) {
1658            storage.addChild(bookmark);
1659        }
1660        sendIqPacket(account, iqPacket, mDefaultIqHandler);
1661    }
1662
1663    private void pushBookmarksPep(Account account) {
1664        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
1665        Element storage = new Element("storage", "storage:bookmarks");
1666        for (Bookmark bookmark : account.getBookmarks()) {
1667            storage.addChild(bookmark);
1668        }
1669        pushNodeAndEnforcePublishOptions(account,Namespace.BOOKMARKS,storage, PublishOptions.persistentWhitelistAccess());
1670
1671    }
1672
1673    private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final Bundle options) {
1674        pushNodeAndEnforcePublishOptions(account, node, element, null, options, true);
1675
1676    }
1677
1678    private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options) {
1679        pushNodeAndEnforcePublishOptions(account, node, element, id, options, true);
1680
1681    }
1682
1683	private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options, final boolean retry) {
1684        final IqPacket packet = mIqGenerator.publishElement(node, element, id, options);
1685        sendIqPacket(account, packet, (a, response) -> {
1686            if (response.getType() == IqPacket.TYPE.RESULT) {
1687                return;
1688            }
1689            if (retry && PublishOptions.preconditionNotMet(response)) {
1690                pushNodeConfiguration(account, node, options, new OnConfigurationPushed() {
1691                    @Override
1692                    public void onPushSucceeded() {
1693                        pushNodeAndEnforcePublishOptions(account, node, element, id, options, false);
1694                    }
1695
1696                    @Override
1697                    public void onPushFailed() {
1698                        Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to push node configuration ("+node+")");
1699                    }
1700                });
1701            } else {
1702                Log.d(Config.LOGTAG,account.getJid().asBareJid()+": error publishing bookmarks (retry="+Boolean.toString(retry)+") "+response);
1703            }
1704        });
1705    }
1706
1707	private void restoreFromDatabase() {
1708		synchronized (this.conversations) {
1709			final Map<String, Account> accountLookupTable = new Hashtable<>();
1710			for (Account account : this.accounts) {
1711				accountLookupTable.put(account.getUuid(), account);
1712			}
1713			Log.d(Config.LOGTAG, "restoring conversations...");
1714			final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
1715			this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1716			for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
1717				Conversation conversation = iterator.next();
1718				Account account = accountLookupTable.get(conversation.getAccountUuid());
1719				if (account != null) {
1720					conversation.setAccount(account);
1721				} else {
1722					Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
1723					iterator.remove();
1724				}
1725			}
1726			long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
1727			Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
1728			Runnable runnable = () -> {
1729				long deletionDate = getAutomaticMessageDeletionDate();
1730				mLastExpiryRun.set(SystemClock.elapsedRealtime());
1731				if (deletionDate > 0) {
1732					Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
1733					databaseBackend.expireOldMessages(deletionDate);
1734				}
1735				Log.d(Config.LOGTAG, "restoring roster...");
1736				for (Account account : accounts) {
1737					databaseBackend.readRoster(account.getRoster());
1738					account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1739				}
1740				getBitmapCache().evictAll();
1741				loadPhoneContacts();
1742				Log.d(Config.LOGTAG, "restoring messages...");
1743				final long startMessageRestore = SystemClock.elapsedRealtime();
1744				final Conversation quickLoad = QuickLoader.get(this.conversations);
1745				if (quickLoad != null) {
1746					restoreMessages(quickLoad);
1747					updateConversationUi();
1748					final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1749					Log.d(Config.LOGTAG,"quickly restored "+quickLoad.getName()+" after " + diffMessageRestore + "ms");
1750				}
1751				for (Conversation conversation : this.conversations) {
1752					if (quickLoad != conversation) {
1753						restoreMessages(conversation);
1754					}
1755				}
1756				mNotificationService.finishBacklog(false);
1757				restoredFromDatabaseLatch.countDown();
1758				final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1759				Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
1760				updateConversationUi();
1761			};
1762			mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
1763		}
1764	}
1765
1766	private void restoreMessages(Conversation conversation) {
1767		conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1768		conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
1769		conversation.findUnreadMessages(message -> mNotificationService.pushFromBacklog(message));
1770	}
1771
1772	public void loadPhoneContacts() {
1773        mContactMergerExecutor.execute(() -> {
1774            Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
1775            Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1776            for (Account account : accounts) {
1777                List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts(JabberIdContact.class);
1778                for (JabberIdContact jidContact : contacts.values()) {
1779                    final Contact contact = account.getRoster().getContact(jidContact.getJid());
1780                    boolean needsCacheClean = contact.setPhoneContact(jidContact);
1781                    if (needsCacheClean) {
1782                        getAvatarService().clear(contact);
1783                    }
1784                    withSystemAccounts.remove(contact);
1785                }
1786                for (Contact contact : withSystemAccounts) {
1787                    boolean needsCacheClean = contact.unsetPhoneContact(JabberIdContact.class);
1788                    if (needsCacheClean) {
1789                        getAvatarService().clear(contact);
1790                    }
1791                }
1792            }
1793            Log.d(Config.LOGTAG, "finished merging phone contacts");
1794            mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
1795            updateRosterUi();
1796            mQuickConversationsService.considerSync();
1797        });
1798	}
1799
1800
1801	public void syncRoster(final Account account) {
1802		mRosterSyncTaskManager.execute(account, () -> databaseBackend.writeRoster(account.getRoster()));
1803	}
1804
1805	public List<Conversation> getConversations() {
1806		return this.conversations;
1807	}
1808
1809	private void markFileDeleted(final String path) {
1810        final File file = new File(path);
1811        final boolean isInternalFile = fileBackend.isInternalFile(file);
1812        final List<String> uuids = databaseBackend.markFileAsDeleted(file, isInternalFile);
1813        Log.d(Config.LOGTAG, "deleted file " + path+" internal="+isInternalFile+", database hits="+uuids.size());
1814        markUuidsAsDeletedFiles(uuids);
1815	}
1816
1817	private void markUuidsAsDeletedFiles(List<String> uuids) {
1818        boolean deleted = false;
1819        for (Conversation conversation : getConversations()) {
1820            deleted |= conversation.markAsDeleted(uuids);
1821        }
1822        if (deleted) {
1823            updateConversationUi();
1824        }
1825    }
1826
1827    private void markChangedFiles(List<DatabaseBackend.FilePathInfo> infos) {
1828        boolean changed = false;
1829        for (Conversation conversation : getConversations()) {
1830            changed |= conversation.markAsChanged(infos);
1831        }
1832        if (changed) {
1833            updateConversationUi();
1834        }
1835    }
1836
1837	public void populateWithOrderedConversations(final List<Conversation> list) {
1838		populateWithOrderedConversations(list, true, true);
1839	}
1840
1841	public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload) {
1842        populateWithOrderedConversations(list, includeNoFileUpload, true);
1843    }
1844
1845	public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload, final boolean sort) {
1846        final List<String> orderedUuids;
1847        if (sort) {
1848            orderedUuids = null;
1849        } else {
1850            orderedUuids = new ArrayList<>();
1851            for(Conversation conversation : list) {
1852                orderedUuids.add(conversation.getUuid());
1853            }
1854        }
1855		list.clear();
1856		if (includeNoFileUpload) {
1857			list.addAll(getConversations());
1858		} else {
1859			for (Conversation conversation : getConversations()) {
1860				if (conversation.getMode() == Conversation.MODE_SINGLE
1861						|| (conversation.getAccount().httpUploadAvailable() && conversation.getMucOptions().participating())) {
1862					list.add(conversation);
1863				}
1864			}
1865		}
1866		try {
1867		    if (orderedUuids != null) {
1868                Collections.sort(list, (a, b) -> {
1869                    final int indexA = orderedUuids.indexOf(a.getUuid());
1870                    final int indexB = orderedUuids.indexOf(b.getUuid());
1871                    if (indexA == -1 || indexB == -1 || indexA == indexB) {
1872                        return a.compareTo(b);
1873                    }
1874                    return indexA - indexB;
1875                });
1876            } else {
1877                Collections.sort(list);
1878            }
1879		} catch (IllegalArgumentException e) {
1880			//ignore
1881		}
1882	}
1883
1884	public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1885		if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
1886			return;
1887		} else if (timestamp == 0) {
1888			return;
1889		}
1890		Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1891		final Runnable runnable = () -> {
1892			final Account account = conversation.getAccount();
1893			List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
1894			if (messages.size() > 0) {
1895				conversation.addAll(0, messages);
1896				callback.onMoreMessagesLoaded(messages.size(), conversation);
1897			} else if (conversation.hasMessagesLeftOnServer()
1898					&& account.isOnlineAndConnected()
1899					&& conversation.getLastClearHistory().getTimestamp() == 0) {
1900				final boolean mamAvailable;
1901				if (conversation.getMode() == Conversation.MODE_SINGLE) {
1902					mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
1903				} else {
1904					mamAvailable = conversation.getMucOptions().mamSupport();
1905				}
1906				if (mamAvailable) {
1907					MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
1908					if (query != null) {
1909						query.setCallback(callback);
1910						callback.informUser(R.string.fetching_history_from_server);
1911					} else {
1912						callback.informUser(R.string.not_fetching_history_retention_period);
1913					}
1914
1915				}
1916			}
1917		};
1918		mDatabaseReaderExecutor.execute(runnable);
1919	}
1920
1921	public List<Account> getAccounts() {
1922		return this.accounts;
1923	}
1924
1925
1926    /**
1927     * 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)
1928     */
1929	public List<Conversation> findAllConferencesWith(Contact contact) {
1930		ArrayList<Conversation> results = new ArrayList<>();
1931		for (final Conversation c : conversations) {
1932			if (c.getMode() == Conversation.MODE_MULTI && (c.getJid().asBareJid().equals(contact.getJid().asBareJid()) || c.getMucOptions().isContactInRoom(contact))) {
1933			    results.add(c);
1934			}
1935		}
1936		return results;
1937	}
1938
1939	public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1940		for (final Conversation conversation : haystack) {
1941			if (conversation.getContact() == contact) {
1942				return conversation;
1943			}
1944		}
1945		return null;
1946	}
1947
1948	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1949		if (jid == null) {
1950			return null;
1951		}
1952		for (final Conversation conversation : haystack) {
1953			if ((account == null || conversation.getAccount() == account)
1954					&& (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
1955				return conversation;
1956			}
1957		}
1958		return null;
1959	}
1960
1961	public boolean isConversationsListEmpty(final Conversation ignore) {
1962		synchronized (this.conversations) {
1963			final int size = this.conversations.size();
1964			return size == 0 || size == 1 && this.conversations.get(0) == ignore;
1965		}
1966	}
1967
1968	public boolean isConversationStillOpen(final Conversation conversation) {
1969		synchronized (this.conversations) {
1970			for (Conversation current : this.conversations) {
1971				if (current == conversation) {
1972					return true;
1973				}
1974			}
1975		}
1976		return false;
1977	}
1978
1979	public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
1980		return this.findOrCreateConversation(account, jid, muc, false, async);
1981	}
1982
1983	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
1984		return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
1985	}
1986
1987	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
1988		synchronized (this.conversations) {
1989			Conversation conversation = find(account, jid);
1990			if (conversation != null) {
1991				return conversation;
1992			}
1993			conversation = databaseBackend.findConversation(account, jid);
1994			final boolean loadMessagesFromDb;
1995			if (conversation != null) {
1996				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1997				conversation.setAccount(account);
1998				if (muc) {
1999					conversation.setMode(Conversation.MODE_MULTI);
2000					conversation.setContactJid(jid);
2001				} else {
2002					conversation.setMode(Conversation.MODE_SINGLE);
2003					conversation.setContactJid(jid.asBareJid());
2004				}
2005				databaseBackend.updateConversation(conversation);
2006				loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
2007			} else {
2008				String conversationName;
2009				Contact contact = account.getRoster().getContact(jid);
2010				if (contact != null) {
2011					conversationName = contact.getDisplayName();
2012				} else {
2013					conversationName = jid.getLocal();
2014				}
2015				if (muc) {
2016					conversation = new Conversation(conversationName, account, jid,
2017							Conversation.MODE_MULTI);
2018				} else {
2019					conversation = new Conversation(conversationName, account, jid.asBareJid(),
2020							Conversation.MODE_SINGLE);
2021				}
2022				this.databaseBackend.createConversation(conversation);
2023				loadMessagesFromDb = false;
2024			}
2025			final Conversation c = conversation;
2026			final Runnable runnable = () -> {
2027				if (loadMessagesFromDb) {
2028					c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
2029					updateConversationUi();
2030					c.messagesLoaded.set(true);
2031				}
2032				if (account.getXmppConnection() != null
2033						&& !c.getContact().isBlocked()
2034						&& account.getXmppConnection().getFeatures().mam()
2035						&& !muc) {
2036					if (query == null) {
2037						mMessageArchiveService.query(c);
2038					} else {
2039						if (query.getConversation() == null) {
2040							mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
2041						}
2042					}
2043				}
2044				if (joinAfterCreate) {
2045					joinMuc(c);
2046				}
2047			};
2048			if (async) {
2049				mDatabaseReaderExecutor.execute(runnable);
2050			} else {
2051				runnable.run();
2052			}
2053			this.conversations.add(conversation);
2054			updateConversationUi();
2055			return conversation;
2056		}
2057	}
2058
2059	public void archiveConversation(Conversation conversation) {
2060	    archiveConversation(conversation, true);
2061    }
2062
2063	private void archiveConversation(Conversation conversation, final boolean maySynchronizeWithBookmarks) {
2064		getNotificationService().clear(conversation);
2065		conversation.setStatus(Conversation.STATUS_ARCHIVED);
2066		conversation.setNextMessage(null);
2067		synchronized (this.conversations) {
2068			getMessageArchiveService().kill(conversation);
2069			if (conversation.getMode() == Conversation.MODE_MULTI) {
2070				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2071					Bookmark bookmark = conversation.getBookmark();
2072					if (maySynchronizeWithBookmarks && bookmark != null && synchronizeWithBookmarks()) {
2073						if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2074							Account account = bookmark.getAccount();
2075							bookmark.setConversation(null);
2076							account.getBookmarks().remove(bookmark);
2077							deleteBookmark(account, bookmark);
2078						} else if (bookmark.autojoin()) {
2079							bookmark.setAutojoin(false);
2080							createBookmark(bookmark.getAccount(), bookmark);
2081						}
2082					}
2083				}
2084                if (conversation.getMucOptions().push()) {
2085                    disableDirectMucPush(conversation);
2086                    mPushManagementService.disablePushOnServer(conversation);
2087                }
2088				leaveMuc(conversation);
2089			} else {
2090				if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2091				    stopPresenceUpdatesTo(conversation.getContact());
2092				}
2093			}
2094			updateConversation(conversation);
2095			this.conversations.remove(conversation);
2096			updateConversationUi();
2097		}
2098	}
2099
2100	public void stopPresenceUpdatesTo(Contact contact) {
2101        Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
2102        sendPresencePacket(contact.getAccount(), mPresenceGenerator.stopPresenceUpdatesTo(contact));
2103        contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2104    }
2105
2106	public void createAccount(final Account account) {
2107		account.initAccountServices(this);
2108		databaseBackend.createAccount(account);
2109		this.accounts.add(account);
2110		this.reconnectAccountInBackground(account);
2111		updateAccountUi();
2112		syncEnabledAccountSetting();
2113		toggleForegroundService();
2114	}
2115
2116	private void syncEnabledAccountSetting() {
2117	    final boolean hasEnabledAccounts = hasEnabledAccounts();
2118		getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
2119		toggleSetProfilePictureActivity(hasEnabledAccounts);
2120	}
2121
2122	private void toggleSetProfilePictureActivity(final boolean enabled) {
2123	    try {
2124	        final ComponentName name = new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
2125	        final int targetState =  enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
2126            getPackageManager().setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
2127        } catch (IllegalStateException e) {
2128	        Log.d(Config.LOGTAG,"unable to toggle profile picture actvitiy");
2129        }
2130    }
2131
2132	public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
2133		new Thread(() -> {
2134			try {
2135				final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
2136				final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
2137				if (cert == null) {
2138					callback.informUser(R.string.unable_to_parse_certificate);
2139					return;
2140				}
2141				Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
2142				if (info == null) {
2143					callback.informUser(R.string.certificate_does_not_contain_jid);
2144					return;
2145				}
2146				if (findAccountByJid(info.first) == null) {
2147					Account account = new Account(info.first, "");
2148					account.setPrivateKeyAlias(alias);
2149					account.setOption(Account.OPTION_DISABLED, true);
2150					account.setDisplayName(info.second);
2151					createAccount(account);
2152					callback.onAccountCreated(account);
2153					if (Config.X509_VERIFICATION) {
2154						try {
2155							getMemorizingTrustManager().getNonInteractive(account.getJid().getDomain()).checkClientTrusted(chain, "RSA");
2156						} catch (CertificateException e) {
2157							callback.informUser(R.string.certificate_chain_is_not_trusted);
2158						}
2159					}
2160				} else {
2161					callback.informUser(R.string.account_already_exists);
2162				}
2163			} catch (Exception e) {
2164				e.printStackTrace();
2165				callback.informUser(R.string.unable_to_parse_certificate);
2166			}
2167		}).start();
2168
2169	}
2170
2171	public void updateKeyInAccount(final Account account, final String alias) {
2172		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
2173		try {
2174			X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
2175			Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
2176			Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
2177			if (info == null) {
2178				showErrorToastInUi(R.string.certificate_does_not_contain_jid);
2179				return;
2180			}
2181			if (account.getJid().asBareJid().equals(info.first)) {
2182				account.setPrivateKeyAlias(alias);
2183				account.setDisplayName(info.second);
2184				databaseBackend.updateAccount(account);
2185				if (Config.X509_VERIFICATION) {
2186					try {
2187						getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
2188					} catch (CertificateException e) {
2189						showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
2190					}
2191					account.getAxolotlService().regenerateKeys(true);
2192				}
2193			} else {
2194				showErrorToastInUi(R.string.jid_does_not_match_certificate);
2195			}
2196		} catch (Exception e) {
2197			e.printStackTrace();
2198		}
2199	}
2200
2201	public boolean updateAccount(final Account account) {
2202		if (databaseBackend.updateAccount(account)) {
2203			account.setShowErrorNotification(true);
2204			this.statusListener.onStatusChanged(account);
2205			databaseBackend.updateAccount(account);
2206			reconnectAccountInBackground(account);
2207			updateAccountUi();
2208			getNotificationService().updateErrorNotification();
2209			toggleForegroundService();
2210			syncEnabledAccountSetting();
2211			return true;
2212		} else {
2213			return false;
2214		}
2215	}
2216
2217	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
2218		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
2219		sendIqPacket(account, iq, (a, packet) -> {
2220			if (packet.getType() == IqPacket.TYPE.RESULT) {
2221				a.setPassword(newPassword);
2222				a.setOption(Account.OPTION_MAGIC_CREATE, false);
2223				databaseBackend.updateAccount(a);
2224				callback.onPasswordChangeSucceeded();
2225			} else {
2226				callback.onPasswordChangeFailed();
2227			}
2228		});
2229	}
2230
2231	public void deleteAccount(final Account account) {
2232	    final boolean connected = account.getStatus() == Account.State.ONLINE;
2233		synchronized (this.conversations) {
2234		    if (connected) {
2235                account.getAxolotlService().deleteOmemoIdentity();
2236            }
2237            for (final Conversation conversation : conversations) {
2238                if (conversation.getAccount() == account) {
2239                    if (conversation.getMode() == Conversation.MODE_MULTI) {
2240                        if (connected) {
2241                            leaveMuc(conversation);
2242                        }
2243                    }
2244                    conversations.remove(conversation);
2245                    mNotificationService.clear(conversation);
2246                }
2247            }
2248			if (account.getXmppConnection() != null) {
2249				new Thread(() -> disconnect(account, !connected)).start();
2250			}
2251			final Runnable runnable = () -> {
2252				if (!databaseBackend.deleteAccount(account)) {
2253					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
2254				}
2255			};
2256			mDatabaseWriterExecutor.execute(runnable);
2257			this.accounts.remove(account);
2258			this.mRosterSyncTaskManager.clear(account);
2259			updateAccountUi();
2260			mNotificationService.updateErrorNotification();
2261			syncEnabledAccountSetting();
2262			toggleForegroundService();
2263		}
2264	}
2265
2266	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
2267		final boolean remainingListeners;
2268		synchronized (LISTENER_LOCK) {
2269			remainingListeners = checkListeners();
2270			if (!this.mOnConversationUpdates.add(listener)) {
2271				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as ConversationListChangedListener");
2272			}
2273			this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2274		}
2275		if (remainingListeners) {
2276			switchToForeground();
2277		}
2278	}
2279
2280	public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
2281		final boolean remainingListeners;
2282		synchronized (LISTENER_LOCK) {
2283			this.mOnConversationUpdates.remove(listener);
2284			this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2285			remainingListeners = checkListeners();
2286		}
2287		if (remainingListeners) {
2288			switchToBackground();
2289		}
2290	}
2291
2292	public void setOnShowErrorToastListener(OnShowErrorToast listener) {
2293		final boolean remainingListeners;
2294		synchronized (LISTENER_LOCK) {
2295			remainingListeners = checkListeners();
2296			if (!this.mOnShowErrorToasts.add(listener)) {
2297				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnShowErrorToastListener");
2298			}
2299		}
2300		if (remainingListeners) {
2301			switchToForeground();
2302		}
2303	}
2304
2305	public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
2306		final boolean remainingListeners;
2307		synchronized (LISTENER_LOCK) {
2308			this.mOnShowErrorToasts.remove(onShowErrorToast);
2309			remainingListeners = checkListeners();
2310		}
2311		if (remainingListeners) {
2312			switchToBackground();
2313		}
2314	}
2315
2316	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
2317		final boolean remainingListeners;
2318		synchronized (LISTENER_LOCK) {
2319			remainingListeners = checkListeners();
2320			if (!this.mOnAccountUpdates.add(listener)) {
2321				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnAccountListChangedtListener");
2322			}
2323		}
2324		if (remainingListeners) {
2325			switchToForeground();
2326		}
2327	}
2328
2329	public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
2330		final boolean remainingListeners;
2331		synchronized (LISTENER_LOCK) {
2332			this.mOnAccountUpdates.remove(listener);
2333			remainingListeners = checkListeners();
2334		}
2335		if (remainingListeners) {
2336			switchToBackground();
2337		}
2338	}
2339
2340	public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2341		final boolean remainingListeners;
2342		synchronized (LISTENER_LOCK) {
2343			remainingListeners = checkListeners();
2344			if (!this.mOnCaptchaRequested.add(listener)) {
2345				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnCaptchaRequestListener");
2346			}
2347		}
2348		if (remainingListeners) {
2349			switchToForeground();
2350		}
2351	}
2352
2353	public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2354		final boolean remainingListeners;
2355		synchronized (LISTENER_LOCK) {
2356			this.mOnCaptchaRequested.remove(listener);
2357			remainingListeners = checkListeners();
2358		}
2359		if (remainingListeners) {
2360			switchToBackground();
2361		}
2362	}
2363
2364	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
2365		final boolean remainingListeners;
2366		synchronized (LISTENER_LOCK) {
2367			remainingListeners = checkListeners();
2368			if (!this.mOnRosterUpdates.add(listener)) {
2369				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnRosterUpdateListener");
2370			}
2371		}
2372		if (remainingListeners) {
2373			switchToForeground();
2374		}
2375	}
2376
2377	public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
2378		final boolean remainingListeners;
2379		synchronized (LISTENER_LOCK) {
2380			this.mOnRosterUpdates.remove(listener);
2381			remainingListeners = checkListeners();
2382		}
2383		if (remainingListeners) {
2384			switchToBackground();
2385		}
2386	}
2387
2388	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2389		final boolean remainingListeners;
2390		synchronized (LISTENER_LOCK) {
2391			remainingListeners = checkListeners();
2392			if (!this.mOnUpdateBlocklist.add(listener)) {
2393				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnUpdateBlocklistListener");
2394			}
2395		}
2396		if (remainingListeners) {
2397			switchToForeground();
2398		}
2399	}
2400
2401	public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2402		final boolean remainingListeners;
2403		synchronized (LISTENER_LOCK) {
2404			this.mOnUpdateBlocklist.remove(listener);
2405			remainingListeners = checkListeners();
2406		}
2407		if (remainingListeners) {
2408			switchToBackground();
2409		}
2410	}
2411
2412	public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2413		final boolean remainingListeners;
2414		synchronized (LISTENER_LOCK) {
2415			remainingListeners = checkListeners();
2416			if (!this.mOnKeyStatusUpdated.add(listener)) {
2417				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnKeyStatusUpdateListener");
2418			}
2419		}
2420		if (remainingListeners) {
2421			switchToForeground();
2422		}
2423	}
2424
2425	public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
2426		final boolean remainingListeners;
2427		synchronized (LISTENER_LOCK) {
2428			this.mOnKeyStatusUpdated.remove(listener);
2429			remainingListeners = checkListeners();
2430		}
2431		if (remainingListeners) {
2432			switchToBackground();
2433		}
2434	}
2435
2436	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2437		final boolean remainingListeners;
2438		synchronized (LISTENER_LOCK) {
2439			remainingListeners = checkListeners();
2440			if (!this.mOnMucRosterUpdate.add(listener)) {
2441				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnMucRosterListener");
2442			}
2443		}
2444		if (remainingListeners) {
2445			switchToForeground();
2446		}
2447	}
2448
2449	public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
2450		final boolean remainingListeners;
2451		synchronized (LISTENER_LOCK) {
2452			this.mOnMucRosterUpdate.remove(listener);
2453			remainingListeners = checkListeners();
2454		}
2455		if (remainingListeners) {
2456			switchToBackground();
2457		}
2458	}
2459
2460	public boolean checkListeners() {
2461		return (this.mOnAccountUpdates.size() == 0
2462				&& this.mOnConversationUpdates.size() == 0
2463				&& this.mOnRosterUpdates.size() == 0
2464				&& this.mOnCaptchaRequested.size() == 0
2465				&& this.mOnMucRosterUpdate.size() == 0
2466				&& this.mOnUpdateBlocklist.size() == 0
2467				&& this.mOnShowErrorToasts.size() == 0
2468				&& this.mOnKeyStatusUpdated.size() == 0);
2469	}
2470
2471	private void switchToForeground() {
2472		final boolean broadcastLastActivity = broadcastLastActivity();
2473		for (Conversation conversation : getConversations()) {
2474			if (conversation.getMode() == Conversation.MODE_MULTI) {
2475				conversation.getMucOptions().resetChatState();
2476			} else {
2477				conversation.setIncomingChatState(Config.DEFAULT_CHATSTATE);
2478			}
2479		}
2480		for (Account account : getAccounts()) {
2481			if (account.getStatus() == Account.State.ONLINE) {
2482				account.deactivateGracePeriod();
2483				final XmppConnection connection = account.getXmppConnection();
2484				if (connection != null) {
2485					if (connection.getFeatures().csi()) {
2486						connection.sendActive();
2487					}
2488					if (broadcastLastActivity) {
2489						sendPresence(account, false); //send new presence but don't include idle because we are not
2490					}
2491				}
2492			}
2493		}
2494		Log.d(Config.LOGTAG, "app switched into foreground");
2495	}
2496
2497	private void switchToBackground() {
2498		final boolean broadcastLastActivity = broadcastLastActivity();
2499		if (broadcastLastActivity) {
2500			mLastActivity = System.currentTimeMillis();
2501			final SharedPreferences.Editor editor = getPreferences().edit();
2502			editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
2503			editor.apply();
2504		}
2505		for (Account account : getAccounts()) {
2506			if (account.getStatus() == Account.State.ONLINE) {
2507				XmppConnection connection = account.getXmppConnection();
2508				if (connection != null) {
2509					if (broadcastLastActivity) {
2510						sendPresence(account, true);
2511					}
2512					if (connection.getFeatures().csi()) {
2513						connection.sendInactive();
2514					}
2515				}
2516			}
2517		}
2518		this.mNotificationService.setIsInForeground(false);
2519		Log.d(Config.LOGTAG, "app switched into background");
2520	}
2521
2522	private void connectMultiModeConversations(Account account) {
2523		List<Conversation> conversations = getConversations();
2524		for (Conversation conversation : conversations) {
2525			if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2526				joinMuc(conversation);
2527			}
2528		}
2529	}
2530
2531	public void mucSelfPingAndRejoin(final Conversation conversation) {
2532	    final Account account = conversation.getAccount();
2533	    synchronized (account.inProgressConferenceJoins) {
2534            if (account.inProgressConferenceJoins.contains(conversation)) {
2535                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because join is already under way");
2536                return;
2537            }
2538        }
2539        synchronized (account.inProgressConferencePings) {
2540	        if (!account.inProgressConferencePings.add(conversation)) {
2541	            Log.d(Config.LOGTAG, account.getJid().asBareJid()+": canceling muc self ping because ping is already under way");
2542	            return;
2543            }
2544        }
2545	    final Jid self = conversation.getMucOptions().getSelf().getFullJid();
2546	    final IqPacket ping = new IqPacket(IqPacket.TYPE.GET);
2547	    ping.setTo(self);
2548	    ping.addChild("ping", Namespace.PING);
2549	    sendIqPacket(conversation.getAccount(), ping, (a, response) -> {
2550	        if (response.getType() == IqPacket.TYPE.ERROR) {
2551	            Element error = response.findChild("error");
2552	            if (error == null || error.hasChild("service-unavailable") || error.hasChild("feature-not-implemented") || error.hasChild("item-not-found")) {
2553	                Log.d(Config.LOGTAG,a.getJid().asBareJid()+": ping to "+self+" came back as ignorable error");
2554                } else {
2555	                Log.d(Config.LOGTAG,a.getJid().asBareJid()+": ping to "+self+" failed. attempting rejoin");
2556	                joinMuc(conversation);
2557                }
2558            } else if (response.getType() == IqPacket.TYPE.RESULT) {
2559	            Log.d(Config.LOGTAG,a.getJid().asBareJid()+": ping to "+self+" came back fine");
2560            }
2561	        synchronized (account.inProgressConferencePings) {
2562	            account.inProgressConferencePings.remove(conversation);
2563            }
2564        });
2565    }
2566
2567	public void joinMuc(Conversation conversation) {
2568		joinMuc(conversation, null, false);
2569	}
2570
2571	public void joinMuc(Conversation conversation, boolean followedInvite) {
2572		joinMuc(conversation, null, followedInvite);
2573	}
2574
2575	private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2576		joinMuc(conversation, onConferenceJoined, false);
2577	}
2578
2579	private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2580		final Account account = conversation.getAccount();
2581		synchronized (account.pendingConferenceJoins) {
2582            account.pendingConferenceJoins.remove(conversation);
2583        }
2584        synchronized (account.pendingConferenceLeaves) {
2585            account.pendingConferenceLeaves.remove(conversation);
2586        }
2587		if (account.getStatus() == Account.State.ONLINE) {
2588		    synchronized (account.inProgressConferenceJoins) {
2589                account.inProgressConferenceJoins.add(conversation);
2590            }
2591            if (Config.MUC_LEAVE_BEFORE_JOIN) {
2592                sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
2593            }
2594            conversation.resetMucOptions();
2595			if (onConferenceJoined != null) {
2596				conversation.getMucOptions().flagNoAutoPushConfiguration();
2597			}
2598			conversation.setHasMessagesLeftOnServer(false);
2599			fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2600
2601				private void join(Conversation conversation) {
2602					Account account = conversation.getAccount();
2603					final MucOptions mucOptions = conversation.getMucOptions();
2604
2605					if (mucOptions.nonanonymous() && !mucOptions.membersOnly() && !conversation.getBooleanAttribute("accept_non_anonymous", false)) {
2606					    synchronized (account.inProgressConferenceJoins) {
2607                            account.inProgressConferenceJoins.remove(conversation);
2608                        }
2609					    mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
2610					    updateConversationUi();
2611                        if (onConferenceJoined != null) {
2612                            onConferenceJoined.onConferenceJoined(conversation);
2613                        }
2614					    return;
2615                    }
2616
2617					final Jid joinJid = mucOptions.getSelf().getFullJid();
2618					Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
2619					PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
2620					packet.setTo(joinJid);
2621					Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2622					if (conversation.getMucOptions().getPassword() != null) {
2623						x.addChild("password").setContent(mucOptions.getPassword());
2624					}
2625
2626					if (mucOptions.mamSupport()) {
2627						// Use MAM instead of the limited muc history to get history
2628						x.addChild("history").setAttribute("maxchars", "0");
2629					} else {
2630						// Fallback to muc history
2631						x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
2632					}
2633					sendPresencePacket(account, packet);
2634					if (onConferenceJoined != null) {
2635						onConferenceJoined.onConferenceJoined(conversation);
2636					}
2637					if (!joinJid.equals(conversation.getJid())) {
2638						conversation.setContactJid(joinJid);
2639						databaseBackend.updateConversation(conversation);
2640					}
2641
2642					if (mucOptions.mamSupport()) {
2643						getMessageArchiveService().catchupMUC(conversation);
2644					}
2645					if (mucOptions.isPrivateAndNonAnonymous()) {
2646						fetchConferenceMembers(conversation);
2647						if (followedInvite && conversation.getBookmark() == null) {
2648							saveConversationAsBookmark(conversation, null);
2649						}
2650					}
2651					if (mucOptions.push()) {
2652					    enableMucPush(conversation);
2653                    }
2654					synchronized (account.inProgressConferenceJoins) {
2655                        account.inProgressConferenceJoins.remove(conversation);
2656                        sendUnsentMessages(conversation);
2657                    }
2658				}
2659
2660				@Override
2661				public void onConferenceConfigurationFetched(Conversation conversation) {
2662				    if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2663				        Log.d(Config.LOGTAG,account.getJid().asBareJid()+": conversation ("+conversation.getJid()+") got archived before IQ result");
2664				        return;
2665                    }
2666					join(conversation);
2667				}
2668
2669				@Override
2670				public void onFetchFailed(final Conversation conversation, Element error) {
2671                    if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2672                        Log.d(Config.LOGTAG,account.getJid().asBareJid()+": conversation ("+conversation.getJid()+") got archived before IQ result");
2673
2674                        return;
2675                    }
2676					if (error != null && "remote-server-not-found".equals(error.getName())) {
2677					    synchronized (account.inProgressConferenceJoins) {
2678                            account.inProgressConferenceJoins.remove(conversation);
2679                        }
2680						conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2681						updateConversationUi();
2682					} else {
2683						join(conversation);
2684						fetchConferenceConfiguration(conversation);
2685					}
2686				}
2687			});
2688			updateConversationUi();
2689		} else {
2690		    synchronized (account.pendingConferenceJoins) {
2691                account.pendingConferenceJoins.add(conversation);
2692            }
2693			conversation.resetMucOptions();
2694			conversation.setHasMessagesLeftOnServer(false);
2695			updateConversationUi();
2696		}
2697	}
2698
2699	private void enableDirectMucPush(final Conversation conversation) {
2700        final Account account = conversation.getAccount();
2701        final Jid room = conversation.getJid().asBareJid();
2702        final IqPacket enable = mIqGenerator.enablePush(conversation.getAccount().getJid(), conversation.getUuid(), null);
2703        enable.setTo(room);
2704        sendIqPacket(account, enable, (a, response) -> {
2705            if (response.getType() == IqPacket.TYPE.RESULT) {
2706                Log.d(Config.LOGTAG,a.getJid().asBareJid()+": enabled direct push for muc "+room);
2707            } else if (response.getType() == IqPacket.TYPE.ERROR) {
2708                Log.d(Config.LOGTAG,a.getJid().asBareJid()+": unable to enable direct push for muc "+room+" "+response.getError());
2709            }
2710        });
2711    }
2712
2713	private void enableMucPush(final Conversation conversation) {
2714	    enableDirectMucPush(conversation);
2715        mPushManagementService.registerPushTokenOnServer(conversation);
2716    }
2717
2718    private void disableDirectMucPush(final Conversation conversation) {
2719        final Account account = conversation.getAccount();
2720        final Jid room = conversation.getJid().asBareJid();
2721        final IqPacket disable = mIqGenerator.disablePush(conversation.getAccount().getJid(), conversation.getUuid());
2722        disable.setTo(room);
2723        sendIqPacket(account, disable, (a, response) -> {
2724            if (response.getType() == IqPacket.TYPE.RESULT) {
2725                Log.d(Config.LOGTAG,a.getJid().asBareJid()+": disabled direct push for muc "+room);
2726            } else if (response.getType() == IqPacket.TYPE.ERROR) {
2727                Log.d(Config.LOGTAG,a.getJid().asBareJid()+": unable to disable direct push for muc "+room+" "+response.getError());
2728            }
2729        });
2730    }
2731
2732	private void fetchConferenceMembers(final Conversation conversation) {
2733		final Account account = conversation.getAccount();
2734		final AxolotlService axolotlService = account.getAxolotlService();
2735		final String[] affiliations = {"member", "admin", "owner"};
2736		OnIqPacketReceived callback = new OnIqPacketReceived() {
2737
2738			private int i = 0;
2739			private boolean success = true;
2740
2741			@Override
2742			public void onIqPacketReceived(Account account, IqPacket packet) {
2743				final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
2744				Element query = packet.query("http://jabber.org/protocol/muc#admin");
2745				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2746					for (Element child : query.getChildren()) {
2747						if ("item".equals(child.getName())) {
2748							MucOptions.User user = AbstractParser.parseItem(conversation, child);
2749							if (!user.realJidMatchesAccount()) {
2750								boolean isNew = conversation.getMucOptions().updateUser(user);
2751								Contact contact = user.getContact();
2752								if (omemoEnabled
2753										&& isNew
2754										&& user.getRealJid() != null
2755										&& (contact == null || !contact.mutualPresenceSubscription())
2756										&& axolotlService.hasEmptyDeviceList(user.getRealJid())) {
2757									axolotlService.fetchDeviceIds(user.getRealJid());
2758								}
2759							}
2760						}
2761					}
2762				} else {
2763					success = false;
2764					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
2765				}
2766				++i;
2767				if (i >= affiliations.length) {
2768					List<Jid> members = conversation.getMucOptions().getMembers(true);
2769					if (success) {
2770						List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
2771						boolean changed = false;
2772						for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
2773							Jid jid = iterator.next();
2774							if (!members.contains(jid) && !members.contains(Jid.ofDomain(jid.getDomain()))) {
2775								iterator.remove();
2776								Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
2777								changed = true;
2778							}
2779						}
2780						if (changed) {
2781							conversation.setAcceptedCryptoTargets(cryptoTargets);
2782							updateConversation(conversation);
2783						}
2784					}
2785					getAvatarService().clear(conversation);
2786					updateMucRosterUi();
2787					updateConversationUi();
2788				}
2789			}
2790		};
2791		for (String affiliation : affiliations) {
2792			sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2793		}
2794		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
2795	}
2796
2797	public void providePasswordForMuc(Conversation conversation, String password) {
2798		if (conversation.getMode() == Conversation.MODE_MULTI) {
2799			conversation.getMucOptions().setPassword(password);
2800			if (conversation.getBookmark() != null) {
2801			    final Bookmark bookmark = conversation.getBookmark();
2802				if (synchronizeWithBookmarks()) {
2803					bookmark.setAutojoin(true);
2804				}
2805				createBookmark(conversation.getAccount(), bookmark);
2806			}
2807			updateConversation(conversation);
2808			joinMuc(conversation);
2809		}
2810	}
2811
2812	private boolean hasEnabledAccounts() {
2813	    if (this.accounts == null) {
2814	        return false;
2815	    }
2816	    for (Account account : this.accounts) {
2817	        if (account.isEnabled()) {
2818	            return true;
2819	        }
2820	    }
2821	    return false;
2822	}
2823
2824
2825	public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
2826        getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
2827    }
2828
2829    public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2830        getAttachments(account.getUuid(),jid.asBareJid(),limit, onMediaLoaded);
2831    }
2832
2833
2834	public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2835        new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
2836    }
2837
2838	public void persistSelfNick(MucOptions.User self) {
2839		final Conversation conversation = self.getConversation();
2840		final boolean tookProposedNickFromBookmark = conversation.getMucOptions().isTookProposedNickFromBookmark();
2841		Jid full = self.getFullJid();
2842		if (!full.equals(conversation.getJid())) {
2843			Log.d(Config.LOGTAG, "nick changed. updating");
2844			conversation.setContactJid(full);
2845			databaseBackend.updateConversation(conversation);
2846		}
2847
2848		final Bookmark bookmark = conversation.getBookmark();
2849		final String bookmarkedNick = bookmark == null ? null : bookmark.getNick();
2850        if (bookmark != null && (tookProposedNickFromBookmark || TextUtils.isEmpty(bookmarkedNick)) && !full.getResource().equals(bookmarkedNick)) {
2851            final Account account = conversation.getAccount();
2852            final String defaultNick = MucOptions.defaultNick(account);
2853            if (TextUtils.isEmpty(bookmarkedNick) && full.getResource().equals(defaultNick)) {
2854                Log.d(Config.LOGTAG,account.getJid().asBareJid()+": do not overwrite empty bookmark nick with default nick for "+conversation.getJid().asBareJid());
2855                return;
2856            }
2857            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persist nick '" + full.getResource() + "' into bookmark for " + conversation.getJid().asBareJid());
2858            bookmark.setNick(full.getResource());
2859            createBookmark(bookmark.getAccount(), bookmark);
2860        }
2861	}
2862
2863	public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2864		final MucOptions options = conversation.getMucOptions();
2865		final Jid joinJid = options.createJoinJid(nick);
2866		if (joinJid == null) {
2867			return false;
2868		}
2869		if (options.online()) {
2870			Account account = conversation.getAccount();
2871			options.setOnRenameListener(new OnRenameListener() {
2872
2873				@Override
2874				public void onSuccess() {
2875					callback.success(conversation);
2876				}
2877
2878				@Override
2879				public void onFailure() {
2880					callback.error(R.string.nick_in_use, conversation);
2881				}
2882			});
2883
2884            final PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous());
2885            packet.setTo(joinJid);
2886			sendPresencePacket(account, packet);
2887		} else {
2888			conversation.setContactJid(joinJid);
2889			databaseBackend.updateConversation(conversation);
2890			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2891				Bookmark bookmark = conversation.getBookmark();
2892				if (bookmark != null) {
2893					bookmark.setNick(nick);
2894					createBookmark(bookmark.getAccount(), bookmark);
2895				}
2896				joinMuc(conversation);
2897			}
2898		}
2899		return true;
2900	}
2901
2902	public void leaveMuc(Conversation conversation) {
2903		leaveMuc(conversation, false);
2904	}
2905
2906	private void leaveMuc(Conversation conversation, boolean now) {
2907		final Account account = conversation.getAccount();
2908		synchronized (account.pendingConferenceJoins) {
2909            account.pendingConferenceJoins.remove(conversation);
2910        }
2911        synchronized (account.pendingConferenceLeaves) {
2912            account.pendingConferenceLeaves.remove(conversation);
2913        }
2914		if (account.getStatus() == Account.State.ONLINE || now) {
2915			sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
2916			conversation.getMucOptions().setOffline();
2917			Bookmark bookmark = conversation.getBookmark();
2918			if (bookmark != null) {
2919				bookmark.setConversation(null);
2920			}
2921			Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
2922		} else {
2923		    synchronized (account.pendingConferenceLeaves) {
2924                account.pendingConferenceLeaves.add(conversation);
2925            }
2926		}
2927	}
2928
2929	public String findConferenceServer(final Account account) {
2930		String server;
2931		if (account.getXmppConnection() != null) {
2932			server = account.getXmppConnection().getMucServer();
2933			if (server != null) {
2934				return server;
2935			}
2936		}
2937		for (Account other : getAccounts()) {
2938			if (other != account && other.getXmppConnection() != null) {
2939				server = other.getXmppConnection().getMucServer();
2940				if (server != null) {
2941					return server;
2942				}
2943			}
2944		}
2945		return null;
2946	}
2947
2948
2949	public void createPublicChannel(final Account account, final String name, final Jid address, final UiCallback<Conversation> callback) {
2950        joinMuc(findOrCreateConversation(account, address, true, false, true), conversation -> {
2951            final Bundle configuration = IqGenerator.defaultChannelConfiguration();
2952            if (!TextUtils.isEmpty(name)) {
2953                configuration.putString("muc#roomconfig_roomname", name);
2954            }
2955            pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
2956                @Override
2957                public void onPushSucceeded() {
2958                    saveConversationAsBookmark(conversation, name);
2959                    callback.success(conversation);
2960                }
2961
2962                @Override
2963                public void onPushFailed() {
2964                    if (conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2965                        callback.error(R.string.unable_to_set_channel_configuration, conversation);
2966                    } else {
2967                        callback.error(R.string.joined_an_existing_channel, conversation);
2968                    }
2969                }
2970            });
2971        });
2972    }
2973
2974	public boolean createAdhocConference(final Account account,
2975	                                     final String name,
2976	                                     final Iterable<Jid> jids,
2977	                                     final UiCallback<Conversation> callback) {
2978		Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2979		if (account.getStatus() == Account.State.ONLINE) {
2980			try {
2981				String server = findConferenceServer(account);
2982				if (server == null) {
2983					if (callback != null) {
2984						callback.error(R.string.no_conference_server_found, null);
2985					}
2986					return false;
2987				}
2988				final Jid jid = Jid.of(CryptoHelper.pronounceable(getRNG()), server, null);
2989				final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
2990				joinMuc(conversation, new OnConferenceJoined() {
2991					@Override
2992					public void onConferenceJoined(final Conversation conversation) {
2993						final Bundle configuration = IqGenerator.defaultGroupChatConfiguration();
2994						if (!TextUtils.isEmpty(name)) {
2995							configuration.putString("muc#roomconfig_roomname", name);
2996						}
2997						pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
2998							@Override
2999							public void onPushSucceeded() {
3000								for (Jid invite : jids) {
3001									invite(conversation, invite);
3002								}
3003								for(String resource : account.getSelfContact().getPresences().toResourceArray()) {
3004								    Jid other = account.getJid().withResource(resource);
3005								    Log.d(Config.LOGTAG,account.getJid().asBareJid()+": sending direct invite to "+other);
3006								    directInvite(conversation, other);
3007                                }
3008								saveConversationAsBookmark(conversation, name);
3009								if (callback != null) {
3010									callback.success(conversation);
3011								}
3012							}
3013
3014							@Override
3015							public void onPushFailed() {
3016								archiveConversation(conversation);
3017								if (callback != null) {
3018									callback.error(R.string.conference_creation_failed, conversation);
3019								}
3020							}
3021						});
3022					}
3023				});
3024				return true;
3025			} catch (IllegalArgumentException e) {
3026				if (callback != null) {
3027					callback.error(R.string.conference_creation_failed, null);
3028				}
3029				return false;
3030			}
3031		} else {
3032			if (callback != null) {
3033				callback.error(R.string.not_connected_try_again, null);
3034			}
3035			return false;
3036		}
3037	}
3038
3039	public void fetchConferenceConfiguration(final Conversation conversation) {
3040		fetchConferenceConfiguration(conversation, null);
3041	}
3042
3043	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
3044		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3045		request.setTo(conversation.getJid().asBareJid());
3046		request.query("http://jabber.org/protocol/disco#info");
3047		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3048			@Override
3049			public void onIqPacketReceived(Account account, IqPacket packet) {
3050				if (packet.getType() == IqPacket.TYPE.RESULT) {
3051                    final MucOptions mucOptions = conversation.getMucOptions();
3052                    final Bookmark bookmark = conversation.getBookmark();
3053                    final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
3054
3055                    if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
3056                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
3057                        updateConversation(conversation);
3058                    }
3059
3060                    if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
3061                        if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
3062                            createBookmark(account, bookmark);
3063                        }
3064                    }
3065
3066
3067                    if (callback != null) {
3068                        callback.onConferenceConfigurationFetched(conversation);
3069                    }
3070
3071
3072                    updateConversationUi();
3073                } else if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
3074                    Log.d(Config.LOGTAG,account.getJid().asBareJid()+": received timeout waiting for conference configuration fetch");
3075				} else {
3076					if (callback != null) {
3077						callback.onFetchFailed(conversation, packet.getError());
3078					}
3079				}
3080			}
3081		});
3082	}
3083
3084	public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
3085		pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
3086	}
3087
3088	public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
3089        Log.d(Config.LOGTAG,"pushing node configuration");
3090		sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
3091			@Override
3092			public void onIqPacketReceived(Account account, IqPacket packet) {
3093				if (packet.getType() == IqPacket.TYPE.RESULT) {
3094					Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
3095					Element configuration = pubsub == null ? null : pubsub.findChild("configure");
3096					Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
3097					if (x != null) {
3098						Data data = Data.parse(x);
3099						data.submit(options);
3100						sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
3101							@Override
3102							public void onIqPacketReceived(Account account, IqPacket packet) {
3103								if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
3104									Log.d(Config.LOGTAG,account.getJid().asBareJid()+": successfully changed node configuration for node "+node);
3105									callback.onPushSucceeded();
3106								} else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3107									callback.onPushFailed();
3108								}
3109							}
3110						});
3111					} else if (callback != null) {
3112						callback.onPushFailed();
3113					}
3114				} else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3115					callback.onPushFailed();
3116				}
3117			}
3118		});
3119	}
3120
3121	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
3122	    if (options.getString("muc#roomconfig_whois","moderators").equals("anyone")) {
3123	        conversation.setAttribute("accept_non_anonymous",true);
3124            updateConversation(conversation);
3125        }
3126		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3127		request.setTo(conversation.getJid().asBareJid());
3128		request.query("http://jabber.org/protocol/muc#owner");
3129		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3130			@Override
3131			public void onIqPacketReceived(Account account, IqPacket packet) {
3132				if (packet.getType() == IqPacket.TYPE.RESULT) {
3133					Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
3134					data.submit(options);
3135					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3136					set.setTo(conversation.getJid().asBareJid());
3137					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
3138					sendIqPacket(account, set, new OnIqPacketReceived() {
3139						@Override
3140						public void onIqPacketReceived(Account account, IqPacket packet) {
3141							if (callback != null) {
3142								if (packet.getType() == IqPacket.TYPE.RESULT) {
3143									callback.onPushSucceeded();
3144								} else {
3145									callback.onPushFailed();
3146								}
3147							}
3148						}
3149					});
3150				} else {
3151					if (callback != null) {
3152						callback.onPushFailed();
3153					}
3154				}
3155			}
3156		});
3157	}
3158
3159	public void pushSubjectToConference(final Conversation conference, final String subject) {
3160		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
3161		this.sendMessagePacket(conference.getAccount(), packet);
3162	}
3163
3164	public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
3165		final Jid jid = user.asBareJid();
3166		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
3167		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
3168			@Override
3169			public void onIqPacketReceived(Account account, IqPacket packet) {
3170				if (packet.getType() == IqPacket.TYPE.RESULT) {
3171					conference.getMucOptions().changeAffiliation(jid, affiliation);
3172					getAvatarService().clear(conference);
3173					callback.onAffiliationChangedSuccessful(jid);
3174				} else {
3175					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
3176				}
3177			}
3178		});
3179	}
3180
3181	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
3182		List<Jid> jids = new ArrayList<>();
3183		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
3184			if (user.getAffiliation() == before && user.getRealJid() != null) {
3185				jids.add(user.getRealJid());
3186			}
3187		}
3188		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
3189		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
3190	}
3191
3192	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) {
3193		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
3194		Log.d(Config.LOGTAG, request.toString());
3195		sendIqPacket(conference.getAccount(), request, (account, packet) -> {
3196            if (packet.getType() != IqPacket.TYPE.RESULT) {
3197                Log.d(Config.LOGTAG,account.getJid().asBareJid()+" unable to change role of "+nick);
3198            }
3199        });
3200	}
3201
3202    public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
3203        IqPacket request = new IqPacket(IqPacket.TYPE.SET);
3204        request.setTo(conversation.getJid().asBareJid());
3205        request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
3206        sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3207            @Override
3208            public void onIqPacketReceived(Account account, IqPacket packet) {
3209                if (packet.getType() == IqPacket.TYPE.RESULT) {
3210                    if (callback != null) {
3211                        callback.onRoomDestroySucceeded();
3212                    }
3213                } else if (packet.getType() == IqPacket.TYPE.ERROR) {
3214                    if (callback != null) {
3215                        callback.onRoomDestroyFailed();
3216                    }
3217                }
3218            }
3219        });
3220    }
3221
3222	private void disconnect(Account account, boolean force) {
3223		if ((account.getStatus() == Account.State.ONLINE)
3224				|| (account.getStatus() == Account.State.DISABLED)) {
3225			final XmppConnection connection = account.getXmppConnection();
3226			if (!force) {
3227				List<Conversation> conversations = getConversations();
3228				for (Conversation conversation : conversations) {
3229					if (conversation.getAccount() == account) {
3230						if (conversation.getMode() == Conversation.MODE_MULTI) {
3231							leaveMuc(conversation, true);
3232						}
3233					}
3234				}
3235				sendOfflinePresence(account);
3236			}
3237			connection.disconnect(force);
3238		}
3239	}
3240
3241	@Override
3242	public IBinder onBind(Intent intent) {
3243		return mBinder;
3244	}
3245
3246	public void updateMessage(Message message) {
3247		updateMessage(message, true);
3248	}
3249
3250	public void updateMessage(Message message, boolean includeBody) {
3251		databaseBackend.updateMessage(message, includeBody);
3252		updateConversationUi();
3253	}
3254
3255	public void updateMessage(Message message, String uuid) {
3256		if (!databaseBackend.updateMessage(message, uuid)) {
3257            Log.e(Config.LOGTAG,"error updated message in DB after edit");
3258        }
3259		updateConversationUi();
3260	}
3261
3262	protected void syncDirtyContacts(Account account) {
3263		for (Contact contact : account.getRoster().getContacts()) {
3264			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
3265				pushContactToServer(contact);
3266			}
3267			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
3268				deleteContactOnServer(contact);
3269			}
3270		}
3271	}
3272
3273	public void createContact(Contact contact, boolean autoGrant) {
3274		if (autoGrant) {
3275			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
3276			contact.setOption(Contact.Options.ASKING);
3277		}
3278		pushContactToServer(contact);
3279	}
3280
3281	public void pushContactToServer(final Contact contact) {
3282		contact.resetOption(Contact.Options.DIRTY_DELETE);
3283		contact.setOption(Contact.Options.DIRTY_PUSH);
3284		final Account account = contact.getAccount();
3285		if (account.getStatus() == Account.State.ONLINE) {
3286			final boolean ask = contact.getOption(Contact.Options.ASKING);
3287			final boolean sendUpdates = contact
3288					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
3289					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
3290			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3291			iq.query(Namespace.ROSTER).addChild(contact.asElement());
3292			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3293			if (sendUpdates) {
3294				sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
3295			}
3296			if (ask) {
3297				sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact));
3298			}
3299		} else {
3300			syncRoster(contact.getAccount());
3301		}
3302	}
3303
3304	public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
3305		new Thread(() -> {
3306			final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3307			final int size = Config.AVATAR_SIZE;
3308			final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3309			if (avatar != null) {
3310				if (!getFileBackend().save(avatar)) {
3311					callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3312					return;
3313				}
3314				avatar.owner = conversation.getJid().asBareJid();
3315				publishMucAvatar(conversation, avatar, callback);
3316			} else {
3317				callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3318			}
3319		}).start();
3320	}
3321
3322	public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
3323		new Thread(() -> {
3324			final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3325			final int size = Config.AVATAR_SIZE;
3326			final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3327			if (avatar != null) {
3328				if (!getFileBackend().save(avatar)) {
3329					Log.d(Config.LOGTAG,"unable to save vcard");
3330					callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3331					return;
3332				}
3333				publishAvatar(account, avatar, callback);
3334			} else {
3335				callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3336			}
3337		}).start();
3338
3339	}
3340
3341	private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
3342		final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
3343		sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
3344			boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
3345			if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
3346				Element vcard = response.findChild("vCard", "vcard-temp");
3347				if (vcard == null) {
3348					vcard = new Element("vCard", "vcard-temp");
3349				}
3350				Element photo = vcard.findChild("PHOTO");
3351				if (photo == null) {
3352					photo = vcard.addChild("PHOTO");
3353				}
3354				photo.clearChildren();
3355				photo.addChild("TYPE").setContent(avatar.type);
3356				photo.addChild("BINVAL").setContent(avatar.image);
3357				IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3358				publication.setTo(conversation.getJid().asBareJid());
3359				publication.addChild(vcard);
3360				sendIqPacket(account, publication, (a1, publicationResponse) -> {
3361					if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3362						callback.onAvatarPublicationSucceeded();
3363					} else {
3364						Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getError());
3365						callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3366					}
3367				});
3368			} else {
3369				Log.d(Config.LOGTAG, "failed to request vcard " + response.toString());
3370				callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
3371			}
3372		});
3373	}
3374
3375    public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
3376        final Bundle options;
3377        if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
3378            options = PublishOptions.openAccess();
3379        } else {
3380            options = null;
3381        }
3382        publishAvatar(account, avatar, options, true, callback);
3383    }
3384
3385	public void publishAvatar(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3386        Log.d(Config.LOGTAG,account.getJid().asBareJid()+": publishing avatar. options="+options);
3387		IqPacket packet = this.mIqGenerator.publishAvatar(avatar, options);
3388		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3389
3390			@Override
3391			public void onIqPacketReceived(Account account, IqPacket result) {
3392				if (result.getType() == IqPacket.TYPE.RESULT) {
3393                    publishAvatarMetadata(account, avatar, options,true, callback);
3394                } else if (retry && PublishOptions.preconditionNotMet(result)) {
3395				    pushNodeConfiguration(account, "urn:xmpp:avatar:data", options, new OnConfigurationPushed() {
3396                        @Override
3397                        public void onPushSucceeded() {
3398                            Log.d(Config.LOGTAG,account.getJid().asBareJid()+": changed node configuration for avatar node");
3399                            publishAvatar(account, avatar, options, false, callback);
3400                        }
3401
3402                        @Override
3403                        public void onPushFailed() {
3404                            Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to change node configuration for avatar node");
3405                            publishAvatar(account, avatar, null, false, callback);
3406                        }
3407                    });
3408				} else {
3409					Element error = result.findChild("error");
3410					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
3411					if (callback != null) {
3412						callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3413					}
3414				}
3415			}
3416		});
3417	}
3418
3419	public void publishAvatarMetadata(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3420        final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
3421        sendIqPacket(account, packet, new OnIqPacketReceived() {
3422            @Override
3423            public void onIqPacketReceived(Account account, IqPacket result) {
3424                if (result.getType() == IqPacket.TYPE.RESULT) {
3425                    if (account.setAvatar(avatar.getFilename())) {
3426                        getAvatarService().clear(account);
3427                        databaseBackend.updateAccount(account);
3428                        notifyAccountAvatarHasChanged(account);
3429                    }
3430                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
3431                    if (callback != null) {
3432                        callback.onAvatarPublicationSucceeded();
3433                    }
3434                } else if (retry && PublishOptions.preconditionNotMet(result)) {
3435                    pushNodeConfiguration(account, "urn:xmpp:avatar:metadata", options, new OnConfigurationPushed() {
3436                        @Override
3437                        public void onPushSucceeded() {
3438                            Log.d(Config.LOGTAG,account.getJid().asBareJid()+": changed node configuration for avatar meta data node");
3439                            publishAvatarMetadata(account, avatar, options,false, callback);
3440                        }
3441
3442                        @Override
3443                        public void onPushFailed() {
3444                            Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to change node configuration for avatar meta data node");
3445                            publishAvatarMetadata(account, avatar,  null,false, callback);
3446                        }
3447                    });
3448                } else {
3449                    if (callback != null) {
3450                        callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3451                    }
3452                }
3453            }
3454        });
3455    }
3456
3457	public void republishAvatarIfNeeded(Account account) {
3458		if (account.getAxolotlService().isPepBroken()) {
3459			Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
3460			return;
3461		}
3462		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3463		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3464
3465			private Avatar parseAvatar(IqPacket packet) {
3466				Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3467				if (pubsub != null) {
3468					Element items = pubsub.findChild("items");
3469					if (items != null) {
3470						return Avatar.parseMetadata(items);
3471					}
3472				}
3473				return null;
3474			}
3475
3476			private boolean errorIsItemNotFound(IqPacket packet) {
3477				Element error = packet.findChild("error");
3478				return packet.getType() == IqPacket.TYPE.ERROR
3479						&& error != null
3480						&& error.hasChild("item-not-found");
3481			}
3482
3483			@Override
3484			public void onIqPacketReceived(Account account, IqPacket packet) {
3485				if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
3486					Avatar serverAvatar = parseAvatar(packet);
3487					if (serverAvatar == null && account.getAvatar() != null) {
3488						Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
3489						if (avatar != null) {
3490							Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
3491							publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
3492						} else {
3493							Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
3494						}
3495					}
3496				}
3497			}
3498		});
3499	}
3500
3501	public void fetchAvatar(Account account, Avatar avatar) {
3502		fetchAvatar(account, avatar, null);
3503	}
3504
3505	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3506		final String KEY = generateFetchKey(account, avatar);
3507		synchronized (this.mInProgressAvatarFetches) {
3508		    if (mInProgressAvatarFetches.add(KEY)) {
3509                switch (avatar.origin) {
3510                    case PEP:
3511                        this.mInProgressAvatarFetches.add(KEY);
3512                        fetchAvatarPep(account, avatar, callback);
3513                        break;
3514                    case VCARD:
3515                        this.mInProgressAvatarFetches.add(KEY);
3516                        fetchAvatarVcard(account, avatar, callback);
3517                        break;
3518                }
3519            } else if (avatar.origin == Avatar.Origin.PEP) {
3520		        mOmittedPepAvatarFetches.add(KEY);
3521            } else {
3522		        Log.d(Config.LOGTAG,account.getJid().asBareJid()+": already fetching "+avatar.origin+" avatar for "+avatar.owner);
3523            }
3524		}
3525	}
3526
3527	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3528		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
3529		sendIqPacket(account, packet, (a, result) -> {
3530			synchronized (mInProgressAvatarFetches) {
3531				mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
3532			}
3533			final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
3534			if (result.getType() == IqPacket.TYPE.RESULT) {
3535				avatar.image = mIqParser.avatarData(result);
3536				if (avatar.image != null) {
3537					if (getFileBackend().save(avatar)) {
3538						if (a.getJid().asBareJid().equals(avatar.owner)) {
3539							if (a.setAvatar(avatar.getFilename())) {
3540								databaseBackend.updateAccount(a);
3541							}
3542							getAvatarService().clear(a);
3543							updateConversationUi();
3544							updateAccountUi();
3545						} else {
3546							Contact contact = a.getRoster().getContact(avatar.owner);
3547							if (contact.setAvatar(avatar)) {
3548								syncRoster(account);
3549								getAvatarService().clear(contact);
3550								updateConversationUi();
3551								updateRosterUi();
3552							}
3553						}
3554						if (callback != null) {
3555							callback.success(avatar);
3556						}
3557						Log.d(Config.LOGTAG, a.getJid().asBareJid()
3558								+ ": successfully fetched pep avatar for " + avatar.owner);
3559						return;
3560					}
3561				} else {
3562
3563					Log.d(Config.LOGTAG, ERROR + "(parsing error)");
3564				}
3565			} else {
3566				Element error = result.findChild("error");
3567				if (error == null) {
3568					Log.d(Config.LOGTAG, ERROR + "(server error)");
3569				} else {
3570					Log.d(Config.LOGTAG, ERROR + error.toString());
3571				}
3572			}
3573			if (callback != null) {
3574				callback.error(0, null);
3575			}
3576
3577		});
3578	}
3579
3580	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3581		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
3582		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3583			@Override
3584			public void onIqPacketReceived(Account account, IqPacket packet) {
3585			    final boolean previouslyOmittedPepFetch;
3586				synchronized (mInProgressAvatarFetches) {
3587				    final String KEY = generateFetchKey(account, avatar);
3588					mInProgressAvatarFetches.remove(KEY);
3589					previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
3590				}
3591				if (packet.getType() == IqPacket.TYPE.RESULT) {
3592					Element vCard = packet.findChild("vCard", "vcard-temp");
3593					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
3594					String image = photo != null ? photo.findChildContent("BINVAL") : null;
3595					if (image != null) {
3596						avatar.image = image;
3597						if (getFileBackend().save(avatar)) {
3598							Log.d(Config.LOGTAG, account.getJid().asBareJid()
3599									+ ": successfully fetched vCard avatar for " + avatar.owner+" omittedPep="+previouslyOmittedPepFetch);
3600							if (avatar.owner.isBareJid()) {
3601								if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
3602									Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
3603									account.setAvatar(avatar.getFilename());
3604									databaseBackend.updateAccount(account);
3605									getAvatarService().clear(account);
3606									updateAccountUi();
3607								} else {
3608									Contact contact = account.getRoster().getContact(avatar.owner);
3609									if (contact.setAvatar(avatar, previouslyOmittedPepFetch)) {
3610										syncRoster(account);
3611										getAvatarService().clear(contact);
3612										updateRosterUi();
3613									}
3614								}
3615								updateConversationUi();
3616							} else {
3617								Conversation conversation = find(account, avatar.owner.asBareJid());
3618								if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
3619									MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
3620									if (user != null) {
3621										if (user.setAvatar(avatar)) {
3622											getAvatarService().clear(user);
3623											updateConversationUi();
3624											updateMucRosterUi();
3625										}
3626										if (user.getRealJid() != null) {
3627										    Contact contact = account.getRoster().getContact(user.getRealJid());
3628										    if (contact.setAvatar(avatar)) {
3629                                                syncRoster(account);
3630                                                getAvatarService().clear(contact);
3631                                                updateRosterUi();
3632                                            }
3633                                        }
3634									}
3635								}
3636							}
3637						}
3638					}
3639				}
3640			}
3641		});
3642	}
3643
3644	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
3645		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3646		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3647
3648			@Override
3649			public void onIqPacketReceived(Account account, IqPacket packet) {
3650				if (packet.getType() == IqPacket.TYPE.RESULT) {
3651					Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3652					if (pubsub != null) {
3653						Element items = pubsub.findChild("items");
3654						if (items != null) {
3655							Avatar avatar = Avatar.parseMetadata(items);
3656							if (avatar != null) {
3657								avatar.owner = account.getJid().asBareJid();
3658								if (fileBackend.isAvatarCached(avatar)) {
3659									if (account.setAvatar(avatar.getFilename())) {
3660										databaseBackend.updateAccount(account);
3661									}
3662									getAvatarService().clear(account);
3663									callback.success(avatar);
3664								} else {
3665									fetchAvatarPep(account, avatar, callback);
3666								}
3667								return;
3668							}
3669						}
3670					}
3671				}
3672				callback.error(0, null);
3673			}
3674		});
3675	}
3676
3677	public void notifyAccountAvatarHasChanged(final Account account) {
3678	    final XmppConnection connection = account.getXmppConnection();
3679	    if (connection != null && connection.getFeatures().bookmarksConversion()) {
3680            Log.d(Config.LOGTAG,account.getJid().asBareJid()+": avatar changed. resending presence to online group chats");
3681            for(Conversation conversation : conversations) {
3682                if (conversation.getAccount() == account && conversation.getMode() == Conversational.MODE_MULTI) {
3683                    final MucOptions mucOptions = conversation.getMucOptions();
3684                    if (mucOptions.online()) {
3685                        PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous());
3686                        packet.setTo(mucOptions.getSelf().getFullJid());
3687                        connection.sendPresencePacket(packet);
3688                    }
3689                }
3690            }
3691        }
3692    }
3693
3694	public void deleteContactOnServer(Contact contact) {
3695		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
3696		contact.resetOption(Contact.Options.DIRTY_PUSH);
3697		contact.setOption(Contact.Options.DIRTY_DELETE);
3698		Account account = contact.getAccount();
3699		if (account.getStatus() == Account.State.ONLINE) {
3700			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3701			Element item = iq.query(Namespace.ROSTER).addChild("item");
3702			item.setAttribute("jid", contact.getJid().toString());
3703			item.setAttribute("subscription", "remove");
3704			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3705		}
3706	}
3707
3708	public void updateConversation(final Conversation conversation) {
3709		mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
3710	}
3711
3712	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
3713		synchronized (account) {
3714			XmppConnection connection = account.getXmppConnection();
3715			if (connection == null) {
3716				connection = createConnection(account);
3717				account.setXmppConnection(connection);
3718			}
3719			boolean hasInternet = hasInternetConnection();
3720			if (account.isEnabled() && hasInternet) {
3721				if (!force) {
3722					disconnect(account, false);
3723				}
3724				Thread thread = new Thread(connection);
3725				connection.setInteractive(interactive);
3726				connection.prepareNewConnection();
3727				connection.interrupt();
3728				thread.start();
3729				scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
3730			} else {
3731				disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
3732				account.getRoster().clearPresences();
3733				connection.resetEverything();
3734				final AxolotlService axolotlService = account.getAxolotlService();
3735				if (axolotlService != null) {
3736					axolotlService.resetBrokenness();
3737				}
3738				if (!hasInternet) {
3739					account.setStatus(Account.State.NO_INTERNET);
3740				}
3741			}
3742		}
3743	}
3744
3745	public void reconnectAccountInBackground(final Account account) {
3746		new Thread(() -> reconnectAccount(account, false, true)).start();
3747	}
3748
3749	public void invite(Conversation conversation, Jid contact) {
3750		Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
3751		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
3752		sendMessagePacket(conversation.getAccount(), packet);
3753	}
3754
3755	public void directInvite(Conversation conversation, Jid jid) {
3756		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
3757		sendMessagePacket(conversation.getAccount(), packet);
3758	}
3759
3760	public void resetSendingToWaiting(Account account) {
3761		for (Conversation conversation : getConversations()) {
3762			if (conversation.getAccount() == account) {
3763				conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
3764			}
3765		}
3766	}
3767
3768	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
3769		return markMessage(account, recipient, uuid, status, null);
3770	}
3771
3772	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
3773		if (uuid == null) {
3774			return null;
3775		}
3776		for (Conversation conversation : getConversations()) {
3777			if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
3778				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
3779				if (message != null) {
3780					markMessage(message, status, errorMessage);
3781				}
3782				return message;
3783			}
3784		}
3785		return null;
3786	}
3787
3788	public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) {
3789		if (uuid == null) {
3790			return false;
3791		} else {
3792			Message message = conversation.findSentMessageWithUuid(uuid);
3793			if (message != null) {
3794				if (message.getServerMsgId() == null) {
3795					message.setServerMsgId(serverMessageId);
3796				}
3797				markMessage(message, status);
3798				return true;
3799			} else {
3800				return false;
3801			}
3802		}
3803	}
3804
3805	public void markMessage(Message message, int status) {
3806		markMessage(message, status, null);
3807	}
3808
3809
3810	public void markMessage(Message message, int status, String errorMessage) {
3811		final int oldStatus = message.getStatus();
3812		if (status == Message.STATUS_SEND_FAILED && (oldStatus == Message.STATUS_SEND_RECEIVED || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
3813			return;
3814		}
3815		if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
3816			return;
3817		}
3818		message.setErrorMessage(errorMessage);
3819		message.setStatus(status);
3820		databaseBackend.updateMessage(message, false);
3821		updateConversationUi();
3822	}
3823
3824	private SharedPreferences getPreferences() {
3825		return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
3826	}
3827
3828	public long getAutomaticMessageDeletionDate() {
3829		final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
3830		return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
3831	}
3832
3833	public long getLongPreference(String name, @IntegerRes int res) {
3834		long defaultValue = getResources().getInteger(res);
3835		try {
3836			return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
3837		} catch (NumberFormatException e) {
3838			return defaultValue;
3839		}
3840	}
3841
3842	public boolean getBooleanPreference(String name, @BoolRes int res) {
3843		return getPreferences().getBoolean(name, getResources().getBoolean(res));
3844	}
3845
3846	public boolean confirmMessages() {
3847		return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
3848	}
3849
3850	public boolean allowMessageCorrection() {
3851		return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
3852	}
3853
3854	public boolean sendChatStates() {
3855		return getBooleanPreference("chat_states", R.bool.chat_states);
3856	}
3857
3858	private boolean synchronizeWithBookmarks() {
3859		return getBooleanPreference("autojoin", R.bool.autojoin);
3860	}
3861
3862	public boolean indicateReceived() {
3863		return getBooleanPreference("indicate_received", R.bool.indicate_received);
3864	}
3865
3866	public boolean useTorToConnect() {
3867		return QuickConversationsService.isConversations() && getBooleanPreference("use_tor", R.bool.use_tor);
3868	}
3869
3870	public boolean showExtendedConnectionOptions() {
3871		return QuickConversationsService.isConversations() && getBooleanPreference("show_connection_options", R.bool.show_connection_options);
3872	}
3873
3874	public boolean broadcastLastActivity() {
3875		return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
3876	}
3877
3878	public int unreadCount() {
3879		int count = 0;
3880		for (Conversation conversation : getConversations()) {
3881			count += conversation.unreadCount();
3882		}
3883		return count;
3884	}
3885
3886
3887	private <T> List<T> threadSafeList(Set<T> set) {
3888		synchronized (LISTENER_LOCK) {
3889			return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
3890		}
3891	}
3892
3893	public void showErrorToastInUi(int resId) {
3894		for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
3895			listener.onShowErrorToast(resId);
3896		}
3897	}
3898
3899	public void updateConversationUi() {
3900		for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
3901			listener.onConversationUpdate();
3902		}
3903	}
3904
3905	public void updateAccountUi() {
3906		for (OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
3907			listener.onAccountUpdate();
3908		}
3909	}
3910
3911	public void updateRosterUi() {
3912		for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
3913			listener.onRosterUpdate();
3914		}
3915	}
3916
3917	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3918		if (mOnCaptchaRequested.size() > 0) {
3919			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3920			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3921					(int) (captcha.getHeight() * metrics.scaledDensity), false);
3922			for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
3923				listener.onCaptchaRequested(account, id, data, scaled);
3924			}
3925			return true;
3926		}
3927		return false;
3928	}
3929
3930	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3931		for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
3932			listener.OnUpdateBlocklist(status);
3933		}
3934	}
3935
3936	public void updateMucRosterUi() {
3937		for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
3938			listener.onMucRosterUpdate();
3939		}
3940	}
3941
3942	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3943		for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
3944			listener.onKeyStatusUpdated(report);
3945		}
3946	}
3947
3948	public Account findAccountByJid(final Jid accountJid) {
3949		for (Account account : this.accounts) {
3950			if (account.getJid().asBareJid().equals(accountJid.asBareJid())) {
3951				return account;
3952			}
3953		}
3954		return null;
3955	}
3956
3957	public Account findAccountByUuid(final String uuid) {
3958		for(Account account : this.accounts) {
3959			if (account.getUuid().equals(uuid)) {
3960				return account;
3961			}
3962		}
3963		return null;
3964	}
3965
3966	public Conversation findConversationByUuid(String uuid) {
3967		for (Conversation conversation : getConversations()) {
3968			if (conversation.getUuid().equals(uuid)) {
3969				return conversation;
3970			}
3971		}
3972		return null;
3973	}
3974
3975	public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
3976		List<Conversation> findings = new ArrayList<>();
3977		for (Conversation c : getConversations()) {
3978			if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
3979				findings.add(c);
3980			}
3981		}
3982		return findings.size() == 1 ? findings.get(0) : null;
3983	}
3984
3985	public boolean markRead(final Conversation conversation, boolean dismiss) {
3986		return markRead(conversation, null, dismiss).size() > 0;
3987	}
3988
3989	public void markRead(final Conversation conversation) {
3990		markRead(conversation, null, true);
3991	}
3992
3993	public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
3994		if (dismiss) {
3995			mNotificationService.clear(conversation);
3996		}
3997		final List<Message> readMessages = conversation.markRead(upToUuid);
3998		if (readMessages.size() > 0) {
3999			Runnable runnable = () -> {
4000				for (Message message : readMessages) {
4001					databaseBackend.updateMessage(message, false);
4002				}
4003			};
4004			mDatabaseWriterExecutor.execute(runnable);
4005			updateUnreadCountBadge();
4006			return readMessages;
4007		} else {
4008			return readMessages;
4009		}
4010	}
4011
4012	public synchronized void updateUnreadCountBadge() {
4013		int count = unreadCount();
4014		if (unreadCount != count) {
4015			Log.d(Config.LOGTAG, "update unread count to " + count);
4016			if (count > 0) {
4017				ShortcutBadger.applyCount(getApplicationContext(), count);
4018			} else {
4019				ShortcutBadger.removeCount(getApplicationContext());
4020			}
4021			unreadCount = count;
4022		}
4023	}
4024
4025	public void sendReadMarker(final Conversation conversation, String upToUuid) {
4026		final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
4027		final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
4028		if (readMessages.size() > 0) {
4029			updateConversationUi();
4030		}
4031		final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
4032		if (confirmMessages()
4033				&& markable != null
4034				&& (markable.trusted() || isPrivateAndNonAnonymousMuc)
4035				&& markable.getRemoteMsgId() != null) {
4036			Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
4037			Account account = conversation.getAccount();
4038			final Jid to = markable.getCounterpart();
4039			final boolean groupChat = conversation.getMode() == Conversation.MODE_MULTI;
4040			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId(), markable.getCounterpart(), groupChat);
4041			this.sendMessagePacket(conversation.getAccount(), packet);
4042		}
4043	}
4044
4045	public SecureRandom getRNG() {
4046		return this.mRandom;
4047	}
4048
4049	public MemorizingTrustManager getMemorizingTrustManager() {
4050		return this.mMemorizingTrustManager;
4051	}
4052
4053	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
4054		this.mMemorizingTrustManager = trustManager;
4055	}
4056
4057	public void updateMemorizingTrustmanager() {
4058		final MemorizingTrustManager tm;
4059		final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
4060		if (dontTrustSystemCAs) {
4061			tm = new MemorizingTrustManager(getApplicationContext(), null);
4062		} else {
4063			tm = new MemorizingTrustManager(getApplicationContext());
4064		}
4065		setMemorizingTrustManager(tm);
4066	}
4067
4068	public LruCache<String, Bitmap> getBitmapCache() {
4069		return this.mBitmapCache;
4070	}
4071
4072	public Collection<String> getKnownHosts() {
4073		final Set<String> hosts = new HashSet<>();
4074		for (final Account account : getAccounts()) {
4075			hosts.add(account.getServer());
4076			for (final Contact contact : account.getRoster().getContacts()) {
4077				if (contact.showInRoster()) {
4078					final String server = contact.getServer();
4079					if (server != null) {
4080						hosts.add(server);
4081					}
4082				}
4083			}
4084		}
4085		if (Config.QUICKSY_DOMAIN != null) {
4086		    hosts.remove(Config.QUICKSY_DOMAIN); //we only want to show this when we type a e164 number
4087        }
4088		if (Config.DOMAIN_LOCK != null) {
4089			hosts.add(Config.DOMAIN_LOCK);
4090		}
4091		if (Config.MAGIC_CREATE_DOMAIN != null) {
4092			hosts.add(Config.MAGIC_CREATE_DOMAIN);
4093		}
4094		return hosts;
4095	}
4096
4097	public Collection<String> getKnownConferenceHosts() {
4098		final Set<String> mucServers = new HashSet<>();
4099		for (final Account account : accounts) {
4100			if (account.getXmppConnection() != null) {
4101				mucServers.addAll(account.getXmppConnection().getMucServers());
4102				for (Bookmark bookmark : account.getBookmarks()) {
4103					final Jid jid = bookmark.getJid();
4104					final String s = jid == null ? null : jid.getDomain();
4105					if (s != null) {
4106						mucServers.add(s);
4107					}
4108				}
4109			}
4110		}
4111		return mucServers;
4112	}
4113
4114	public void sendMessagePacket(Account account, MessagePacket packet) {
4115		XmppConnection connection = account.getXmppConnection();
4116		if (connection != null) {
4117			connection.sendMessagePacket(packet);
4118		}
4119	}
4120
4121	public void sendPresencePacket(Account account, PresencePacket packet) {
4122		XmppConnection connection = account.getXmppConnection();
4123		if (connection != null) {
4124			connection.sendPresencePacket(packet);
4125		}
4126	}
4127
4128	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
4129		final XmppConnection connection = account.getXmppConnection();
4130		if (connection != null) {
4131			IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
4132			connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
4133		}
4134	}
4135
4136	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
4137		final XmppConnection connection = account.getXmppConnection();
4138		if (connection != null) {
4139			connection.sendIqPacket(packet, callback);
4140		} else if (callback != null) {
4141		    callback.onIqPacketReceived(account,new IqPacket(IqPacket.TYPE.TIMEOUT));
4142        }
4143	}
4144
4145	public void sendPresence(final Account account) {
4146		sendPresence(account, checkListeners() && broadcastLastActivity());
4147	}
4148
4149	private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
4150		Presence.Status status;
4151		if (manuallyChangePresence()) {
4152			status = account.getPresenceStatus();
4153		} else {
4154			status = getTargetPresence();
4155		}
4156		final PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
4157		if (mLastActivity > 0 && includeIdleTimestamp) {
4158			long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
4159			packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
4160		}
4161		sendPresencePacket(account, packet);
4162	}
4163
4164	private void deactivateGracePeriod() {
4165		for (Account account : getAccounts()) {
4166			account.deactivateGracePeriod();
4167		}
4168	}
4169
4170	public void refreshAllPresences() {
4171		boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
4172		for (Account account : getAccounts()) {
4173			if (account.isEnabled()) {
4174				sendPresence(account, includeIdleTimestamp);
4175			}
4176		}
4177	}
4178
4179	private void refreshAllFcmTokens() {
4180		for (Account account : getAccounts()) {
4181			if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
4182				mPushManagementService.registerPushTokenOnServer(account);
4183				//TODO renew mucs
4184			}
4185		}
4186	}
4187
4188	private void sendOfflinePresence(final Account account) {
4189		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
4190		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
4191	}
4192
4193	public MessageGenerator getMessageGenerator() {
4194		return this.mMessageGenerator;
4195	}
4196
4197	public PresenceGenerator getPresenceGenerator() {
4198		return this.mPresenceGenerator;
4199	}
4200
4201	public IqGenerator getIqGenerator() {
4202		return this.mIqGenerator;
4203	}
4204
4205	public IqParser getIqParser() {
4206		return this.mIqParser;
4207	}
4208
4209	public JingleConnectionManager getJingleConnectionManager() {
4210		return this.mJingleConnectionManager;
4211	}
4212
4213	public MessageArchiveService getMessageArchiveService() {
4214		return this.mMessageArchiveService;
4215	}
4216
4217	public QuickConversationsService getQuickConversationsService() {
4218        return this.mQuickConversationsService;
4219    }
4220
4221	public List<Contact> findContacts(Jid jid, String accountJid) {
4222		ArrayList<Contact> contacts = new ArrayList<>();
4223		for (Account account : getAccounts()) {
4224			if ((account.isEnabled() || accountJid != null)
4225					&& (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
4226				Contact contact = account.getRoster().getContactFromContactList(jid);
4227				if (contact != null) {
4228					contacts.add(contact);
4229				}
4230			}
4231		}
4232		return contacts;
4233	}
4234
4235	public Conversation findFirstMuc(Jid jid) {
4236		for (Conversation conversation : getConversations()) {
4237			if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
4238				return conversation;
4239			}
4240		}
4241		return null;
4242	}
4243
4244	public NotificationService getNotificationService() {
4245		return this.mNotificationService;
4246	}
4247
4248	public HttpConnectionManager getHttpConnectionManager() {
4249		return this.mHttpConnectionManager;
4250	}
4251
4252	public void resendFailedMessages(final Message message) {
4253		final Collection<Message> messages = new ArrayList<>();
4254		Message current = message;
4255		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
4256			messages.add(current);
4257			if (current.mergeable(current.next())) {
4258				current = current.next();
4259			} else {
4260				break;
4261			}
4262		}
4263		for (final Message msg : messages) {
4264			msg.setTime(System.currentTimeMillis());
4265			markMessage(msg, Message.STATUS_WAITING);
4266			this.resendMessage(msg, false);
4267		}
4268		if (message.getConversation() instanceof Conversation) {
4269			((Conversation) message.getConversation()).sort();
4270		}
4271		updateConversationUi();
4272	}
4273
4274	public void clearConversationHistory(final Conversation conversation) {
4275		final long clearDate;
4276		final String reference;
4277		if (conversation.countMessages() > 0) {
4278			Message latestMessage = conversation.getLatestMessage();
4279			clearDate = latestMessage.getTimeSent() + 1000;
4280			reference = latestMessage.getServerMsgId();
4281		} else {
4282			clearDate = System.currentTimeMillis();
4283			reference = null;
4284		}
4285		conversation.clearMessages();
4286		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
4287		conversation.setLastClearHistory(clearDate, reference);
4288		Runnable runnable = () -> {
4289			databaseBackend.deleteMessagesInConversation(conversation);
4290			databaseBackend.updateConversation(conversation);
4291		};
4292		mDatabaseWriterExecutor.execute(runnable);
4293	}
4294
4295	public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
4296		if (blockable != null && blockable.getBlockedJid() != null) {
4297			final Jid jid = blockable.getBlockedJid();
4298			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), (a, response) -> {
4299                if (response.getType() == IqPacket.TYPE.RESULT) {
4300                    a.getBlocklist().add(jid);
4301                    updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
4302                }
4303            });
4304			if (blockable.getBlockedJid().isFullJid()) {
4305			    return false;
4306            } else if (removeBlockedConversations(blockable.getAccount(), jid)) {
4307				updateConversationUi();
4308				return true;
4309			} else {
4310				return false;
4311			}
4312		} else {
4313			return false;
4314		}
4315	}
4316
4317	public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
4318		boolean removed = false;
4319		synchronized (this.conversations) {
4320			boolean domainJid = blockedJid.getLocal() == null;
4321			for (Conversation conversation : this.conversations) {
4322				boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
4323						|| blockedJid.equals(conversation.getJid().asBareJid());
4324				if (conversation.getAccount() == account
4325						&& conversation.getMode() == Conversation.MODE_SINGLE
4326						&& jidMatches) {
4327					this.conversations.remove(conversation);
4328					markRead(conversation);
4329					conversation.setStatus(Conversation.STATUS_ARCHIVED);
4330					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
4331					updateConversation(conversation);
4332					removed = true;
4333				}
4334			}
4335		}
4336		return removed;
4337	}
4338
4339	public void sendUnblockRequest(final Blockable blockable) {
4340		if (blockable != null && blockable.getJid() != null) {
4341			final Jid jid = blockable.getBlockedJid();
4342			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
4343				@Override
4344				public void onIqPacketReceived(final Account account, final IqPacket packet) {
4345					if (packet.getType() == IqPacket.TYPE.RESULT) {
4346						account.getBlocklist().remove(jid);
4347						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
4348					}
4349				}
4350			});
4351		}
4352	}
4353
4354	public void publishDisplayName(Account account) {
4355		String displayName = account.getDisplayName();
4356		final IqPacket request;
4357		if (TextUtils.isEmpty(displayName)) {
4358            request = mIqGenerator.deleteNode(Namespace.NICK);
4359		} else {
4360            request = mIqGenerator.publishNick(displayName);
4361        }
4362        mAvatarService.clear(account);
4363        sendIqPacket(account, request, (account1, packet) -> {
4364            if (packet.getType() == IqPacket.TYPE.ERROR) {
4365                Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": unable to modify nick name "+packet.toString());
4366            }
4367        });
4368	}
4369
4370	public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
4371		ServiceDiscoveryResult result = discoCache.get(key);
4372		if (result != null) {
4373			return result;
4374		} else {
4375			result = databaseBackend.findDiscoveryResult(key.first, key.second);
4376			if (result != null) {
4377				discoCache.put(key, result);
4378			}
4379			return result;
4380		}
4381	}
4382
4383	public void fetchCaps(Account account, final Jid jid, final Presence presence) {
4384		final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
4385		ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
4386		if (disco != null) {
4387			presence.setServiceDiscoveryResult(disco);
4388		} else {
4389			if (!account.inProgressDiscoFetches.contains(key)) {
4390				account.inProgressDiscoFetches.add(key);
4391				IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4392				request.setTo(jid);
4393				final String node = presence.getNode();
4394				final String ver = presence.getVer();
4395				final Element query = request.query("http://jabber.org/protocol/disco#info");
4396				if (node != null && ver != null) {
4397					query.setAttribute("node",node+"#"+ver);
4398				}
4399				Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
4400				sendIqPacket(account, request, (a, response) -> {
4401					if (response.getType() == IqPacket.TYPE.RESULT) {
4402						ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
4403						if (presence.getVer().equals(discoveryResult.getVer())) {
4404							databaseBackend.insertDiscoveryResult(discoveryResult);
4405							injectServiceDiscoveryResult(a.getRoster(), presence.getHash(), presence.getVer(), discoveryResult);
4406						} else {
4407							Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
4408						}
4409					}
4410					a.inProgressDiscoFetches.remove(key);
4411				});
4412			}
4413		}
4414	}
4415
4416	private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
4417		for (Contact contact : roster.getContacts()) {
4418			for (Presence presence : contact.getPresences().getPresences().values()) {
4419				if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
4420					presence.setServiceDiscoveryResult(disco);
4421				}
4422			}
4423		}
4424	}
4425
4426	public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
4427		final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
4428		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4429		request.addChild("prefs", version.namespace);
4430		sendIqPacket(account, request, (account1, packet) -> {
4431			Element prefs = packet.findChild("prefs", version.namespace);
4432			if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
4433				callback.onPreferencesFetched(prefs);
4434			} else {
4435				callback.onPreferencesFetchFailed();
4436			}
4437		});
4438	}
4439
4440	public PushManagementService getPushManagementService() {
4441		return mPushManagementService;
4442	}
4443
4444	public void changeStatus(Account account, PresenceTemplate template, String signature) {
4445		if (!template.getStatusMessage().isEmpty()) {
4446			databaseBackend.insertPresenceTemplate(template);
4447		}
4448		account.setPgpSignature(signature);
4449		account.setPresenceStatus(template.getStatus());
4450		account.setPresenceStatusMessage(template.getStatusMessage());
4451		databaseBackend.updateAccount(account);
4452		sendPresence(account);
4453	}
4454
4455	public List<PresenceTemplate> getPresenceTemplates(Account account) {
4456		List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
4457		for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
4458			if (!templates.contains(template)) {
4459				templates.add(0, template);
4460			}
4461		}
4462		return templates;
4463	}
4464
4465	public void saveConversationAsBookmark(Conversation conversation, String name) {
4466		final Account account = conversation.getAccount();
4467		final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
4468		final String nick = conversation.getJid().getResource();
4469        if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
4470            bookmark.setNick(nick);
4471        }
4472		if (!TextUtils.isEmpty(name)) {
4473			bookmark.setBookmarkName(name);
4474		}
4475		bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
4476		account.getBookmarks().add(bookmark);
4477		createBookmark(account, bookmark);
4478		bookmark.setConversation(conversation);
4479	}
4480
4481	public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
4482		boolean performedVerification = false;
4483		final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
4484		for (XmppUri.Fingerprint fp : fingerprints) {
4485			if (fp.type == XmppUri.FingerprintType.OMEMO) {
4486				String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4487				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4488				if (fingerprintStatus != null) {
4489					if (!fingerprintStatus.isVerified()) {
4490						performedVerification = true;
4491						axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4492					}
4493				} else {
4494					axolotlService.preVerifyFingerprint(contact, fingerprint);
4495				}
4496			}
4497		}
4498		return performedVerification;
4499	}
4500
4501	public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
4502		final AxolotlService axolotlService = account.getAxolotlService();
4503		boolean verifiedSomething = false;
4504		for (XmppUri.Fingerprint fp : fingerprints) {
4505			if (fp.type == XmppUri.FingerprintType.OMEMO) {
4506				String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4507				Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
4508				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4509				if (fingerprintStatus != null) {
4510					if (!fingerprintStatus.isVerified()) {
4511						axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4512						verifiedSomething = true;
4513					}
4514				} else {
4515					axolotlService.preVerifyFingerprint(account, fingerprint);
4516					verifiedSomething = true;
4517				}
4518			}
4519		}
4520		return verifiedSomething;
4521	}
4522
4523	public boolean blindTrustBeforeVerification() {
4524		return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
4525	}
4526
4527	public ShortcutService getShortcutService() {
4528		return mShortcutService;
4529	}
4530
4531	public void pushMamPreferences(Account account, Element prefs) {
4532		IqPacket set = new IqPacket(IqPacket.TYPE.SET);
4533		set.addChild(prefs);
4534		sendIqPacket(account, set, null);
4535	}
4536
4537	public interface OnMamPreferencesFetched {
4538		void onPreferencesFetched(Element prefs);
4539
4540		void onPreferencesFetchFailed();
4541	}
4542
4543	public interface OnAccountCreated {
4544		void onAccountCreated(Account account);
4545
4546		void informUser(int r);
4547	}
4548
4549	public interface OnMoreMessagesLoaded {
4550		void onMoreMessagesLoaded(int count, Conversation conversation);
4551
4552		void informUser(int r);
4553	}
4554
4555	public interface OnAccountPasswordChanged {
4556		void onPasswordChangeSucceeded();
4557
4558		void onPasswordChangeFailed();
4559	}
4560
4561    public interface OnRoomDestroy {
4562        void onRoomDestroySucceeded();
4563
4564        void onRoomDestroyFailed();
4565    }
4566
4567	public interface OnAffiliationChanged {
4568		void onAffiliationChangedSuccessful(Jid jid);
4569
4570		void onAffiliationChangeFailed(Jid jid, int resId);
4571	}
4572
4573	public interface OnConversationUpdate {
4574		void onConversationUpdate();
4575	}
4576
4577	public interface OnAccountUpdate {
4578		void onAccountUpdate();
4579	}
4580
4581	public interface OnCaptchaRequested {
4582		void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
4583	}
4584
4585	public interface OnRosterUpdate {
4586		void onRosterUpdate();
4587	}
4588
4589	public interface OnMucRosterUpdate {
4590		void onMucRosterUpdate();
4591	}
4592
4593	public interface OnConferenceConfigurationFetched {
4594		void onConferenceConfigurationFetched(Conversation conversation);
4595
4596		void onFetchFailed(Conversation conversation, Element error);
4597	}
4598
4599	public interface OnConferenceJoined {
4600		void onConferenceJoined(Conversation conversation);
4601	}
4602
4603	public interface OnConfigurationPushed {
4604		void onPushSucceeded();
4605
4606		void onPushFailed();
4607	}
4608
4609	public interface OnShowErrorToast {
4610		void onShowErrorToast(int resId);
4611	}
4612
4613	public class XmppConnectionBinder extends Binder {
4614		public XmppConnectionService getService() {
4615			return XmppConnectionService.this;
4616		}
4617	}
4618
4619	private class InternalEventReceiver extends BroadcastReceiver {
4620
4621        @Override
4622        public void onReceive(Context context, Intent intent) {
4623            onStartCommand(intent,0,0);
4624        }
4625    }
4626}