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