XmppConnectionService.java

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