XmppConnectionService.java

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