XmppConnectionService.java

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