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