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