XmppConnectionService.java

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