XmppConnectionService.java

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