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                    Log.w(Config.LOGTAG,"falling back to special use foreground service type");
1470                }
1471                startForeground(id, notification, foregroundServiceType);
1472            } else {
1473                startForeground(id, notification);
1474            }
1475        } catch (final IllegalStateException | SecurityException e) {
1476            Log.e(Config.LOGTAG, "Could not start foreground service", e);
1477        }
1478    }
1479
1480    public boolean foregroundNotificationNeedsUpdatingWhenErrorStateChanges() {
1481        return !mForceForegroundService.get() && ongoingCall.get() == null && Compatibility.keepForegroundService(this) && hasEnabledAccounts();
1482    }
1483
1484    @Override
1485    public void onTaskRemoved(final Intent rootIntent) {
1486        super.onTaskRemoved(rootIntent);
1487        if ((Compatibility.keepForegroundService(this) && hasEnabledAccounts()) || mForceForegroundService.get() || ongoingCall.get() != null) {
1488            Log.d(Config.LOGTAG, "ignoring onTaskRemoved because foreground service is activated");
1489        } else {
1490            this.logoutAndSave(false);
1491        }
1492    }
1493
1494    private void logoutAndSave(boolean stop) {
1495        int activeAccounts = 0;
1496        for (final Account account : accounts) {
1497            if (account.isConnectionEnabled()) {
1498                databaseBackend.writeRoster(account.getRoster());
1499                activeAccounts++;
1500            }
1501            if (account.getXmppConnection() != null) {
1502                new Thread(() -> disconnect(account, false)).start();
1503            }
1504        }
1505        if (stop || activeAccounts == 0) {
1506            Log.d(Config.LOGTAG, "good bye");
1507            stopSelf();
1508        }
1509    }
1510
1511    private void schedulePostConnectivityChange() {
1512        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1513        if (alarmManager == null) {
1514            return;
1515        }
1516        final long triggerAtMillis = SystemClock.elapsedRealtime() + (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL * 1000);
1517        final Intent intent = new Intent(this, EventReceiver.class);
1518        intent.setAction(ACTION_POST_CONNECTIVITY_CHANGE);
1519        try {
1520            final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, s()
1521                    ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1522                    : PendingIntent.FLAG_UPDATE_CURRENT);
1523            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1524                alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1525            } else {
1526                alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1527            }
1528        } catch (RuntimeException e) {
1529            Log.e(Config.LOGTAG, "unable to schedule alarm for post connectivity change", e);
1530        }
1531    }
1532
1533    public void scheduleWakeUpCall(final int seconds, final int requestCode) {
1534        final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000L;
1535        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1536        if (alarmManager == null) {
1537            return;
1538        }
1539        final Intent intent = new Intent(this, EventReceiver.class);
1540        intent.setAction(ACTION_PING);
1541        try {
1542            final PendingIntent pendingIntent =
1543                    PendingIntent.getBroadcast(
1544                            this, requestCode, intent, PendingIntent.FLAG_IMMUTABLE);
1545            alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1546        } catch (RuntimeException e) {
1547            Log.e(Config.LOGTAG, "unable to schedule alarm for ping", e);
1548        }
1549    }
1550
1551    @TargetApi(Build.VERSION_CODES.M)
1552    private void scheduleNextIdlePing() {
1553        final long timeToWake = SystemClock.elapsedRealtime() + (Config.IDLE_PING_INTERVAL * 1000);
1554        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1555        if (alarmManager == null) {
1556            return;
1557        }
1558        final Intent intent = new Intent(this, EventReceiver.class);
1559        intent.setAction(ACTION_IDLE_PING);
1560        try {
1561            final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, s()
1562                    ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1563                    : PendingIntent.FLAG_UPDATE_CURRENT);
1564            alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1565        } catch (RuntimeException e) {
1566            Log.d(Config.LOGTAG, "unable to schedule alarm for idle ping", e);
1567        }
1568    }
1569
1570    public XmppConnection createConnection(final Account account) {
1571        final XmppConnection connection = new XmppConnection(account, this);
1572        connection.setOnMessagePacketReceivedListener(this.mMessageParser);
1573        connection.setOnStatusChangedListener(this.statusListener);
1574        connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
1575        connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
1576        connection.setOnJinglePacketReceivedListener((mJingleConnectionManager::deliverPacket));
1577        connection.setOnBindListener(this.mOnBindListener);
1578        connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
1579        connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
1580        connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
1581        AxolotlService axolotlService = account.getAxolotlService();
1582        if (axolotlService != null) {
1583            connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
1584        }
1585        return connection;
1586    }
1587
1588    public void sendChatState(Conversation conversation) {
1589        if (sendChatStates()) {
1590            MessagePacket packet = mMessageGenerator.generateChatState(conversation);
1591            sendMessagePacket(conversation.getAccount(), packet);
1592        }
1593    }
1594
1595    private void sendFileMessage(final Message message, final boolean delay) {
1596        Log.d(Config.LOGTAG, "send file message");
1597        final Account account = message.getConversation().getAccount();
1598        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1599                || message.getConversation().getMode() == Conversation.MODE_MULTI) {
1600            mHttpConnectionManager.createNewUploadConnection(message, delay);
1601        } else {
1602            mJingleConnectionManager.startJingleFileTransfer(message);
1603        }
1604    }
1605
1606    public void sendMessage(final Message message) {
1607        sendMessage(message, false, false);
1608    }
1609
1610    private void sendMessage(final Message message, final boolean resend, final boolean delay) {
1611        final Account account = message.getConversation().getAccount();
1612        if (account.setShowErrorNotification(true)) {
1613            databaseBackend.updateAccount(account);
1614            mNotificationService.updateErrorNotification();
1615        }
1616        final Conversation conversation = (Conversation) message.getConversation();
1617        account.deactivateGracePeriod();
1618
1619
1620        if (QuickConversationsService.isQuicksy() && conversation.getMode() == Conversation.MODE_SINGLE) {
1621            final Contact contact = conversation.getContact();
1622            if (!contact.showInRoster() && contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1623                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": adding " + contact.getJid() + " on sending message");
1624                createContact(contact, true);
1625            }
1626        }
1627
1628        MessagePacket packet = null;
1629        final boolean addToConversation = !message.edited();
1630        boolean saveInDb = addToConversation;
1631        message.setStatus(Message.STATUS_WAITING);
1632
1633        if (message.getEncryption() != Message.ENCRYPTION_NONE && conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous()) {
1634            if (conversation.setAttribute(Conversation.ATTRIBUTE_FORMERLY_PRIVATE_NON_ANONYMOUS, true)) {
1635                databaseBackend.updateConversation(conversation);
1636            }
1637        }
1638
1639        final boolean inProgressJoin = isJoinInProgress(conversation);
1640
1641
1642        if (account.isOnlineAndConnected() && !inProgressJoin) {
1643            switch (message.getEncryption()) {
1644                case Message.ENCRYPTION_NONE:
1645                    if (message.needsUploading()) {
1646                        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1647                                || conversation.getMode() == Conversation.MODE_MULTI
1648                                || message.fixCounterpart()) {
1649                            this.sendFileMessage(message, delay);
1650                        } else {
1651                            break;
1652                        }
1653                    } else {
1654                        packet = mMessageGenerator.generateChat(message);
1655                    }
1656                    break;
1657                case Message.ENCRYPTION_PGP:
1658                case Message.ENCRYPTION_DECRYPTED:
1659                    if (message.needsUploading()) {
1660                        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1661                                || conversation.getMode() == Conversation.MODE_MULTI
1662                                || message.fixCounterpart()) {
1663                            this.sendFileMessage(message, delay);
1664                        } else {
1665                            break;
1666                        }
1667                    } else {
1668                        packet = mMessageGenerator.generatePgpChat(message);
1669                    }
1670                    break;
1671                case Message.ENCRYPTION_AXOLOTL:
1672                    message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1673                    if (message.needsUploading()) {
1674                        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1675                                || conversation.getMode() == Conversation.MODE_MULTI
1676                                || message.fixCounterpart()) {
1677                            this.sendFileMessage(message, delay);
1678                        } else {
1679                            break;
1680                        }
1681                    } else {
1682                        XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
1683                        if (axolotlMessage == null) {
1684                            account.getAxolotlService().preparePayloadMessage(message, delay);
1685                        } else {
1686                            packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
1687                        }
1688                    }
1689                    break;
1690
1691            }
1692            if (packet != null) {
1693                if (account.getXmppConnection().getFeatures().sm()
1694                        || (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1695                    message.setStatus(Message.STATUS_UNSEND);
1696                } else {
1697                    message.setStatus(Message.STATUS_SEND);
1698                }
1699            }
1700        } else {
1701            switch (message.getEncryption()) {
1702                case Message.ENCRYPTION_DECRYPTED:
1703                    if (!message.needsUploading()) {
1704                        String pgpBody = message.getEncryptedBody();
1705                        String decryptedBody = message.getBody();
1706                        message.setBody(pgpBody); //TODO might throw NPE
1707                        message.setEncryption(Message.ENCRYPTION_PGP);
1708                        if (message.edited()) {
1709                            message.setBody(decryptedBody);
1710                            message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1711                            if (!databaseBackend.updateMessage(message, message.getEditedId())) {
1712                                Log.e(Config.LOGTAG, "error updated message in DB after edit");
1713                            }
1714                            updateConversationUi();
1715                            return;
1716                        } else {
1717                            databaseBackend.createMessage(message);
1718                            saveInDb = false;
1719                            message.setBody(decryptedBody);
1720                            message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1721                        }
1722                    }
1723                    break;
1724                case Message.ENCRYPTION_AXOLOTL:
1725                    message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1726                    break;
1727            }
1728        }
1729
1730
1731        boolean mucMessage = conversation.getMode() == Conversation.MODE_MULTI && !message.isPrivateMessage();
1732        if (mucMessage) {
1733            message.setCounterpart(conversation.getMucOptions().getSelf().getFullJid());
1734        }
1735
1736        if (resend) {
1737            if (packet != null && addToConversation) {
1738                if (account.getXmppConnection().getFeatures().sm() || mucMessage) {
1739                    markMessage(message, Message.STATUS_UNSEND);
1740                } else {
1741                    markMessage(message, Message.STATUS_SEND);
1742                }
1743            }
1744        } else {
1745            if (addToConversation) {
1746                conversation.add(message);
1747            }
1748            if (saveInDb) {
1749                databaseBackend.createMessage(message);
1750            } else if (message.edited()) {
1751                if (!databaseBackend.updateMessage(message, message.getEditedId())) {
1752                    Log.e(Config.LOGTAG, "error updated message in DB after edit");
1753                }
1754            }
1755            updateConversationUi();
1756        }
1757        if (packet != null) {
1758            if (delay) {
1759                mMessageGenerator.addDelay(packet, message.getTimeSent());
1760            }
1761            if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
1762                if (this.sendChatStates()) {
1763                    packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
1764                }
1765            }
1766            sendMessagePacket(account, packet);
1767        }
1768    }
1769
1770    private boolean isJoinInProgress(final Conversation conversation) {
1771        final Account account = conversation.getAccount();
1772        synchronized (account.inProgressConferenceJoins) {
1773            if (conversation.getMode() == Conversational.MODE_MULTI) {
1774                final boolean inProgress = account.inProgressConferenceJoins.contains(conversation);
1775                final boolean pending = account.pendingConferenceJoins.contains(conversation);
1776                final boolean inProgressJoin = inProgress || pending;
1777                if (inProgressJoin) {
1778                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": holding back message to group. inProgress=" + inProgress + ", pending=" + pending);
1779                }
1780                return inProgressJoin;
1781            } else {
1782                return false;
1783            }
1784        }
1785    }
1786
1787    private void sendUnsentMessages(final Conversation conversation) {
1788        conversation.findWaitingMessages(message -> resendMessage(message, true));
1789    }
1790
1791    public void resendMessage(final Message message, final boolean delay) {
1792        sendMessage(message, true, delay);
1793    }
1794
1795    public void requestEasyOnboardingInvite(final Account account, final EasyOnboardingInvite.OnInviteRequested callback) {
1796        final XmppConnection connection = account.getXmppConnection();
1797        final Jid jid = connection == null ? null : connection.getJidForCommand(Namespace.EASY_ONBOARDING_INVITE);
1798        if (jid == null) {
1799            callback.inviteRequestFailed(getString(R.string.server_does_not_support_easy_onboarding_invites));
1800            return;
1801        }
1802        final IqPacket request = new IqPacket(IqPacket.TYPE.SET);
1803        request.setTo(jid);
1804        final Element command = request.addChild("command", Namespace.COMMANDS);
1805        command.setAttribute("node", Namespace.EASY_ONBOARDING_INVITE);
1806        command.setAttribute("action", "execute");
1807        sendIqPacket(account, request, (a, response) -> {
1808            if (response.getType() == IqPacket.TYPE.RESULT) {
1809                final Element resultCommand = response.findChild("command", Namespace.COMMANDS);
1810                final Element x = resultCommand == null ? null : resultCommand.findChild("x", Namespace.DATA);
1811                if (x != null) {
1812                    final Data data = Data.parse(x);
1813                    final String uri = data.getValue("uri");
1814                    final String landingUrl = data.getValue("landing-url");
1815                    if (uri != null) {
1816                        final EasyOnboardingInvite invite = new EasyOnboardingInvite(jid.getDomain().toEscapedString(), uri, landingUrl);
1817                        callback.inviteRequested(invite);
1818                        return;
1819                    }
1820                }
1821                callback.inviteRequestFailed(getString(R.string.unable_to_parse_invite));
1822                Log.d(Config.LOGTAG, response.toString());
1823            } else if (response.getType() == IqPacket.TYPE.ERROR) {
1824                callback.inviteRequestFailed(IqParser.errorMessage(response));
1825            } else {
1826                callback.inviteRequestFailed(getString(R.string.remote_server_timeout));
1827            }
1828        });
1829
1830    }
1831
1832    public void fetchRosterFromServer(final Account account) {
1833        final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1834        if (!"".equals(account.getRosterVersion())) {
1835            Log.d(Config.LOGTAG, account.getJid().asBareJid()
1836                    + ": fetching roster version " + account.getRosterVersion());
1837        } else {
1838            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching roster");
1839        }
1840        iqPacket.query(Namespace.ROSTER).setAttribute("ver", account.getRosterVersion());
1841        sendIqPacket(account, iqPacket, mIqParser);
1842    }
1843
1844    public void fetchBookmarks(final Account account) {
1845        final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1846        final Element query = iqPacket.query("jabber:iq:private");
1847        query.addChild("storage", Namespace.BOOKMARKS);
1848        final OnIqPacketReceived callback = (a, response) -> {
1849            if (response.getType() == IqPacket.TYPE.RESULT) {
1850                final Element query1 = response.query();
1851                final Element storage = query1.findChild("storage", "storage:bookmarks");
1852                Map<Jid, Bookmark> bookmarks = Bookmark.parseFromStorage(storage, account);
1853                processBookmarksInitial(a, bookmarks, false);
1854            } else {
1855                Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": could not fetch bookmarks");
1856            }
1857        };
1858        sendIqPacket(account, iqPacket, callback);
1859    }
1860
1861    public void fetchBookmarks2(final Account account) {
1862        final IqPacket retrieve = mIqGenerator.retrieveBookmarks();
1863        sendIqPacket(account, retrieve, new OnIqPacketReceived() {
1864            @Override
1865            public void onIqPacketReceived(final Account account, final IqPacket response) {
1866                if (response.getType() == IqPacket.TYPE.RESULT) {
1867                    final Element pubsub = response.findChild("pubsub", Namespace.PUBSUB);
1868                    final Map<Jid, Bookmark> bookmarks = Bookmark.parseFromPubsub(pubsub, account);
1869                    processBookmarksInitial(account, bookmarks, true);
1870                }
1871            }
1872        });
1873    }
1874
1875    public void processBookmarksInitial(Account account, Map<Jid, Bookmark> bookmarks, final boolean pep) {
1876        final Set<Jid> previousBookmarks = account.getBookmarkedJids();
1877        final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
1878        for (Bookmark bookmark : bookmarks.values()) {
1879            previousBookmarks.remove(bookmark.getJid().asBareJid());
1880            processModifiedBookmark(bookmark, pep, synchronizeWithBookmarks);
1881        }
1882        if (pep && synchronizeWithBookmarks) {
1883            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + previousBookmarks.size() + " bookmarks have been removed");
1884            for (Jid jid : previousBookmarks) {
1885                processDeletedBookmark(account, jid);
1886            }
1887        }
1888        account.setBookmarks(bookmarks);
1889    }
1890
1891    public void processDeletedBookmark(Account account, Jid jid) {
1892        final Conversation conversation = find(account, jid);
1893        if (conversation != null && conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
1894            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving destroyed conference (" + conversation.getJid() + ") after receiving pep");
1895            archiveConversation(conversation, false);
1896        }
1897    }
1898
1899    private void processModifiedBookmark(Bookmark bookmark, final boolean pep, final boolean synchronizeWithBookmarks) {
1900        final Account account = bookmark.getAccount();
1901        Conversation conversation = find(bookmark);
1902        if (conversation != null) {
1903            if (conversation.getMode() != Conversation.MODE_MULTI) {
1904                return;
1905            }
1906            bookmark.setConversation(conversation);
1907            if (pep && synchronizeWithBookmarks && !bookmark.autojoin()) {
1908                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conference (" + conversation.getJid() + ") after receiving pep");
1909                archiveConversation(conversation, false);
1910            } else {
1911                final MucOptions mucOptions = conversation.getMucOptions();
1912                if (mucOptions.getError() == MucOptions.Error.NICK_IN_USE) {
1913                    final String current = mucOptions.getActualNick();
1914                    final String proposed = mucOptions.getProposedNick();
1915                    if (current != null && !current.equals(proposed)) {
1916                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": proposed nick changed after bookmark push " + current + "->" + proposed);
1917                        joinMuc(conversation);
1918                    }
1919                }
1920            }
1921        } else if (synchronizeWithBookmarks && bookmark.autojoin()) {
1922            conversation = findOrCreateConversation(account, bookmark.getFullJid(), true, true, false);
1923            bookmark.setConversation(conversation);
1924        }
1925    }
1926
1927    public void processModifiedBookmark(Bookmark bookmark) {
1928        final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
1929        processModifiedBookmark(bookmark, true, synchronizeWithBookmarks);
1930    }
1931
1932    public void createBookmark(final Account account, final Bookmark bookmark) {
1933        account.putBookmark(bookmark);
1934        final XmppConnection connection = account.getXmppConnection();
1935        if (connection == null) {
1936            Log.d(Config.LOGTAG, account.getJid().asBareJid()+": no connection. ignoring bookmark creation");
1937        } else if (connection.getFeatures().bookmarks2()) {
1938            final Element item = mIqGenerator.publishBookmarkItem(bookmark);
1939            pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS2, item, bookmark.getJid().asBareJid().toEscapedString(), PublishOptions.persistentWhitelistAccessMaxItems());
1940        } else if (connection.getFeatures().bookmarksConversion()) {
1941            pushBookmarksPep(account);
1942        } else {
1943            pushBookmarksPrivateXml(account);
1944        }
1945    }
1946
1947    public void deleteBookmark(final Account account, final Bookmark bookmark) {
1948        account.removeBookmark(bookmark);
1949        final XmppConnection connection = account.getXmppConnection();
1950        if (connection.getFeatures().bookmarks2()) {
1951            IqPacket request = mIqGenerator.deleteItem(Namespace.BOOKMARKS2, bookmark.getJid().asBareJid().toEscapedString());
1952            sendIqPacket(account, request, (a, response) -> {
1953                if (response.getType() == IqPacket.TYPE.ERROR) {
1954                    Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": unable to delete bookmark " + response.getErrorCondition());
1955                }
1956            });
1957        } else if (connection.getFeatures().bookmarksConversion()) {
1958            pushBookmarksPep(account);
1959        } else {
1960            pushBookmarksPrivateXml(account);
1961        }
1962    }
1963
1964    private void pushBookmarksPrivateXml(Account account) {
1965        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
1966        IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1967        Element query = iqPacket.query("jabber:iq:private");
1968        Element storage = query.addChild("storage", "storage:bookmarks");
1969        for (final Bookmark bookmark : account.getBookmarks()) {
1970            storage.addChild(bookmark);
1971        }
1972        sendIqPacket(account, iqPacket, mDefaultIqHandler);
1973    }
1974
1975    private void pushBookmarksPep(Account account) {
1976        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
1977        final Element storage = new Element("storage", "storage:bookmarks");
1978        for (final Bookmark bookmark : account.getBookmarks()) {
1979            storage.addChild(bookmark);
1980        }
1981        pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS, storage, "current", PublishOptions.persistentWhitelistAccess());
1982
1983    }
1984
1985    private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options) {
1986        pushNodeAndEnforcePublishOptions(account, node, element, id, options, true);
1987
1988    }
1989
1990    private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options, final boolean retry) {
1991        final IqPacket packet = mIqGenerator.publishElement(node, element, id, options);
1992        sendIqPacket(account, packet, (a, response) -> {
1993            if (response.getType() == IqPacket.TYPE.RESULT) {
1994                return;
1995            }
1996            if (retry && PublishOptions.preconditionNotMet(response)) {
1997                pushNodeConfiguration(account, node, options, new OnConfigurationPushed() {
1998                    @Override
1999                    public void onPushSucceeded() {
2000                        pushNodeAndEnforcePublishOptions(account, node, element, id, options, false);
2001                    }
2002
2003                    @Override
2004                    public void onPushFailed() {
2005                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to push node configuration (" + node + ")");
2006                    }
2007                });
2008            } else {
2009                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error publishing bookmarks (retry=" + retry + ") " + response);
2010            }
2011        });
2012    }
2013
2014    private void restoreFromDatabase() {
2015        synchronized (this.conversations) {
2016            final Map<String, Account> accountLookupTable = new Hashtable<>();
2017            for (Account account : this.accounts) {
2018                accountLookupTable.put(account.getUuid(), account);
2019            }
2020            Log.d(Config.LOGTAG, "restoring conversations...");
2021            final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
2022            this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
2023            for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
2024                Conversation conversation = iterator.next();
2025                Account account = accountLookupTable.get(conversation.getAccountUuid());
2026                if (account != null) {
2027                    conversation.setAccount(account);
2028                } else {
2029                    Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
2030                    iterator.remove();
2031                }
2032            }
2033            long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
2034            Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
2035            Runnable runnable = () -> {
2036                if (DatabaseBackend.requiresMessageIndexRebuild()) {
2037                    DatabaseBackend.getInstance(this).rebuildMessagesIndex();
2038                }
2039                final long deletionDate = getAutomaticMessageDeletionDate();
2040                mLastExpiryRun.set(SystemClock.elapsedRealtime());
2041                if (deletionDate > 0) {
2042                    Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
2043                    databaseBackend.expireOldMessages(deletionDate);
2044                }
2045                Log.d(Config.LOGTAG, "restoring roster...");
2046                for (final Account account : accounts) {
2047                    databaseBackend.readRoster(account.getRoster());
2048                    account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
2049                }
2050                getBitmapCache().evictAll();
2051                loadPhoneContacts();
2052                Log.d(Config.LOGTAG, "restoring messages...");
2053                final long startMessageRestore = SystemClock.elapsedRealtime();
2054                final Conversation quickLoad = QuickLoader.get(this.conversations);
2055                if (quickLoad != null) {
2056                    restoreMessages(quickLoad);
2057                    updateConversationUi();
2058                    final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
2059                    Log.d(Config.LOGTAG, "quickly restored " + quickLoad.getName() + " after " + diffMessageRestore + "ms");
2060                }
2061                for (Conversation conversation : this.conversations) {
2062                    if (quickLoad != conversation) {
2063                        restoreMessages(conversation);
2064                    }
2065                }
2066                mNotificationService.finishBacklog();
2067                restoredFromDatabaseLatch.countDown();
2068                final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
2069                Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
2070                updateConversationUi();
2071            };
2072            mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
2073        }
2074    }
2075
2076    private void restoreMessages(Conversation conversation) {
2077        conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
2078        conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
2079        conversation.findUnreadMessagesAndCalls(mNotificationService::pushFromBacklog);
2080    }
2081
2082    public void loadPhoneContacts() {
2083        mContactMergerExecutor.execute(() -> {
2084            final Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
2085            Log.d(Config.LOGTAG, "start merging phone contacts with roster");
2086            for (final Account account : accounts) {
2087                final List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts(JabberIdContact.class);
2088                for (final JabberIdContact jidContact : contacts.values()) {
2089                    final Contact contact = account.getRoster().getContact(jidContact.getJid());
2090                    boolean needsCacheClean = contact.setPhoneContact(jidContact);
2091                    if (needsCacheClean) {
2092                        getAvatarService().clear(contact);
2093                    }
2094                    withSystemAccounts.remove(contact);
2095                }
2096                for (final Contact contact : withSystemAccounts) {
2097                    boolean needsCacheClean = contact.unsetPhoneContact(JabberIdContact.class);
2098                    if (needsCacheClean) {
2099                        getAvatarService().clear(contact);
2100                    }
2101                }
2102            }
2103            Log.d(Config.LOGTAG, "finished merging phone contacts");
2104            mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
2105            updateRosterUi();
2106            mQuickConversationsService.considerSync();
2107        });
2108    }
2109
2110
2111    public void syncRoster(final Account account) {
2112        mRosterSyncTaskManager.execute(account, () -> databaseBackend.writeRoster(account.getRoster()));
2113    }
2114
2115    public List<Conversation> getConversations() {
2116        return this.conversations;
2117    }
2118
2119    private void markFileDeleted(final File file) {
2120        synchronized (FILENAMES_TO_IGNORE_DELETION) {
2121            if (FILENAMES_TO_IGNORE_DELETION.remove(file.getAbsolutePath())) {
2122                Log.d(Config.LOGTAG, "ignored deletion of " + file.getAbsolutePath());
2123                return;
2124            }
2125        }
2126        final boolean isInternalFile = fileBackend.isInternalFile(file);
2127        final List<String> uuids = databaseBackend.markFileAsDeleted(file, isInternalFile);
2128        Log.d(Config.LOGTAG, "deleted file " + file.getAbsolutePath() + " internal=" + isInternalFile + ", database hits=" + uuids.size());
2129        markUuidsAsDeletedFiles(uuids);
2130    }
2131
2132    private void markUuidsAsDeletedFiles(List<String> uuids) {
2133        boolean deleted = false;
2134        for (Conversation conversation : getConversations()) {
2135            deleted |= conversation.markAsDeleted(uuids);
2136        }
2137        for (final String uuid : uuids) {
2138            evictPreview(uuid);
2139        }
2140        if (deleted) {
2141            updateConversationUi();
2142        }
2143    }
2144
2145    private void markChangedFiles(List<DatabaseBackend.FilePathInfo> infos) {
2146        boolean changed = false;
2147        for (Conversation conversation : getConversations()) {
2148            changed |= conversation.markAsChanged(infos);
2149        }
2150        if (changed) {
2151            updateConversationUi();
2152        }
2153    }
2154
2155    public void populateWithOrderedConversations(final List<Conversation> list) {
2156        populateWithOrderedConversations(list, true, true);
2157    }
2158
2159    public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload) {
2160        populateWithOrderedConversations(list, includeNoFileUpload, true);
2161    }
2162
2163    public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload, final boolean sort) {
2164        final List<String> orderedUuids;
2165        if (sort) {
2166            orderedUuids = null;
2167        } else {
2168            orderedUuids = new ArrayList<>();
2169            for (Conversation conversation : list) {
2170                orderedUuids.add(conversation.getUuid());
2171            }
2172        }
2173        list.clear();
2174        if (includeNoFileUpload) {
2175            list.addAll(getConversations());
2176        } else {
2177            for (Conversation conversation : getConversations()) {
2178                if (conversation.getMode() == Conversation.MODE_SINGLE
2179                        || (conversation.getAccount().httpUploadAvailable() && conversation.getMucOptions().participating())) {
2180                    list.add(conversation);
2181                }
2182            }
2183        }
2184        try {
2185            if (orderedUuids != null) {
2186                Collections.sort(list, (a, b) -> {
2187                    final int indexA = orderedUuids.indexOf(a.getUuid());
2188                    final int indexB = orderedUuids.indexOf(b.getUuid());
2189                    if (indexA == -1 || indexB == -1 || indexA == indexB) {
2190                        return a.compareTo(b);
2191                    }
2192                    return indexA - indexB;
2193                });
2194            } else {
2195                Collections.sort(list);
2196            }
2197        } catch (IllegalArgumentException e) {
2198            //ignore
2199        }
2200    }
2201
2202    public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
2203        if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
2204            return;
2205        } else if (timestamp == 0) {
2206            return;
2207        }
2208        Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
2209        final Runnable runnable = () -> {
2210            final Account account = conversation.getAccount();
2211            List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
2212            if (messages.size() > 0) {
2213                conversation.addAll(0, messages);
2214                callback.onMoreMessagesLoaded(messages.size(), conversation);
2215            } else if (conversation.hasMessagesLeftOnServer()
2216                    && account.isOnlineAndConnected()
2217                    && conversation.getLastClearHistory().getTimestamp() == 0) {
2218                final boolean mamAvailable;
2219                if (conversation.getMode() == Conversation.MODE_SINGLE) {
2220                    mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
2221                } else {
2222                    mamAvailable = conversation.getMucOptions().mamSupport();
2223                }
2224                if (mamAvailable) {
2225                    MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
2226                    if (query != null) {
2227                        query.setCallback(callback);
2228                        callback.informUser(R.string.fetching_history_from_server);
2229                    } else {
2230                        callback.informUser(R.string.not_fetching_history_retention_period);
2231                    }
2232
2233                }
2234            }
2235        };
2236        mDatabaseReaderExecutor.execute(runnable);
2237    }
2238
2239    public List<Account> getAccounts() {
2240        return this.accounts;
2241    }
2242
2243
2244    /**
2245     * 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)
2246     */
2247    public List<Conversation> findAllConferencesWith(Contact contact) {
2248        final ArrayList<Conversation> results = new ArrayList<>();
2249        for (final Conversation c : conversations) {
2250            if (c.getMode() != Conversation.MODE_MULTI) {
2251                continue;
2252            }
2253            final MucOptions mucOptions = c.getMucOptions();
2254            if (c.getJid().asBareJid().equals(contact.getJid().asBareJid()) || (mucOptions != null && mucOptions.isContactInRoom(contact))) {
2255                results.add(c);
2256            }
2257        }
2258        return results;
2259    }
2260
2261    public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
2262        for (final Conversation conversation : haystack) {
2263            if (conversation.getContact() == contact) {
2264                return conversation;
2265            }
2266        }
2267        return null;
2268    }
2269
2270    public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
2271        if (jid == null) {
2272            return null;
2273        }
2274        for (final Conversation conversation : haystack) {
2275            if ((account == null || conversation.getAccount() == account)
2276                    && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
2277                return conversation;
2278            }
2279        }
2280        return null;
2281    }
2282
2283    public boolean isConversationsListEmpty(final Conversation ignore) {
2284        synchronized (this.conversations) {
2285            final int size = this.conversations.size();
2286            return size == 0 || size == 1 && this.conversations.get(0) == ignore;
2287        }
2288    }
2289
2290    public boolean isConversationStillOpen(final Conversation conversation) {
2291        synchronized (this.conversations) {
2292            for (Conversation current : this.conversations) {
2293                if (current == conversation) {
2294                    return true;
2295                }
2296            }
2297        }
2298        return false;
2299    }
2300
2301    public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
2302        return this.findOrCreateConversation(account, jid, muc, false, async);
2303    }
2304
2305    public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
2306        return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
2307    }
2308
2309    public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
2310        synchronized (this.conversations) {
2311            Conversation conversation = find(account, jid);
2312            if (conversation != null) {
2313                return conversation;
2314            }
2315            conversation = databaseBackend.findConversation(account, jid);
2316            final boolean loadMessagesFromDb;
2317            if (conversation != null) {
2318                conversation.setStatus(Conversation.STATUS_AVAILABLE);
2319                conversation.setAccount(account);
2320                if (muc) {
2321                    conversation.setMode(Conversation.MODE_MULTI);
2322                    conversation.setContactJid(jid);
2323                } else {
2324                    conversation.setMode(Conversation.MODE_SINGLE);
2325                    conversation.setContactJid(jid.asBareJid());
2326                }
2327                databaseBackend.updateConversation(conversation);
2328                loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
2329            } else {
2330                String conversationName;
2331                Contact contact = account.getRoster().getContact(jid);
2332                if (contact != null) {
2333                    conversationName = contact.getDisplayName();
2334                } else {
2335                    conversationName = jid.getLocal();
2336                }
2337                if (muc) {
2338                    conversation = new Conversation(conversationName, account, jid,
2339                            Conversation.MODE_MULTI);
2340                } else {
2341                    conversation = new Conversation(conversationName, account, jid.asBareJid(),
2342                            Conversation.MODE_SINGLE);
2343                }
2344                this.databaseBackend.createConversation(conversation);
2345                loadMessagesFromDb = false;
2346            }
2347            final Conversation c = conversation;
2348            final Runnable runnable = () -> {
2349                if (loadMessagesFromDb) {
2350                    c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
2351                    updateConversationUi();
2352                    c.messagesLoaded.set(true);
2353                }
2354                if (account.getXmppConnection() != null
2355                        && !c.getContact().isBlocked()
2356                        && account.getXmppConnection().getFeatures().mam()
2357                        && !muc) {
2358                    if (query == null) {
2359                        mMessageArchiveService.query(c);
2360                    } else {
2361                        if (query.getConversation() == null) {
2362                            mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
2363                        }
2364                    }
2365                }
2366                if (joinAfterCreate) {
2367                    joinMuc(c);
2368                }
2369            };
2370            if (async) {
2371                mDatabaseReaderExecutor.execute(runnable);
2372            } else {
2373                runnable.run();
2374            }
2375            this.conversations.add(conversation);
2376            updateConversationUi();
2377            return conversation;
2378        }
2379    }
2380
2381    public void archiveConversation(Conversation conversation) {
2382        archiveConversation(conversation, true);
2383    }
2384
2385    private void archiveConversation(Conversation conversation, final boolean maySynchronizeWithBookmarks) {
2386        getNotificationService().clear(conversation);
2387        conversation.setStatus(Conversation.STATUS_ARCHIVED);
2388        conversation.setNextMessage(null);
2389        synchronized (this.conversations) {
2390            getMessageArchiveService().kill(conversation);
2391            if (conversation.getMode() == Conversation.MODE_MULTI) {
2392                if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2393                    final Bookmark bookmark = conversation.getBookmark();
2394                    if (maySynchronizeWithBookmarks && bookmark != null && synchronizeWithBookmarks()) {
2395                        if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2396                            Account account = bookmark.getAccount();
2397                            bookmark.setConversation(null);
2398                            deleteBookmark(account, bookmark);
2399                        } else if (bookmark.autojoin()) {
2400                            bookmark.setAutojoin(false);
2401                            createBookmark(bookmark.getAccount(), bookmark);
2402                        }
2403                    }
2404                }
2405                leaveMuc(conversation);
2406            } else {
2407                if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2408                    stopPresenceUpdatesTo(conversation.getContact());
2409                }
2410            }
2411            updateConversation(conversation);
2412            this.conversations.remove(conversation);
2413            updateConversationUi();
2414        }
2415    }
2416
2417    public void stopPresenceUpdatesTo(Contact contact) {
2418        Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
2419        sendPresencePacket(contact.getAccount(), mPresenceGenerator.stopPresenceUpdatesTo(contact));
2420        contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2421    }
2422
2423    public void createAccount(final Account account) {
2424        account.initAccountServices(this);
2425        databaseBackend.createAccount(account);
2426        this.accounts.add(account);
2427        this.reconnectAccountInBackground(account);
2428        updateAccountUi();
2429        syncEnabledAccountSetting();
2430        toggleForegroundService();
2431    }
2432
2433    private void syncEnabledAccountSetting() {
2434        final boolean hasEnabledAccounts = hasEnabledAccounts();
2435        getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
2436        toggleSetProfilePictureActivity(hasEnabledAccounts);
2437    }
2438
2439    private void toggleSetProfilePictureActivity(final boolean enabled) {
2440        try {
2441            final ComponentName name = new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
2442            final int targetState = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
2443            getPackageManager().setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
2444        } catch (IllegalStateException e) {
2445            Log.d(Config.LOGTAG, "unable to toggle profile picture activity");
2446        }
2447    }
2448
2449    public boolean reconfigurePushDistributor() {
2450        return this.unifiedPushBroker.reconfigurePushDistributor();
2451    }
2452
2453    private Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints(final UnifiedPushBroker.PushTargetMessenger pushTargetMessenger) {
2454        return this.unifiedPushBroker.renewUnifiedPushEndpoints(pushTargetMessenger);
2455    }
2456
2457    public Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints() {
2458        return this.unifiedPushBroker.renewUnifiedPushEndpoints(null);
2459    }
2460
2461    private void provisionAccount(final String address, final String password) {
2462        final Jid jid = Jid.ofEscaped(address);
2463        final Account account = new Account(jid, password);
2464        account.setOption(Account.OPTION_DISABLED, true);
2465        Log.d(Config.LOGTAG, jid.asBareJid().toEscapedString() + ": provisioning account");
2466        createAccount(account);
2467    }
2468
2469    public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
2470        new Thread(() -> {
2471            try {
2472                final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
2473                final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
2474                if (cert == null) {
2475                    callback.informUser(R.string.unable_to_parse_certificate);
2476                    return;
2477                }
2478                Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
2479                if (info == null) {
2480                    callback.informUser(R.string.certificate_does_not_contain_jid);
2481                    return;
2482                }
2483                if (findAccountByJid(info.first) == null) {
2484                    final Account account = new Account(info.first, "");
2485                    account.setPrivateKeyAlias(alias);
2486                    account.setOption(Account.OPTION_DISABLED, true);
2487                    account.setOption(Account.OPTION_FIXED_USERNAME, true);
2488                    account.setDisplayName(info.second);
2489                    createAccount(account);
2490                    callback.onAccountCreated(account);
2491                    if (Config.X509_VERIFICATION) {
2492                        try {
2493                            getMemorizingTrustManager().getNonInteractive(account.getServer()).checkClientTrusted(chain, "RSA");
2494                        } catch (CertificateException e) {
2495                            callback.informUser(R.string.certificate_chain_is_not_trusted);
2496                        }
2497                    }
2498                } else {
2499                    callback.informUser(R.string.account_already_exists);
2500                }
2501            } catch (Exception e) {
2502                callback.informUser(R.string.unable_to_parse_certificate);
2503            }
2504        }).start();
2505
2506    }
2507
2508    public void updateKeyInAccount(final Account account, final String alias) {
2509        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
2510        try {
2511            X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
2512            Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
2513            Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
2514            if (info == null) {
2515                showErrorToastInUi(R.string.certificate_does_not_contain_jid);
2516                return;
2517            }
2518            if (account.getJid().asBareJid().equals(info.first)) {
2519                account.setPrivateKeyAlias(alias);
2520                account.setDisplayName(info.second);
2521                databaseBackend.updateAccount(account);
2522                if (Config.X509_VERIFICATION) {
2523                    try {
2524                        getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
2525                    } catch (CertificateException e) {
2526                        showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
2527                    }
2528                    account.getAxolotlService().regenerateKeys(true);
2529                }
2530            } else {
2531                showErrorToastInUi(R.string.jid_does_not_match_certificate);
2532            }
2533        } catch (Exception e) {
2534            e.printStackTrace();
2535        }
2536    }
2537
2538    public boolean updateAccount(final Account account) {
2539        if (databaseBackend.updateAccount(account)) {
2540            account.setShowErrorNotification(true);
2541            this.statusListener.onStatusChanged(account);
2542            databaseBackend.updateAccount(account);
2543            reconnectAccountInBackground(account);
2544            updateAccountUi();
2545            getNotificationService().updateErrorNotification();
2546            toggleForegroundService();
2547            syncEnabledAccountSetting();
2548            mChannelDiscoveryService.cleanCache();
2549            return true;
2550        } else {
2551            return false;
2552        }
2553    }
2554
2555    public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
2556        final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
2557        sendIqPacket(account, iq, (a, packet) -> {
2558            if (packet.getType() == IqPacket.TYPE.RESULT) {
2559                a.setPassword(newPassword);
2560                a.setOption(Account.OPTION_MAGIC_CREATE, false);
2561                databaseBackend.updateAccount(a);
2562                callback.onPasswordChangeSucceeded();
2563            } else {
2564                callback.onPasswordChangeFailed();
2565            }
2566        });
2567    }
2568
2569    public void unregisterAccount(final Account account, final Consumer<Boolean> callback) {
2570        final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
2571        final Element query = iqPacket.addChild("query",Namespace.REGISTER);
2572        query.addChild("remove");
2573        sendIqPacket(account, iqPacket, (a, response) -> {
2574            if (response.getType() == IqPacket.TYPE.RESULT) {
2575                deleteAccount(a);
2576                callback.accept(true);
2577            } else {
2578                callback.accept(false);
2579            }
2580        });
2581    }
2582
2583    public void deleteAccount(final Account account) {
2584        final boolean connected = account.getStatus() == Account.State.ONLINE;
2585        synchronized (this.conversations) {
2586            if (connected) {
2587                account.getAxolotlService().deleteOmemoIdentity();
2588            }
2589            for (final Conversation conversation : conversations) {
2590                if (conversation.getAccount() == account) {
2591                    if (conversation.getMode() == Conversation.MODE_MULTI) {
2592                        if (connected) {
2593                            leaveMuc(conversation);
2594                        }
2595                    }
2596                    conversations.remove(conversation);
2597                    mNotificationService.clear(conversation);
2598                }
2599            }
2600            if (account.getXmppConnection() != null) {
2601                new Thread(() -> disconnect(account, !connected)).start();
2602            }
2603            final Runnable runnable = () -> {
2604                if (!databaseBackend.deleteAccount(account)) {
2605                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
2606                }
2607            };
2608            mDatabaseWriterExecutor.execute(runnable);
2609            this.accounts.remove(account);
2610            this.mRosterSyncTaskManager.clear(account);
2611            updateAccountUi();
2612            mNotificationService.updateErrorNotification();
2613            syncEnabledAccountSetting();
2614            toggleForegroundService();
2615        }
2616    }
2617
2618    public void setOnConversationListChangedListener(OnConversationUpdate listener) {
2619        final boolean remainingListeners;
2620        synchronized (LISTENER_LOCK) {
2621            remainingListeners = checkListeners();
2622            if (!this.mOnConversationUpdates.add(listener)) {
2623                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as ConversationListChangedListener");
2624            }
2625            this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2626        }
2627        if (remainingListeners) {
2628            switchToForeground();
2629        }
2630    }
2631
2632    public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
2633        final boolean remainingListeners;
2634        synchronized (LISTENER_LOCK) {
2635            this.mOnConversationUpdates.remove(listener);
2636            this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2637            remainingListeners = checkListeners();
2638        }
2639        if (remainingListeners) {
2640            switchToBackground();
2641        }
2642    }
2643
2644    public void setOnShowErrorToastListener(OnShowErrorToast listener) {
2645        final boolean remainingListeners;
2646        synchronized (LISTENER_LOCK) {
2647            remainingListeners = checkListeners();
2648            if (!this.mOnShowErrorToasts.add(listener)) {
2649                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnShowErrorToastListener");
2650            }
2651        }
2652        if (remainingListeners) {
2653            switchToForeground();
2654        }
2655    }
2656
2657    public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
2658        final boolean remainingListeners;
2659        synchronized (LISTENER_LOCK) {
2660            this.mOnShowErrorToasts.remove(onShowErrorToast);
2661            remainingListeners = checkListeners();
2662        }
2663        if (remainingListeners) {
2664            switchToBackground();
2665        }
2666    }
2667
2668    public void setOnAccountListChangedListener(OnAccountUpdate listener) {
2669        final boolean remainingListeners;
2670        synchronized (LISTENER_LOCK) {
2671            remainingListeners = checkListeners();
2672            if (!this.mOnAccountUpdates.add(listener)) {
2673                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnAccountListChangedtListener");
2674            }
2675        }
2676        if (remainingListeners) {
2677            switchToForeground();
2678        }
2679    }
2680
2681    public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
2682        final boolean remainingListeners;
2683        synchronized (LISTENER_LOCK) {
2684            this.mOnAccountUpdates.remove(listener);
2685            remainingListeners = checkListeners();
2686        }
2687        if (remainingListeners) {
2688            switchToBackground();
2689        }
2690    }
2691
2692    public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2693        final boolean remainingListeners;
2694        synchronized (LISTENER_LOCK) {
2695            remainingListeners = checkListeners();
2696            if (!this.mOnCaptchaRequested.add(listener)) {
2697                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnCaptchaRequestListener");
2698            }
2699        }
2700        if (remainingListeners) {
2701            switchToForeground();
2702        }
2703    }
2704
2705    public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2706        final boolean remainingListeners;
2707        synchronized (LISTENER_LOCK) {
2708            this.mOnCaptchaRequested.remove(listener);
2709            remainingListeners = checkListeners();
2710        }
2711        if (remainingListeners) {
2712            switchToBackground();
2713        }
2714    }
2715
2716    public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
2717        final boolean remainingListeners;
2718        synchronized (LISTENER_LOCK) {
2719            remainingListeners = checkListeners();
2720            if (!this.mOnRosterUpdates.add(listener)) {
2721                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnRosterUpdateListener");
2722            }
2723        }
2724        if (remainingListeners) {
2725            switchToForeground();
2726        }
2727    }
2728
2729    public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
2730        final boolean remainingListeners;
2731        synchronized (LISTENER_LOCK) {
2732            this.mOnRosterUpdates.remove(listener);
2733            remainingListeners = checkListeners();
2734        }
2735        if (remainingListeners) {
2736            switchToBackground();
2737        }
2738    }
2739
2740    public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2741        final boolean remainingListeners;
2742        synchronized (LISTENER_LOCK) {
2743            remainingListeners = checkListeners();
2744            if (!this.mOnUpdateBlocklist.add(listener)) {
2745                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnUpdateBlocklistListener");
2746            }
2747        }
2748        if (remainingListeners) {
2749            switchToForeground();
2750        }
2751    }
2752
2753    public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2754        final boolean remainingListeners;
2755        synchronized (LISTENER_LOCK) {
2756            this.mOnUpdateBlocklist.remove(listener);
2757            remainingListeners = checkListeners();
2758        }
2759        if (remainingListeners) {
2760            switchToBackground();
2761        }
2762    }
2763
2764    public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2765        final boolean remainingListeners;
2766        synchronized (LISTENER_LOCK) {
2767            remainingListeners = checkListeners();
2768            if (!this.mOnKeyStatusUpdated.add(listener)) {
2769                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnKeyStatusUpdateListener");
2770            }
2771        }
2772        if (remainingListeners) {
2773            switchToForeground();
2774        }
2775    }
2776
2777    public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
2778        final boolean remainingListeners;
2779        synchronized (LISTENER_LOCK) {
2780            this.mOnKeyStatusUpdated.remove(listener);
2781            remainingListeners = checkListeners();
2782        }
2783        if (remainingListeners) {
2784            switchToBackground();
2785        }
2786    }
2787
2788    public void setOnRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
2789        final boolean remainingListeners;
2790        synchronized (LISTENER_LOCK) {
2791            remainingListeners = checkListeners();
2792            if (!this.onJingleRtpConnectionUpdate.add(listener)) {
2793                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnJingleRtpConnectionUpdate");
2794            }
2795        }
2796        if (remainingListeners) {
2797            switchToForeground();
2798        }
2799    }
2800
2801    public void removeRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
2802        final boolean remainingListeners;
2803        synchronized (LISTENER_LOCK) {
2804            this.onJingleRtpConnectionUpdate.remove(listener);
2805            remainingListeners = checkListeners();
2806        }
2807        if (remainingListeners) {
2808            switchToBackground();
2809        }
2810    }
2811
2812    public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2813        final boolean remainingListeners;
2814        synchronized (LISTENER_LOCK) {
2815            remainingListeners = checkListeners();
2816            if (!this.mOnMucRosterUpdate.add(listener)) {
2817                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnMucRosterListener");
2818            }
2819        }
2820        if (remainingListeners) {
2821            switchToForeground();
2822        }
2823    }
2824
2825    public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
2826        final boolean remainingListeners;
2827        synchronized (LISTENER_LOCK) {
2828            this.mOnMucRosterUpdate.remove(listener);
2829            remainingListeners = checkListeners();
2830        }
2831        if (remainingListeners) {
2832            switchToBackground();
2833        }
2834    }
2835
2836    public boolean checkListeners() {
2837        return (this.mOnAccountUpdates.size() == 0
2838                && this.mOnConversationUpdates.size() == 0
2839                && this.mOnRosterUpdates.size() == 0
2840                && this.mOnCaptchaRequested.size() == 0
2841                && this.mOnMucRosterUpdate.size() == 0
2842                && this.mOnUpdateBlocklist.size() == 0
2843                && this.mOnShowErrorToasts.size() == 0
2844                && this.onJingleRtpConnectionUpdate.size() == 0
2845                && this.mOnKeyStatusUpdated.size() == 0);
2846    }
2847
2848    private void switchToForeground() {
2849        toggleSoftDisabled(false);
2850        final boolean broadcastLastActivity = broadcastLastActivity();
2851        for (Conversation conversation : getConversations()) {
2852            if (conversation.getMode() == Conversation.MODE_MULTI) {
2853                conversation.getMucOptions().resetChatState();
2854            } else {
2855                conversation.setIncomingChatState(Config.DEFAULT_CHAT_STATE);
2856            }
2857        }
2858        for (Account account : getAccounts()) {
2859            if (account.getStatus() == Account.State.ONLINE) {
2860                account.deactivateGracePeriod();
2861                final XmppConnection connection = account.getXmppConnection();
2862                if (connection != null) {
2863                    if (connection.getFeatures().csi()) {
2864                        connection.sendActive();
2865                    }
2866                    if (broadcastLastActivity) {
2867                        sendPresence(account, false); //send new presence but don't include idle because we are not
2868                    }
2869                }
2870            }
2871        }
2872        Log.d(Config.LOGTAG, "app switched into foreground");
2873    }
2874
2875    private void switchToBackground() {
2876        final boolean broadcastLastActivity = broadcastLastActivity();
2877        if (broadcastLastActivity) {
2878            mLastActivity = System.currentTimeMillis();
2879            final SharedPreferences.Editor editor = getPreferences().edit();
2880            editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
2881            editor.apply();
2882        }
2883        for (Account account : getAccounts()) {
2884            if (account.getStatus() == Account.State.ONLINE) {
2885                XmppConnection connection = account.getXmppConnection();
2886                if (connection != null) {
2887                    if (broadcastLastActivity) {
2888                        sendPresence(account, true);
2889                    }
2890                    if (connection.getFeatures().csi()) {
2891                        connection.sendInactive();
2892                    }
2893                }
2894            }
2895        }
2896        this.mNotificationService.setIsInForeground(false);
2897        Log.d(Config.LOGTAG, "app switched into background");
2898    }
2899
2900    private void connectMultiModeConversations(Account account) {
2901        List<Conversation> conversations = getConversations();
2902        for (Conversation conversation : conversations) {
2903            if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2904                joinMuc(conversation);
2905            }
2906        }
2907    }
2908
2909    public void mucSelfPingAndRejoin(final Conversation conversation) {
2910        final Account account = conversation.getAccount();
2911        synchronized (account.inProgressConferenceJoins) {
2912            if (account.inProgressConferenceJoins.contains(conversation)) {
2913                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because join is already under way");
2914                return;
2915            }
2916        }
2917        synchronized (account.inProgressConferencePings) {
2918            if (!account.inProgressConferencePings.add(conversation)) {
2919                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because ping is already under way");
2920                return;
2921            }
2922        }
2923        final Jid self = conversation.getMucOptions().getSelf().getFullJid();
2924        final IqPacket ping = new IqPacket(IqPacket.TYPE.GET);
2925        ping.setTo(self);
2926        ping.addChild("ping", Namespace.PING);
2927        sendIqPacket(conversation.getAccount(), ping, (a, response) -> {
2928            if (response.getType() == IqPacket.TYPE.ERROR) {
2929                Element error = response.findChild("error");
2930                if (error == null || error.hasChild("service-unavailable") || error.hasChild("feature-not-implemented") || error.hasChild("item-not-found")) {
2931                    Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back as ignorable error");
2932                } else {
2933                    Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " failed. attempting rejoin");
2934                    joinMuc(conversation);
2935                }
2936            } else if (response.getType() == IqPacket.TYPE.RESULT) {
2937                Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back fine");
2938            }
2939            synchronized (account.inProgressConferencePings) {
2940                account.inProgressConferencePings.remove(conversation);
2941            }
2942        });
2943    }
2944    public void joinMuc(Conversation conversation) {
2945        joinMuc(conversation, null, false);
2946    }
2947
2948    public void joinMuc(Conversation conversation, boolean followedInvite) {
2949        joinMuc(conversation, null, followedInvite);
2950    }
2951
2952    private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2953        joinMuc(conversation, onConferenceJoined, false);
2954    }
2955
2956    private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2957        final Account account = conversation.getAccount();
2958        synchronized (account.pendingConferenceJoins) {
2959            account.pendingConferenceJoins.remove(conversation);
2960        }
2961        synchronized (account.pendingConferenceLeaves) {
2962            account.pendingConferenceLeaves.remove(conversation);
2963        }
2964        if (account.getStatus() == Account.State.ONLINE) {
2965            synchronized (account.inProgressConferenceJoins) {
2966                account.inProgressConferenceJoins.add(conversation);
2967            }
2968            if (Config.MUC_LEAVE_BEFORE_JOIN) {
2969                sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
2970            }
2971            conversation.resetMucOptions();
2972            if (onConferenceJoined != null) {
2973                conversation.getMucOptions().flagNoAutoPushConfiguration();
2974            }
2975            conversation.setHasMessagesLeftOnServer(false);
2976            fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2977
2978                private void join(Conversation conversation) {
2979                    Account account = conversation.getAccount();
2980                    final MucOptions mucOptions = conversation.getMucOptions();
2981
2982                    if (mucOptions.nonanonymous() && !mucOptions.membersOnly() && !conversation.getBooleanAttribute("accept_non_anonymous", false)) {
2983                        synchronized (account.inProgressConferenceJoins) {
2984                            account.inProgressConferenceJoins.remove(conversation);
2985                        }
2986                        mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
2987                        updateConversationUi();
2988                        if (onConferenceJoined != null) {
2989                            onConferenceJoined.onConferenceJoined(conversation);
2990                        }
2991                        return;
2992                    }
2993
2994                    final Jid joinJid = mucOptions.getSelf().getFullJid();
2995                    Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
2996                    PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
2997                    packet.setTo(joinJid);
2998                    Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2999                    if (conversation.getMucOptions().getPassword() != null) {
3000                        x.addChild("password").setContent(mucOptions.getPassword());
3001                    }
3002
3003                    if (mucOptions.mamSupport()) {
3004                        // Use MAM instead of the limited muc history to get history
3005                        x.addChild("history").setAttribute("maxchars", "0");
3006                    } else {
3007                        // Fallback to muc history
3008                        x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
3009                    }
3010                    sendPresencePacket(account, packet);
3011                    if (onConferenceJoined != null) {
3012                        onConferenceJoined.onConferenceJoined(conversation);
3013                    }
3014                    if (!joinJid.equals(conversation.getJid())) {
3015                        conversation.setContactJid(joinJid);
3016                        databaseBackend.updateConversation(conversation);
3017                    }
3018
3019                    if (mucOptions.mamSupport()) {
3020                        getMessageArchiveService().catchupMUC(conversation);
3021                    }
3022                    if (mucOptions.isPrivateAndNonAnonymous()) {
3023                        fetchConferenceMembers(conversation);
3024
3025                        if (followedInvite) {
3026                            final Bookmark bookmark = conversation.getBookmark();
3027                            if (bookmark != null) {
3028                                if (!bookmark.autojoin()) {
3029                                    bookmark.setAutojoin(true);
3030                                    createBookmark(account, bookmark);
3031                                }
3032                            } else {
3033                                saveConversationAsBookmark(conversation, null);
3034                            }
3035                        }
3036                    }
3037                    synchronized (account.inProgressConferenceJoins) {
3038                        account.inProgressConferenceJoins.remove(conversation);
3039                        sendUnsentMessages(conversation);
3040                    }
3041                }
3042
3043                @Override
3044                public void onConferenceConfigurationFetched(Conversation conversation) {
3045                    if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3046                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
3047                        return;
3048                    }
3049                    join(conversation);
3050                }
3051
3052                @Override
3053                public void onFetchFailed(final Conversation conversation, final String errorCondition) {
3054                    if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3055                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
3056                        return;
3057                    }
3058                    if ("remote-server-not-found".equals(errorCondition)) {
3059                        synchronized (account.inProgressConferenceJoins) {
3060                            account.inProgressConferenceJoins.remove(conversation);
3061                        }
3062                        conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
3063                        updateConversationUi();
3064                    } else {
3065                        join(conversation);
3066                        fetchConferenceConfiguration(conversation);
3067                    }
3068                }
3069            });
3070            updateConversationUi();
3071        } else {
3072            synchronized (account.pendingConferenceJoins) {
3073                account.pendingConferenceJoins.add(conversation);
3074            }
3075            conversation.resetMucOptions();
3076            conversation.setHasMessagesLeftOnServer(false);
3077            updateConversationUi();
3078        }
3079    }
3080
3081    private void fetchConferenceMembers(final Conversation conversation) {
3082        final Account account = conversation.getAccount();
3083        final AxolotlService axolotlService = account.getAxolotlService();
3084        final String[] affiliations = {"member", "admin", "owner"};
3085        OnIqPacketReceived callback = new OnIqPacketReceived() {
3086
3087            private int i = 0;
3088            private boolean success = true;
3089
3090            @Override
3091            public void onIqPacketReceived(Account account, IqPacket packet) {
3092                final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
3093                Element query = packet.query("http://jabber.org/protocol/muc#admin");
3094                if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
3095                    for (Element child : query.getChildren()) {
3096                        if ("item".equals(child.getName())) {
3097                            MucOptions.User user = AbstractParser.parseItem(conversation, child);
3098                            if (!user.realJidMatchesAccount()) {
3099                                boolean isNew = conversation.getMucOptions().updateUser(user);
3100                                Contact contact = user.getContact();
3101                                if (omemoEnabled
3102                                        && isNew
3103                                        && user.getRealJid() != null
3104                                        && (contact == null || !contact.mutualPresenceSubscription())
3105                                        && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
3106                                    axolotlService.fetchDeviceIds(user.getRealJid());
3107                                }
3108                            }
3109                        }
3110                    }
3111                } else {
3112                    success = false;
3113                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
3114                }
3115                ++i;
3116                if (i >= affiliations.length) {
3117                    List<Jid> members = conversation.getMucOptions().getMembers(true);
3118                    if (success) {
3119                        List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
3120                        boolean changed = false;
3121                        for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
3122                            Jid jid = iterator.next();
3123                            if (!members.contains(jid) && !members.contains(jid.getDomain())) {
3124                                iterator.remove();
3125                                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
3126                                changed = true;
3127                            }
3128                        }
3129                        if (changed) {
3130                            conversation.setAcceptedCryptoTargets(cryptoTargets);
3131                            updateConversation(conversation);
3132                        }
3133                    }
3134                    getAvatarService().clear(conversation);
3135                    updateMucRosterUi();
3136                    updateConversationUi();
3137                }
3138            }
3139        };
3140        for (String affiliation : affiliations) {
3141            sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
3142        }
3143        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
3144    }
3145
3146    public void providePasswordForMuc(Conversation conversation, String password) {
3147        if (conversation.getMode() == Conversation.MODE_MULTI) {
3148            conversation.getMucOptions().setPassword(password);
3149            if (conversation.getBookmark() != null) {
3150                final Bookmark bookmark = conversation.getBookmark();
3151                if (synchronizeWithBookmarks()) {
3152                    bookmark.setAutojoin(true);
3153                }
3154                createBookmark(conversation.getAccount(), bookmark);
3155            }
3156            updateConversation(conversation);
3157            joinMuc(conversation);
3158        }
3159    }
3160
3161    public void deleteAvatar(final Account account) {
3162        final AtomicBoolean executed = new AtomicBoolean(false);
3163        final Runnable onDeleted =
3164                () -> {
3165                    if (executed.compareAndSet(false, true)) {
3166                        account.setAvatar(null);
3167                        databaseBackend.updateAccount(account);
3168                        getAvatarService().clear(account);
3169                        updateAccountUi();
3170                    }
3171                };
3172        deleteVcardAvatar(account, onDeleted);
3173        deletePepNode(account, Namespace.AVATAR_DATA);
3174        deletePepNode(account, Namespace.AVATAR_METADATA, onDeleted);
3175    }
3176
3177    public void deletePepNode(final Account account, final String node) {
3178        deletePepNode(account, node, null);
3179    }
3180
3181    private void deletePepNode(final Account account, final String node, final Runnable runnable) {
3182        final IqPacket request = mIqGenerator.deleteNode(node);
3183        sendIqPacket(account, request, (a, packet) -> {
3184            if (packet.getType() == IqPacket.TYPE.RESULT) {
3185                Log.d(Config.LOGTAG,a.getJid().asBareJid()+": successfully deleted pep node "+node);
3186                if (runnable != null) {
3187                    runnable.run();
3188                }
3189            } else {
3190                Log.d(Config.LOGTAG,a.getJid().asBareJid()+": failed to delete "+ packet);
3191            }
3192        });
3193    }
3194
3195    private void deleteVcardAvatar(final Account account, @NonNull final Runnable runnable) {
3196        final IqPacket retrieveVcard = mIqGenerator.retrieveVcardAvatar(account.getJid().asBareJid());
3197        sendIqPacket(account, retrieveVcard, (a, response) -> {
3198            if (response.getType() != IqPacket.TYPE.RESULT) {
3199                Log.d(Config.LOGTAG,a.getJid().asBareJid()+": no vCard set. nothing to do");
3200                return;
3201            }
3202            final Element vcard = response.findChild("vCard", "vcard-temp");
3203            if (vcard == null) {
3204                Log.d(Config.LOGTAG,a.getJid().asBareJid()+": no vCard set. nothing to do");
3205                return;
3206            }
3207            Element photo = vcard.findChild("PHOTO");
3208            if (photo == null) {
3209                photo = vcard.addChild("PHOTO");
3210            }
3211            photo.clearChildren();
3212            IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3213            publication.setTo(a.getJid().asBareJid());
3214            publication.addChild(vcard);
3215            sendIqPacket(account, publication, (a1, publicationResponse) -> {
3216                if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3217                    Log.d(Config.LOGTAG,a1.getJid().asBareJid()+": successfully deleted vcard avatar");
3218                    runnable.run();
3219                } else {
3220                    Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
3221                }
3222            });
3223        });
3224    }
3225
3226    private boolean hasEnabledAccounts() {
3227        if (this.accounts == null) {
3228            return false;
3229        }
3230        for (final Account account : this.accounts) {
3231            if (account.isConnectionEnabled()) {
3232                return true;
3233            }
3234        }
3235        return false;
3236    }
3237
3238
3239    public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
3240        getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
3241    }
3242
3243    public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3244        getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
3245    }
3246
3247
3248    public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3249        new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
3250    }
3251
3252    public void persistSelfNick(MucOptions.User self) {
3253        final Conversation conversation = self.getConversation();
3254        final boolean tookProposedNickFromBookmark = conversation.getMucOptions().isTookProposedNickFromBookmark();
3255        Jid full = self.getFullJid();
3256        if (!full.equals(conversation.getJid())) {
3257            Log.d(Config.LOGTAG, "nick changed. updating");
3258            conversation.setContactJid(full);
3259            databaseBackend.updateConversation(conversation);
3260        }
3261
3262        final Bookmark bookmark = conversation.getBookmark();
3263        final String bookmarkedNick = bookmark == null ? null : bookmark.getNick();
3264        if (bookmark != null && (tookProposedNickFromBookmark || TextUtils.isEmpty(bookmarkedNick)) && !full.getResource().equals(bookmarkedNick)) {
3265            final Account account = conversation.getAccount();
3266            final String defaultNick = MucOptions.defaultNick(account);
3267            if (TextUtils.isEmpty(bookmarkedNick) && full.getResource().equals(defaultNick)) {
3268                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not overwrite empty bookmark nick with default nick for " + conversation.getJid().asBareJid());
3269                return;
3270            }
3271            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persist nick '" + full.getResource() + "' into bookmark for " + conversation.getJid().asBareJid());
3272            bookmark.setNick(full.getResource());
3273            createBookmark(bookmark.getAccount(), bookmark);
3274        }
3275    }
3276
3277    public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
3278        final MucOptions options = conversation.getMucOptions();
3279        final Jid joinJid = options.createJoinJid(nick);
3280        if (joinJid == null) {
3281            return false;
3282        }
3283        if (options.online()) {
3284            Account account = conversation.getAccount();
3285            options.setOnRenameListener(new OnRenameListener() {
3286
3287                @Override
3288                public void onSuccess() {
3289                    callback.success(conversation);
3290                }
3291
3292                @Override
3293                public void onFailure() {
3294                    callback.error(R.string.nick_in_use, conversation);
3295                }
3296            });
3297
3298            final PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous());
3299            packet.setTo(joinJid);
3300            sendPresencePacket(account, packet);
3301        } else {
3302            conversation.setContactJid(joinJid);
3303            databaseBackend.updateConversation(conversation);
3304            if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
3305                Bookmark bookmark = conversation.getBookmark();
3306                if (bookmark != null) {
3307                    bookmark.setNick(nick);
3308                    createBookmark(bookmark.getAccount(), bookmark);
3309                }
3310                joinMuc(conversation);
3311            }
3312        }
3313        return true;
3314    }
3315
3316    public void leaveMuc(Conversation conversation) {
3317        leaveMuc(conversation, false);
3318    }
3319
3320    private void leaveMuc(Conversation conversation, boolean now) {
3321        final Account account = conversation.getAccount();
3322        synchronized (account.pendingConferenceJoins) {
3323            account.pendingConferenceJoins.remove(conversation);
3324        }
3325        synchronized (account.pendingConferenceLeaves) {
3326            account.pendingConferenceLeaves.remove(conversation);
3327        }
3328        if (account.getStatus() == Account.State.ONLINE || now) {
3329            sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
3330            conversation.getMucOptions().setOffline();
3331            Bookmark bookmark = conversation.getBookmark();
3332            if (bookmark != null) {
3333                bookmark.setConversation(null);
3334            }
3335            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
3336        } else {
3337            synchronized (account.pendingConferenceLeaves) {
3338                account.pendingConferenceLeaves.add(conversation);
3339            }
3340        }
3341    }
3342
3343    public String findConferenceServer(final Account account) {
3344        String server;
3345        if (account.getXmppConnection() != null) {
3346            server = account.getXmppConnection().getMucServer();
3347            if (server != null) {
3348                return server;
3349            }
3350        }
3351        for (Account other : getAccounts()) {
3352            if (other != account && other.getXmppConnection() != null) {
3353                server = other.getXmppConnection().getMucServer();
3354                if (server != null) {
3355                    return server;
3356                }
3357            }
3358        }
3359        return null;
3360    }
3361
3362
3363    public void createPublicChannel(final Account account, final String name, final Jid address, final UiCallback<Conversation> callback) {
3364        joinMuc(findOrCreateConversation(account, address, true, false, true), conversation -> {
3365            final Bundle configuration = IqGenerator.defaultChannelConfiguration();
3366            if (!TextUtils.isEmpty(name)) {
3367                configuration.putString("muc#roomconfig_roomname", name);
3368            }
3369            pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3370                @Override
3371                public void onPushSucceeded() {
3372                    saveConversationAsBookmark(conversation, name);
3373                    callback.success(conversation);
3374                }
3375
3376                @Override
3377                public void onPushFailed() {
3378                    if (conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
3379                        callback.error(R.string.unable_to_set_channel_configuration, conversation);
3380                    } else {
3381                        callback.error(R.string.joined_an_existing_channel, conversation);
3382                    }
3383                }
3384            });
3385        });
3386    }
3387
3388    public boolean createAdhocConference(final Account account,
3389                                         final String name,
3390                                         final Iterable<Jid> jids,
3391                                         final UiCallback<Conversation> callback) {
3392        Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
3393        if (account.getStatus() == Account.State.ONLINE) {
3394            try {
3395                String server = findConferenceServer(account);
3396                if (server == null) {
3397                    if (callback != null) {
3398                        callback.error(R.string.no_conference_server_found, null);
3399                    }
3400                    return false;
3401                }
3402                final Jid jid = Jid.of(CryptoHelper.pronounceable(), server, null);
3403                final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
3404                joinMuc(conversation, new OnConferenceJoined() {
3405                    @Override
3406                    public void onConferenceJoined(final Conversation conversation) {
3407                        final Bundle configuration = IqGenerator.defaultGroupChatConfiguration();
3408                        if (!TextUtils.isEmpty(name)) {
3409                            configuration.putString("muc#roomconfig_roomname", name);
3410                        }
3411                        pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3412                            @Override
3413                            public void onPushSucceeded() {
3414                                for (Jid invite : jids) {
3415                                    invite(conversation, invite);
3416                                }
3417                                for (String resource : account.getSelfContact().getPresences().toResourceArray()) {
3418                                    Jid other = account.getJid().withResource(resource);
3419                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending direct invite to " + other);
3420                                    directInvite(conversation, other);
3421                                }
3422                                saveConversationAsBookmark(conversation, name);
3423                                if (callback != null) {
3424                                    callback.success(conversation);
3425                                }
3426                            }
3427
3428                            @Override
3429                            public void onPushFailed() {
3430                                archiveConversation(conversation);
3431                                if (callback != null) {
3432                                    callback.error(R.string.conference_creation_failed, conversation);
3433                                }
3434                            }
3435                        });
3436                    }
3437                });
3438                return true;
3439            } catch (IllegalArgumentException e) {
3440                if (callback != null) {
3441                    callback.error(R.string.conference_creation_failed, null);
3442                }
3443                return false;
3444            }
3445        } else {
3446            if (callback != null) {
3447                callback.error(R.string.not_connected_try_again, null);
3448            }
3449            return false;
3450        }
3451    }
3452
3453    public void fetchConferenceConfiguration(final Conversation conversation) {
3454        fetchConferenceConfiguration(conversation, null);
3455    }
3456
3457    public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
3458        IqPacket request = mIqGenerator.queryDiscoInfo(conversation.getJid().asBareJid());
3459        sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3460            @Override
3461            public void onIqPacketReceived(Account account, IqPacket packet) {
3462                if (packet.getType() == IqPacket.TYPE.RESULT) {
3463                    final MucOptions mucOptions = conversation.getMucOptions();
3464                    final Bookmark bookmark = conversation.getBookmark();
3465                    final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
3466
3467                    if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
3468                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
3469                        updateConversation(conversation);
3470                    }
3471
3472                    if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
3473                        if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
3474                            createBookmark(account, bookmark);
3475                        }
3476                    }
3477
3478
3479                    if (callback != null) {
3480                        callback.onConferenceConfigurationFetched(conversation);
3481                    }
3482
3483
3484                    updateConversationUi();
3485                } else if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
3486                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received timeout waiting for conference configuration fetch");
3487                } else {
3488                    if (callback != null) {
3489                        callback.onFetchFailed(conversation, packet.getErrorCondition());
3490                    }
3491                }
3492            }
3493        });
3494    }
3495
3496    public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
3497        pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
3498    }
3499
3500    public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
3501        Log.d(Config.LOGTAG, "pushing node configuration");
3502        sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
3503            @Override
3504            public void onIqPacketReceived(Account account, IqPacket packet) {
3505                if (packet.getType() == IqPacket.TYPE.RESULT) {
3506                    Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
3507                    Element configuration = pubsub == null ? null : pubsub.findChild("configure");
3508                    Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
3509                    if (x != null) {
3510                        Data data = Data.parse(x);
3511                        data.submit(options);
3512                        sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
3513                            @Override
3514                            public void onIqPacketReceived(Account account, IqPacket packet) {
3515                                if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
3516                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully changed node configuration for node " + node);
3517                                    callback.onPushSucceeded();
3518                                } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3519                                    callback.onPushFailed();
3520                                }
3521                            }
3522                        });
3523                    } else if (callback != null) {
3524                        callback.onPushFailed();
3525                    }
3526                } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3527                    callback.onPushFailed();
3528                }
3529            }
3530        });
3531    }
3532
3533    public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
3534        if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
3535            conversation.setAttribute("accept_non_anonymous", true);
3536            updateConversation(conversation);
3537        }
3538        if (options.containsKey("muc#roomconfig_moderatedroom")) {
3539            final boolean moderated = "1".equals(options.getString("muc#roomconfig_moderatedroom"));
3540            options.putString("members_by_default", moderated ? "0" : "1");
3541        }
3542        final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3543        request.setTo(conversation.getJid().asBareJid());
3544        request.query("http://jabber.org/protocol/muc#owner");
3545        sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3546            @Override
3547            public void onIqPacketReceived(Account account, IqPacket packet) {
3548                if (packet.getType() == IqPacket.TYPE.RESULT) {
3549                    final Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
3550                    data.submit(options);
3551                    final IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3552                    set.setTo(conversation.getJid().asBareJid());
3553                    set.query("http://jabber.org/protocol/muc#owner").addChild(data);
3554                    sendIqPacket(account, set, new OnIqPacketReceived() {
3555                        @Override
3556                        public void onIqPacketReceived(Account account, IqPacket packet) {
3557                            if (callback != null) {
3558                                if (packet.getType() == IqPacket.TYPE.RESULT) {
3559                                    callback.onPushSucceeded();
3560                                } else {
3561                                    callback.onPushFailed();
3562                                }
3563                            }
3564                        }
3565                    });
3566                } else {
3567                    if (callback != null) {
3568                        callback.onPushFailed();
3569                    }
3570                }
3571            }
3572        });
3573    }
3574
3575    public void pushSubjectToConference(final Conversation conference, final String subject) {
3576        MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
3577        this.sendMessagePacket(conference.getAccount(), packet);
3578    }
3579
3580    public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
3581        final Jid jid = user.asBareJid();
3582        final IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
3583        sendIqPacket(conference.getAccount(), request, (account, response) -> {
3584            if (response.getType() == IqPacket.TYPE.RESULT) {
3585                conference.getMucOptions().changeAffiliation(jid, affiliation);
3586                getAvatarService().clear(conference);
3587                if (callback != null) {
3588                    callback.onAffiliationChangedSuccessful(jid);
3589                } else {
3590                    Log.d(Config.LOGTAG, "changed affiliation of " + user + " to " + affiliation);
3591                }
3592            } else if (callback != null) {
3593                callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
3594            } else {
3595                Log.d(Config.LOGTAG, "unable to change affiliation");
3596            }
3597        });
3598    }
3599
3600    public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) {
3601        IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
3602        sendIqPacket(conference.getAccount(), request, (account, packet) -> {
3603            if (packet.getType() != IqPacket.TYPE.RESULT) {
3604                Log.d(Config.LOGTAG, account.getJid().asBareJid() + " unable to change role of " + nick);
3605            }
3606        });
3607    }
3608
3609    public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
3610        IqPacket request = new IqPacket(IqPacket.TYPE.SET);
3611        request.setTo(conversation.getJid().asBareJid());
3612        request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
3613        sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3614            @Override
3615            public void onIqPacketReceived(Account account, IqPacket packet) {
3616                if (packet.getType() == IqPacket.TYPE.RESULT) {
3617                    if (callback != null) {
3618                        callback.onRoomDestroySucceeded();
3619                    }
3620                } else if (packet.getType() == IqPacket.TYPE.ERROR) {
3621                    if (callback != null) {
3622                        callback.onRoomDestroyFailed();
3623                    }
3624                }
3625            }
3626        });
3627    }
3628
3629    private void disconnect(final Account account, boolean force) {
3630        final XmppConnection connection = account.getXmppConnection();
3631        if (connection == null) {
3632            return;
3633        }
3634        if (!force) {
3635            final List<Conversation> conversations = getConversations();
3636            for (Conversation conversation : conversations) {
3637                if (conversation.getAccount() == account) {
3638                    if (conversation.getMode() == Conversation.MODE_MULTI) {
3639                        leaveMuc(conversation, true);
3640                    }
3641                }
3642            }
3643            sendOfflinePresence(account);
3644        }
3645        connection.disconnect(force);
3646    }
3647
3648    @Override
3649    public IBinder onBind(Intent intent) {
3650        return mBinder;
3651    }
3652
3653    public void updateMessage(Message message) {
3654        updateMessage(message, true);
3655    }
3656
3657    public void updateMessage(Message message, boolean includeBody) {
3658        databaseBackend.updateMessage(message, includeBody);
3659        updateConversationUi();
3660    }
3661
3662    public void createMessageAsync(final Message message) {
3663        mDatabaseWriterExecutor.execute(() -> databaseBackend.createMessage(message));
3664    }
3665
3666    public void updateMessage(Message message, String uuid) {
3667        if (!databaseBackend.updateMessage(message, uuid)) {
3668            Log.e(Config.LOGTAG, "error updated message in DB after edit");
3669        }
3670        updateConversationUi();
3671    }
3672
3673    protected void syncDirtyContacts(Account account) {
3674        for (Contact contact : account.getRoster().getContacts()) {
3675            if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
3676                pushContactToServer(contact);
3677            }
3678            if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
3679                deleteContactOnServer(contact);
3680            }
3681        }
3682    }
3683
3684    public void createContact(final Contact contact, final boolean autoGrant) {
3685        createContact(contact, autoGrant, null);
3686    }
3687
3688    public void createContact(final Contact contact, final boolean autoGrant, final String preAuth) {
3689        if (autoGrant) {
3690            contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
3691            contact.setOption(Contact.Options.ASKING);
3692        }
3693        pushContactToServer(contact, preAuth);
3694    }
3695
3696    public void pushContactToServer(final Contact contact) {
3697        pushContactToServer(contact, null);
3698    }
3699
3700    private void pushContactToServer(final Contact contact, final String preAuth) {
3701        contact.resetOption(Contact.Options.DIRTY_DELETE);
3702        contact.setOption(Contact.Options.DIRTY_PUSH);
3703        final Account account = contact.getAccount();
3704        if (account.getStatus() == Account.State.ONLINE) {
3705            final boolean ask = contact.getOption(Contact.Options.ASKING);
3706            final boolean sendUpdates = contact
3707                    .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
3708                    && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
3709            final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3710            iq.query(Namespace.ROSTER).addChild(contact.asElement());
3711            account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3712            if (sendUpdates) {
3713                sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
3714            }
3715            if (ask) {
3716                sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact, preAuth));
3717            }
3718        } else {
3719            syncRoster(contact.getAccount());
3720        }
3721    }
3722
3723    public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
3724        new Thread(() -> {
3725            final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3726            final int size = Config.AVATAR_SIZE;
3727            final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3728            if (avatar != null) {
3729                if (!getFileBackend().save(avatar)) {
3730                    callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3731                    return;
3732                }
3733                avatar.owner = conversation.getJid().asBareJid();
3734                publishMucAvatar(conversation, avatar, callback);
3735            } else {
3736                callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3737            }
3738        }).start();
3739    }
3740
3741    public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
3742        new Thread(() -> {
3743            final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3744            final int size = Config.AVATAR_SIZE;
3745            final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3746            if (avatar != null) {
3747                if (!getFileBackend().save(avatar)) {
3748                    Log.d(Config.LOGTAG, "unable to save vcard");
3749                    callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3750                    return;
3751                }
3752                publishAvatar(account, avatar, callback);
3753            } else {
3754                callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3755            }
3756        }).start();
3757
3758    }
3759
3760    private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
3761        final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
3762        sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
3763            boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
3764            if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
3765                Element vcard = response.findChild("vCard", "vcard-temp");
3766                if (vcard == null) {
3767                    vcard = new Element("vCard", "vcard-temp");
3768                }
3769                Element photo = vcard.findChild("PHOTO");
3770                if (photo == null) {
3771                    photo = vcard.addChild("PHOTO");
3772                }
3773                photo.clearChildren();
3774                photo.addChild("TYPE").setContent(avatar.type);
3775                photo.addChild("BINVAL").setContent(avatar.image);
3776                IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3777                publication.setTo(conversation.getJid().asBareJid());
3778                publication.addChild(vcard);
3779                sendIqPacket(account, publication, (a1, publicationResponse) -> {
3780                    if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3781                        callback.onAvatarPublicationSucceeded();
3782                    } else {
3783                        Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
3784                        callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3785                    }
3786                });
3787            } else {
3788                Log.d(Config.LOGTAG, "failed to request vcard " + response);
3789                callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
3790            }
3791        });
3792    }
3793
3794    public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
3795        final Bundle options;
3796        if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
3797            options = PublishOptions.openAccess();
3798        } else {
3799            options = null;
3800        }
3801        publishAvatar(account, avatar, options, true, callback);
3802    }
3803
3804    public void publishAvatar(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3805        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": publishing avatar. options=" + options);
3806        IqPacket packet = this.mIqGenerator.publishAvatar(avatar, options);
3807        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3808
3809            @Override
3810            public void onIqPacketReceived(Account account, IqPacket result) {
3811                if (result.getType() == IqPacket.TYPE.RESULT) {
3812                    publishAvatarMetadata(account, avatar, options, true, callback);
3813                } else if (retry && PublishOptions.preconditionNotMet(result)) {
3814                    pushNodeConfiguration(account, Namespace.AVATAR_DATA, options, new OnConfigurationPushed() {
3815                        @Override
3816                        public void onPushSucceeded() {
3817                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar node");
3818                            publishAvatar(account, avatar, options, false, callback);
3819                        }
3820
3821                        @Override
3822                        public void onPushFailed() {
3823                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar node");
3824                            publishAvatar(account, avatar, null, false, callback);
3825                        }
3826                    });
3827                } else {
3828                    Element error = result.findChild("error");
3829                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
3830                    if (callback != null) {
3831                        callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3832                    }
3833                }
3834            }
3835        });
3836    }
3837
3838    public void publishAvatarMetadata(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3839        final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
3840        sendIqPacket(account, packet, new OnIqPacketReceived() {
3841            @Override
3842            public void onIqPacketReceived(Account account, IqPacket result) {
3843                if (result.getType() == IqPacket.TYPE.RESULT) {
3844                    if (account.setAvatar(avatar.getFilename())) {
3845                        getAvatarService().clear(account);
3846                        databaseBackend.updateAccount(account);
3847                        notifyAccountAvatarHasChanged(account);
3848                    }
3849                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
3850                    if (callback != null) {
3851                        callback.onAvatarPublicationSucceeded();
3852                    }
3853                } else if (retry && PublishOptions.preconditionNotMet(result)) {
3854                    pushNodeConfiguration(account, Namespace.AVATAR_METADATA, options, new OnConfigurationPushed() {
3855                        @Override
3856                        public void onPushSucceeded() {
3857                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar meta data node");
3858                            publishAvatarMetadata(account, avatar, options, false, callback);
3859                        }
3860
3861                        @Override
3862                        public void onPushFailed() {
3863                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar meta data node");
3864                            publishAvatarMetadata(account, avatar, null, false, callback);
3865                        }
3866                    });
3867                } else {
3868                    if (callback != null) {
3869                        callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3870                    }
3871                }
3872            }
3873        });
3874    }
3875
3876    public void republishAvatarIfNeeded(Account account) {
3877        if (account.getAxolotlService().isPepBroken()) {
3878            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
3879            return;
3880        }
3881        IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3882        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3883
3884            private Avatar parseAvatar(IqPacket packet) {
3885                Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3886                if (pubsub != null) {
3887                    Element items = pubsub.findChild("items");
3888                    if (items != null) {
3889                        return Avatar.parseMetadata(items);
3890                    }
3891                }
3892                return null;
3893            }
3894
3895            private boolean errorIsItemNotFound(IqPacket packet) {
3896                Element error = packet.findChild("error");
3897                return packet.getType() == IqPacket.TYPE.ERROR
3898                        && error != null
3899                        && error.hasChild("item-not-found");
3900            }
3901
3902            @Override
3903            public void onIqPacketReceived(Account account, IqPacket packet) {
3904                if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
3905                    Avatar serverAvatar = parseAvatar(packet);
3906                    if (serverAvatar == null && account.getAvatar() != null) {
3907                        Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
3908                        if (avatar != null) {
3909                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
3910                            publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
3911                        } else {
3912                            Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
3913                        }
3914                    }
3915                }
3916            }
3917        });
3918    }
3919
3920    public void fetchAvatar(Account account, Avatar avatar) {
3921        fetchAvatar(account, avatar, null);
3922    }
3923
3924    public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3925        final String KEY = generateFetchKey(account, avatar);
3926        synchronized (this.mInProgressAvatarFetches) {
3927            if (mInProgressAvatarFetches.add(KEY)) {
3928                switch (avatar.origin) {
3929                    case PEP:
3930                        this.mInProgressAvatarFetches.add(KEY);
3931                        fetchAvatarPep(account, avatar, callback);
3932                        break;
3933                    case VCARD:
3934                        this.mInProgressAvatarFetches.add(KEY);
3935                        fetchAvatarVcard(account, avatar, callback);
3936                        break;
3937                }
3938            } else if (avatar.origin == Avatar.Origin.PEP) {
3939                mOmittedPepAvatarFetches.add(KEY);
3940            } else {
3941                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": already fetching " + avatar.origin + " avatar for " + avatar.owner);
3942            }
3943        }
3944    }
3945
3946    private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3947        IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
3948        sendIqPacket(account, packet, (a, result) -> {
3949            synchronized (mInProgressAvatarFetches) {
3950                mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
3951            }
3952            final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
3953            if (result.getType() == IqPacket.TYPE.RESULT) {
3954                avatar.image = mIqParser.avatarData(result);
3955                if (avatar.image != null) {
3956                    if (getFileBackend().save(avatar)) {
3957                        if (a.getJid().asBareJid().equals(avatar.owner)) {
3958                            if (a.setAvatar(avatar.getFilename())) {
3959                                databaseBackend.updateAccount(a);
3960                            }
3961                            getAvatarService().clear(a);
3962                            updateConversationUi();
3963                            updateAccountUi();
3964                        } else {
3965                            final Contact contact = a.getRoster().getContact(avatar.owner);
3966                            contact.setAvatar(avatar);
3967                            syncRoster(account);
3968                            getAvatarService().clear(contact);
3969                            updateConversationUi();
3970                            updateRosterUi();
3971                        }
3972                        if (callback != null) {
3973                            callback.success(avatar);
3974                        }
3975                        Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": successfully fetched pep avatar for " + avatar.owner);
3976                        return;
3977                    }
3978                } else {
3979
3980                    Log.d(Config.LOGTAG, ERROR + "(parsing error)");
3981                }
3982            } else {
3983                Element error = result.findChild("error");
3984                if (error == null) {
3985                    Log.d(Config.LOGTAG, ERROR + "(server error)");
3986                } else {
3987                    Log.d(Config.LOGTAG, ERROR + error.toString());
3988                }
3989            }
3990            if (callback != null) {
3991                callback.error(0, null);
3992            }
3993
3994        });
3995    }
3996
3997    private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3998        IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
3999        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4000            @Override
4001            public void onIqPacketReceived(Account account, IqPacket packet) {
4002                final boolean previouslyOmittedPepFetch;
4003                synchronized (mInProgressAvatarFetches) {
4004                    final String KEY = generateFetchKey(account, avatar);
4005                    mInProgressAvatarFetches.remove(KEY);
4006                    previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
4007                }
4008                if (packet.getType() == IqPacket.TYPE.RESULT) {
4009                    Element vCard = packet.findChild("vCard", "vcard-temp");
4010                    Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
4011                    String image = photo != null ? photo.findChildContent("BINVAL") : null;
4012                    if (image != null) {
4013                        avatar.image = image;
4014                        if (getFileBackend().save(avatar)) {
4015                            Log.d(Config.LOGTAG, account.getJid().asBareJid()
4016                                    + ": successfully fetched vCard avatar for " + avatar.owner + " omittedPep=" + previouslyOmittedPepFetch);
4017                            if (avatar.owner.isBareJid()) {
4018                                if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
4019                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
4020                                    account.setAvatar(avatar.getFilename());
4021                                    databaseBackend.updateAccount(account);
4022                                    getAvatarService().clear(account);
4023                                    updateAccountUi();
4024                                } else {
4025                                    final Contact contact = account.getRoster().getContact(avatar.owner);
4026                                    contact.setAvatar(avatar, previouslyOmittedPepFetch);
4027                                    syncRoster(account);
4028                                    getAvatarService().clear(contact);
4029                                    updateRosterUi();
4030                                }
4031                                updateConversationUi();
4032                            } else {
4033                                Conversation conversation = find(account, avatar.owner.asBareJid());
4034                                if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
4035                                    MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
4036                                    if (user != null) {
4037                                        if (user.setAvatar(avatar)) {
4038                                            getAvatarService().clear(user);
4039                                            updateConversationUi();
4040                                            updateMucRosterUi();
4041                                        }
4042                                        if (user.getRealJid() != null) {
4043                                            Contact contact = account.getRoster().getContact(user.getRealJid());
4044                                            contact.setAvatar(avatar);
4045                                            syncRoster(account);
4046                                            getAvatarService().clear(contact);
4047                                            updateRosterUi();
4048                                        }
4049                                    }
4050                                }
4051                            }
4052                        }
4053                    }
4054                }
4055            }
4056        });
4057    }
4058
4059    public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
4060        IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4061        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4062
4063            @Override
4064            public void onIqPacketReceived(Account account, IqPacket packet) {
4065                if (packet.getType() == IqPacket.TYPE.RESULT) {
4066                    Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
4067                    if (pubsub != null) {
4068                        Element items = pubsub.findChild("items");
4069                        if (items != null) {
4070                            Avatar avatar = Avatar.parseMetadata(items);
4071                            if (avatar != null) {
4072                                avatar.owner = account.getJid().asBareJid();
4073                                if (fileBackend.isAvatarCached(avatar)) {
4074                                    if (account.setAvatar(avatar.getFilename())) {
4075                                        databaseBackend.updateAccount(account);
4076                                    }
4077                                    getAvatarService().clear(account);
4078                                    callback.success(avatar);
4079                                } else {
4080                                    fetchAvatarPep(account, avatar, callback);
4081                                }
4082                                return;
4083                            }
4084                        }
4085                    }
4086                }
4087                callback.error(0, null);
4088            }
4089        });
4090    }
4091
4092    public void notifyAccountAvatarHasChanged(final Account account) {
4093        final XmppConnection connection = account.getXmppConnection();
4094        if (connection != null && connection.getFeatures().bookmarksConversion()) {
4095            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar changed. resending presence to online group chats");
4096            for (Conversation conversation : conversations) {
4097                if (conversation.getAccount() == account && conversation.getMode() == Conversational.MODE_MULTI) {
4098                    final MucOptions mucOptions = conversation.getMucOptions();
4099                    if (mucOptions.online()) {
4100                        PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous());
4101                        packet.setTo(mucOptions.getSelf().getFullJid());
4102                        connection.sendPresencePacket(packet);
4103                    }
4104                }
4105            }
4106        }
4107    }
4108
4109    public void deleteContactOnServer(Contact contact) {
4110        contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
4111        contact.resetOption(Contact.Options.DIRTY_PUSH);
4112        contact.setOption(Contact.Options.DIRTY_DELETE);
4113        Account account = contact.getAccount();
4114        if (account.getStatus() == Account.State.ONLINE) {
4115            IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
4116            Element item = iq.query(Namespace.ROSTER).addChild("item");
4117            item.setAttribute("jid", contact.getJid());
4118            item.setAttribute("subscription", "remove");
4119            account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
4120        }
4121    }
4122
4123    public void updateConversation(final Conversation conversation) {
4124        mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
4125    }
4126
4127    private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
4128        synchronized (account) {
4129            final XmppConnection existingConnection = account.getXmppConnection();
4130            final XmppConnection connection;
4131            if (existingConnection != null) {
4132                connection = existingConnection;
4133            } else if (account.isConnectionEnabled()) {
4134                connection = createConnection(account);
4135                account.setXmppConnection(connection);
4136            } else {
4137                return;
4138            }
4139            final boolean hasInternet = hasInternetConnection();
4140            if (account.isConnectionEnabled() && hasInternet) {
4141                if (!force) {
4142                    disconnect(account, false);
4143                }
4144                Thread thread = new Thread(connection);
4145                connection.setInteractive(interactive);
4146                connection.prepareNewConnection();
4147                connection.interrupt();
4148                thread.start();
4149                scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
4150            } else {
4151                disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
4152                account.getRoster().clearPresences();
4153                connection.resetEverything();
4154                final AxolotlService axolotlService = account.getAxolotlService();
4155                if (axolotlService != null) {
4156                    axolotlService.resetBrokenness();
4157                }
4158                if (!hasInternet) {
4159                    account.setStatus(Account.State.NO_INTERNET);
4160                }
4161            }
4162        }
4163    }
4164
4165    public void reconnectAccountInBackground(final Account account) {
4166        new Thread(() -> reconnectAccount(account, false, true)).start();
4167    }
4168
4169    public void invite(final Conversation conversation, final Jid contact) {
4170        Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
4171        final MucOptions.User user = conversation.getMucOptions().findUserByRealJid(contact.asBareJid());
4172        if (user == null || user.getAffiliation() == MucOptions.Affiliation.OUTCAST) {
4173            changeAffiliationInConference(conversation, contact, MucOptions.Affiliation.NONE, null);
4174        }
4175        final MessagePacket packet = mMessageGenerator.invite(conversation, contact);
4176        sendMessagePacket(conversation.getAccount(), packet);
4177    }
4178
4179    public void directInvite(Conversation conversation, Jid jid) {
4180        MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
4181        sendMessagePacket(conversation.getAccount(), packet);
4182    }
4183
4184    public void resetSendingToWaiting(Account account) {
4185        for (Conversation conversation : getConversations()) {
4186            if (conversation.getAccount() == account) {
4187                conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
4188            }
4189        }
4190    }
4191
4192    public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
4193        return markMessage(account, recipient, uuid, status, null);
4194    }
4195
4196    public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
4197        if (uuid == null) {
4198            return null;
4199        }
4200        for (Conversation conversation : getConversations()) {
4201            if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
4202                final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
4203                if (message != null) {
4204                    markMessage(message, status, errorMessage);
4205                }
4206                return message;
4207            }
4208        }
4209        return null;
4210    }
4211
4212    public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId) {
4213        return markMessage(conversation, uuid, status, serverMessageId, null);
4214    }
4215
4216    public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId, final LocalizedContent body) {
4217        if (uuid == null) {
4218            return false;
4219        } else {
4220            final Message message = conversation.findSentMessageWithUuid(uuid);
4221            if (message != null) {
4222                if (message.getServerMsgId() == null) {
4223                    message.setServerMsgId(serverMessageId);
4224                }
4225                if (message.getEncryption() == Message.ENCRYPTION_NONE
4226                        && message.isTypeText()
4227                        && isBodyModified(message, body)) {
4228                    message.setBody(body.content);
4229                    if (body.count > 1) {
4230                        message.setBodyLanguage(body.language);
4231                    }
4232                    markMessage(message, status, null, true);
4233                } else {
4234                    markMessage(message, status);
4235                }
4236                return true;
4237            } else {
4238                return false;
4239            }
4240        }
4241    }
4242
4243    private static boolean isBodyModified(final Message message, final LocalizedContent body) {
4244        if (body == null || body.content == null) {
4245            return false;
4246        }
4247        return !body.content.equals(message.getBody());
4248    }
4249
4250    public void markMessage(Message message, int status) {
4251        markMessage(message, status, null);
4252    }
4253
4254
4255    public void markMessage(final Message message, final int status, final String errorMessage) {
4256        markMessage(message, status, errorMessage, false);
4257    }
4258
4259    public void markMessage(final Message message, final int status, final String errorMessage, final boolean includeBody) {
4260        final int oldStatus = message.getStatus();
4261        if (status == Message.STATUS_SEND_FAILED && (oldStatus == Message.STATUS_SEND_RECEIVED || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
4262            return;
4263        }
4264        if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
4265            return;
4266        }
4267        message.setErrorMessage(errorMessage);
4268        message.setStatus(status);
4269        databaseBackend.updateMessage(message, includeBody);
4270        updateConversationUi();
4271        if (oldStatus != status && status == Message.STATUS_SEND_FAILED) {
4272            mNotificationService.pushFailedDelivery(message);
4273        }
4274    }
4275
4276    private SharedPreferences getPreferences() {
4277        return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
4278    }
4279
4280    public long getAutomaticMessageDeletionDate() {
4281        final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
4282        return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
4283    }
4284
4285    public long getLongPreference(String name, @IntegerRes int res) {
4286        long defaultValue = getResources().getInteger(res);
4287        try {
4288            return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
4289        } catch (NumberFormatException e) {
4290            return defaultValue;
4291        }
4292    }
4293
4294    public boolean getBooleanPreference(String name, @BoolRes int res) {
4295        return getPreferences().getBoolean(name, getResources().getBoolean(res));
4296    }
4297
4298    public boolean confirmMessages() {
4299        return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
4300    }
4301
4302    public boolean allowMessageCorrection() {
4303        return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
4304    }
4305
4306    public boolean sendChatStates() {
4307        return getBooleanPreference("chat_states", R.bool.chat_states);
4308    }
4309
4310    private boolean synchronizeWithBookmarks() {
4311        return getBooleanPreference("autojoin", R.bool.autojoin);
4312    }
4313
4314    public boolean useTorToConnect() {
4315        return QuickConversationsService.isConversations() && getBooleanPreference("use_tor", R.bool.use_tor);
4316    }
4317
4318    public boolean showExtendedConnectionOptions() {
4319        return QuickConversationsService.isConversations() && getBooleanPreference("show_connection_options", R.bool.show_connection_options);
4320    }
4321
4322    public boolean broadcastLastActivity() {
4323        return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
4324    }
4325
4326    public int unreadCount() {
4327        int count = 0;
4328        for (Conversation conversation : getConversations()) {
4329            count += conversation.unreadCount();
4330        }
4331        return count;
4332    }
4333
4334
4335    private <T> List<T> threadSafeList(Set<T> set) {
4336        synchronized (LISTENER_LOCK) {
4337            return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
4338        }
4339    }
4340
4341    public void showErrorToastInUi(int resId) {
4342        for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
4343            listener.onShowErrorToast(resId);
4344        }
4345    }
4346
4347    public void updateConversationUi() {
4348        for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
4349            listener.onConversationUpdate();
4350        }
4351    }
4352
4353    public void notifyJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state) {
4354        for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4355            listener.onJingleRtpConnectionUpdate(account, with, sessionId, state);
4356        }
4357    }
4358
4359    public void notifyJingleRtpConnectionUpdate(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
4360        for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4361            listener.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
4362        }
4363    }
4364
4365    public void updateAccountUi() {
4366        for (final OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
4367            listener.onAccountUpdate();
4368        }
4369    }
4370
4371    public void updateRosterUi() {
4372        for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
4373            listener.onRosterUpdate();
4374        }
4375    }
4376
4377    public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
4378        if (mOnCaptchaRequested.size() > 0) {
4379            DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
4380            Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
4381                    (int) (captcha.getHeight() * metrics.scaledDensity), false);
4382            for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
4383                listener.onCaptchaRequested(account, id, data, scaled);
4384            }
4385            return true;
4386        }
4387        return false;
4388    }
4389
4390    public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
4391        for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
4392            listener.OnUpdateBlocklist(status);
4393        }
4394    }
4395
4396    public void updateMucRosterUi() {
4397        for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
4398            listener.onMucRosterUpdate();
4399        }
4400    }
4401
4402    public void keyStatusUpdated(AxolotlService.FetchStatus report) {
4403        for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
4404            listener.onKeyStatusUpdated(report);
4405        }
4406    }
4407
4408    public Account findAccountByJid(final Jid jid) {
4409        for (final Account account : this.accounts) {
4410            if (account.getJid().asBareJid().equals(jid.asBareJid())) {
4411                return account;
4412            }
4413        }
4414        return null;
4415    }
4416
4417    public Account findAccountByUuid(final String uuid) {
4418        for (Account account : this.accounts) {
4419            if (account.getUuid().equals(uuid)) {
4420                return account;
4421            }
4422        }
4423        return null;
4424    }
4425
4426    public Conversation findConversationByUuid(String uuid) {
4427        for (Conversation conversation : getConversations()) {
4428            if (conversation.getUuid().equals(uuid)) {
4429                return conversation;
4430            }
4431        }
4432        return null;
4433    }
4434
4435    public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
4436        List<Conversation> findings = new ArrayList<>();
4437        for (Conversation c : getConversations()) {
4438            if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
4439                findings.add(c);
4440            }
4441        }
4442        return findings.size() == 1 ? findings.get(0) : null;
4443    }
4444
4445    public boolean markRead(final Conversation conversation, boolean dismiss) {
4446        return markRead(conversation, null, dismiss).size() > 0;
4447    }
4448
4449    public void markRead(final Conversation conversation) {
4450        markRead(conversation, null, true);
4451    }
4452
4453    public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
4454        if (dismiss) {
4455            mNotificationService.clear(conversation);
4456        }
4457        final List<Message> readMessages = conversation.markRead(upToUuid);
4458        if (readMessages.size() > 0) {
4459            Runnable runnable = () -> {
4460                for (Message message : readMessages) {
4461                    databaseBackend.updateMessage(message, false);
4462                }
4463            };
4464            mDatabaseWriterExecutor.execute(runnable);
4465            updateConversationUi();
4466            updateUnreadCountBadge();
4467            return readMessages;
4468        } else {
4469            return readMessages;
4470        }
4471    }
4472
4473    public synchronized void updateUnreadCountBadge() {
4474        int count = unreadCount();
4475        if (unreadCount != count) {
4476            Log.d(Config.LOGTAG, "update unread count to " + count);
4477            if (count > 0) {
4478                ShortcutBadger.applyCount(getApplicationContext(), count);
4479            } else {
4480                ShortcutBadger.removeCount(getApplicationContext());
4481            }
4482            unreadCount = count;
4483        }
4484    }
4485
4486    public void sendReadMarker(final Conversation conversation, String upToUuid) {
4487        final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
4488        final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
4489        if (readMessages.size() > 0) {
4490            updateConversationUi();
4491        }
4492        final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
4493        if (confirmMessages()
4494                && markable != null
4495                && (markable.trusted() || isPrivateAndNonAnonymousMuc)
4496                && markable.getRemoteMsgId() != null) {
4497            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
4498            final Account account = conversation.getAccount();
4499            final MessagePacket packet = mMessageGenerator.confirm(markable);
4500            this.sendMessagePacket(account, packet);
4501        }
4502    }
4503
4504    public MemorizingTrustManager getMemorizingTrustManager() {
4505        return this.mMemorizingTrustManager;
4506    }
4507
4508    public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
4509        this.mMemorizingTrustManager = trustManager;
4510    }
4511
4512    public void updateMemorizingTrustmanager() {
4513        final MemorizingTrustManager tm;
4514        final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
4515        if (dontTrustSystemCAs) {
4516            tm = new MemorizingTrustManager(getApplicationContext(), null);
4517        } else {
4518            tm = new MemorizingTrustManager(getApplicationContext());
4519        }
4520        setMemorizingTrustManager(tm);
4521    }
4522
4523    public LruCache<String, Bitmap> getBitmapCache() {
4524        return this.mBitmapCache;
4525    }
4526
4527    public Collection<String> getKnownHosts() {
4528        final Set<String> hosts = new HashSet<>();
4529        for (final Account account : getAccounts()) {
4530            hosts.add(account.getServer());
4531            for (final Contact contact : account.getRoster().getContacts()) {
4532                if (contact.showInRoster()) {
4533                    final String server = contact.getServer();
4534                    if (server != null) {
4535                        hosts.add(server);
4536                    }
4537                }
4538            }
4539        }
4540        if (Config.QUICKSY_DOMAIN != null) {
4541            hosts.remove(Config.QUICKSY_DOMAIN.toEscapedString()); //we only want to show this when we type a e164 number
4542        }
4543        if (Config.DOMAIN_LOCK != null) {
4544            hosts.add(Config.DOMAIN_LOCK);
4545        }
4546        if (Config.MAGIC_CREATE_DOMAIN != null) {
4547            hosts.add(Config.MAGIC_CREATE_DOMAIN);
4548        }
4549        return hosts;
4550    }
4551
4552    public Collection<String> getKnownConferenceHosts() {
4553        final Set<String> mucServers = new HashSet<>();
4554        for (final Account account : accounts) {
4555            if (account.getXmppConnection() != null) {
4556                mucServers.addAll(account.getXmppConnection().getMucServers());
4557                for (final Bookmark bookmark : account.getBookmarks()) {
4558                    final Jid jid = bookmark.getJid();
4559                    final String s = jid == null ? null : jid.getDomain().toEscapedString();
4560                    if (s != null) {
4561                        mucServers.add(s);
4562                    }
4563                }
4564            }
4565        }
4566        return mucServers;
4567    }
4568
4569    public void sendMessagePacket(Account account, MessagePacket packet) {
4570        final XmppConnection connection = account.getXmppConnection();
4571        if (connection != null) {
4572            connection.sendMessagePacket(packet);
4573        }
4574    }
4575
4576    public void sendPresencePacket(Account account, PresencePacket packet) {
4577        XmppConnection connection = account.getXmppConnection();
4578        if (connection != null) {
4579            connection.sendPresencePacket(packet);
4580        }
4581    }
4582
4583    public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
4584        final XmppConnection connection = account.getXmppConnection();
4585        if (connection != null) {
4586            IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
4587            connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
4588        }
4589    }
4590
4591    public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
4592        final XmppConnection connection = account.getXmppConnection();
4593        if (connection != null) {
4594            connection.sendIqPacket(packet, callback);
4595        } else if (callback != null) {
4596            callback.onIqPacketReceived(account, new IqPacket(IqPacket.TYPE.TIMEOUT));
4597        }
4598    }
4599
4600    public void sendPresence(final Account account) {
4601        sendPresence(account, checkListeners() && broadcastLastActivity());
4602    }
4603
4604    private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
4605        final Presence.Status status;
4606        if (manuallyChangePresence()) {
4607            status = account.getPresenceStatus();
4608        } else {
4609            status = getTargetPresence();
4610        }
4611        final PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
4612        if (mLastActivity > 0 && includeIdleTimestamp) {
4613            long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
4614            packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
4615        }
4616        sendPresencePacket(account, packet);
4617    }
4618
4619    private void deactivateGracePeriod() {
4620        for (Account account : getAccounts()) {
4621            account.deactivateGracePeriod();
4622        }
4623    }
4624
4625    public void refreshAllPresences() {
4626        boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
4627        for (Account account : getAccounts()) {
4628            if (account.isConnectionEnabled()) {
4629                sendPresence(account, includeIdleTimestamp);
4630            }
4631        }
4632    }
4633
4634    private void refreshAllFcmTokens() {
4635        for (Account account : getAccounts()) {
4636            if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
4637                mPushManagementService.registerPushTokenOnServer(account);
4638            }
4639        }
4640    }
4641
4642
4643
4644    private void sendOfflinePresence(final Account account) {
4645        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
4646        sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
4647    }
4648
4649    public MessageGenerator getMessageGenerator() {
4650        return this.mMessageGenerator;
4651    }
4652
4653    public PresenceGenerator getPresenceGenerator() {
4654        return this.mPresenceGenerator;
4655    }
4656
4657    public IqGenerator getIqGenerator() {
4658        return this.mIqGenerator;
4659    }
4660
4661    public IqParser getIqParser() {
4662        return this.mIqParser;
4663    }
4664
4665    public JingleConnectionManager getJingleConnectionManager() {
4666        return this.mJingleConnectionManager;
4667    }
4668
4669    private boolean hasJingleRtpConnection(final Account account) {
4670        return this.mJingleConnectionManager.hasJingleRtpConnection(account);
4671    }
4672
4673    public MessageArchiveService getMessageArchiveService() {
4674        return this.mMessageArchiveService;
4675    }
4676
4677    public QuickConversationsService getQuickConversationsService() {
4678        return this.mQuickConversationsService;
4679    }
4680
4681    public List<Contact> findContacts(Jid jid, String accountJid) {
4682        ArrayList<Contact> contacts = new ArrayList<>();
4683        for (Account account : getAccounts()) {
4684            if ((account.isEnabled() || accountJid != null)
4685                    && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
4686                Contact contact = account.getRoster().getContactFromContactList(jid);
4687                if (contact != null) {
4688                    contacts.add(contact);
4689                }
4690            }
4691        }
4692        return contacts;
4693    }
4694
4695    public Conversation findFirstMuc(Jid jid) {
4696        for (Conversation conversation : getConversations()) {
4697            if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
4698                return conversation;
4699            }
4700        }
4701        return null;
4702    }
4703
4704    public NotificationService getNotificationService() {
4705        return this.mNotificationService;
4706    }
4707
4708    public HttpConnectionManager getHttpConnectionManager() {
4709        return this.mHttpConnectionManager;
4710    }
4711
4712    public void resendFailedMessages(final Message message) {
4713        final Collection<Message> messages = new ArrayList<>();
4714        Message current = message;
4715        while (current.getStatus() == Message.STATUS_SEND_FAILED) {
4716            messages.add(current);
4717            if (current.mergeable(current.next())) {
4718                current = current.next();
4719            } else {
4720                break;
4721            }
4722        }
4723        for (final Message msg : messages) {
4724            msg.setTime(System.currentTimeMillis());
4725            markMessage(msg, Message.STATUS_WAITING);
4726            this.resendMessage(msg, false);
4727        }
4728        if (message.getConversation() instanceof Conversation) {
4729            ((Conversation) message.getConversation()).sort();
4730        }
4731        updateConversationUi();
4732    }
4733
4734    public void clearConversationHistory(final Conversation conversation) {
4735        final long clearDate;
4736        final String reference;
4737        if (conversation.countMessages() > 0) {
4738            Message latestMessage = conversation.getLatestMessage();
4739            clearDate = latestMessage.getTimeSent() + 1000;
4740            reference = latestMessage.getServerMsgId();
4741        } else {
4742            clearDate = System.currentTimeMillis();
4743            reference = null;
4744        }
4745        conversation.clearMessages();
4746        conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
4747        conversation.setLastClearHistory(clearDate, reference);
4748        Runnable runnable = () -> {
4749            databaseBackend.deleteMessagesInConversation(conversation);
4750            databaseBackend.updateConversation(conversation);
4751        };
4752        mDatabaseWriterExecutor.execute(runnable);
4753    }
4754
4755    public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
4756        if (blockable != null && blockable.getBlockedJid() != null) {
4757            final Jid jid = blockable.getBlockedJid();
4758            this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), (a, response) -> {
4759                if (response.getType() == IqPacket.TYPE.RESULT) {
4760                    a.getBlocklist().add(jid);
4761                    updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
4762                }
4763            });
4764            if (blockable.getBlockedJid().isFullJid()) {
4765                return false;
4766            } else if (removeBlockedConversations(blockable.getAccount(), jid)) {
4767                updateConversationUi();
4768                return true;
4769            } else {
4770                return false;
4771            }
4772        } else {
4773            return false;
4774        }
4775    }
4776
4777    public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
4778        boolean removed = false;
4779        synchronized (this.conversations) {
4780            boolean domainJid = blockedJid.getLocal() == null;
4781            for (Conversation conversation : this.conversations) {
4782                boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
4783                        || blockedJid.equals(conversation.getJid().asBareJid());
4784                if (conversation.getAccount() == account
4785                        && conversation.getMode() == Conversation.MODE_SINGLE
4786                        && jidMatches) {
4787                    this.conversations.remove(conversation);
4788                    markRead(conversation);
4789                    conversation.setStatus(Conversation.STATUS_ARCHIVED);
4790                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
4791                    updateConversation(conversation);
4792                    removed = true;
4793                }
4794            }
4795        }
4796        return removed;
4797    }
4798
4799    public void sendUnblockRequest(final Blockable blockable) {
4800        if (blockable != null && blockable.getJid() != null) {
4801            final Jid jid = blockable.getBlockedJid();
4802            this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
4803                @Override
4804                public void onIqPacketReceived(final Account account, final IqPacket packet) {
4805                    if (packet.getType() == IqPacket.TYPE.RESULT) {
4806                        account.getBlocklist().remove(jid);
4807                        updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
4808                    }
4809                }
4810            });
4811        }
4812    }
4813
4814    public void publishDisplayName(Account account) {
4815        String displayName = account.getDisplayName();
4816        final IqPacket request;
4817        if (TextUtils.isEmpty(displayName)) {
4818            request = mIqGenerator.deleteNode(Namespace.NICK);
4819        } else {
4820            request = mIqGenerator.publishNick(displayName);
4821        }
4822        mAvatarService.clear(account);
4823        sendIqPacket(account, request, (account1, packet) -> {
4824            if (packet.getType() == IqPacket.TYPE.ERROR) {
4825                Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": unable to modify nick name " + packet);
4826            }
4827        });
4828    }
4829
4830    public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
4831        ServiceDiscoveryResult result = discoCache.get(key);
4832        if (result != null) {
4833            return result;
4834        } else {
4835            result = databaseBackend.findDiscoveryResult(key.first, key.second);
4836            if (result != null) {
4837                discoCache.put(key, result);
4838            }
4839            return result;
4840        }
4841    }
4842
4843    public void fetchCaps(Account account, final Jid jid, final Presence presence) {
4844        final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
4845        final ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
4846        if (disco != null) {
4847            presence.setServiceDiscoveryResult(disco);
4848            final Contact contact = account.getRoster().getContact(jid);
4849            if (contact.refreshRtpCapability()) {
4850                syncRoster(account);
4851            }
4852        } else {
4853            final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4854            request.setTo(jid);
4855            final String node = presence.getNode();
4856            final String ver = presence.getVer();
4857            final Element query = request.query(Namespace.DISCO_INFO);
4858            if (node != null && ver != null) {
4859                query.setAttribute("node", node + "#" + ver);
4860            }
4861            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
4862            sendIqPacket(account, request, (a, response) -> {
4863                if (response.getType() == IqPacket.TYPE.RESULT) {
4864                    final ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
4865                    if (presence.getVer().equals(discoveryResult.getVer())) {
4866                        databaseBackend.insertDiscoveryResult(discoveryResult);
4867                        injectServiceDiscoveryResult(a.getRoster(), presence.getHash(), presence.getVer(), discoveryResult);
4868                    } else {
4869                        Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
4870                    }
4871                } else {
4872                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to fetch caps from " + jid);
4873                }
4874            });
4875        }
4876    }
4877
4878    private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
4879        boolean rosterNeedsSync = false;
4880        for (final Contact contact : roster.getContacts()) {
4881            boolean serviceDiscoverySet = false;
4882            for (final Presence presence : contact.getPresences().getPresences()) {
4883                if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
4884                    presence.setServiceDiscoveryResult(disco);
4885                    serviceDiscoverySet = true;
4886                }
4887            }
4888            if (serviceDiscoverySet) {
4889                rosterNeedsSync |= contact.refreshRtpCapability();
4890            }
4891        }
4892        if (rosterNeedsSync) {
4893            syncRoster(roster.getAccount());
4894        }
4895    }
4896
4897    public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
4898        final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
4899        IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4900        request.addChild("prefs", version.namespace);
4901        sendIqPacket(account, request, (account1, packet) -> {
4902            Element prefs = packet.findChild("prefs", version.namespace);
4903            if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
4904                callback.onPreferencesFetched(prefs);
4905            } else {
4906                callback.onPreferencesFetchFailed();
4907            }
4908        });
4909    }
4910
4911    public PushManagementService getPushManagementService() {
4912        return mPushManagementService;
4913    }
4914
4915    public void changeStatus(Account account, PresenceTemplate template, String signature) {
4916        if (!template.getStatusMessage().isEmpty()) {
4917            databaseBackend.insertPresenceTemplate(template);
4918        }
4919        account.setPgpSignature(signature);
4920        account.setPresenceStatus(template.getStatus());
4921        account.setPresenceStatusMessage(template.getStatusMessage());
4922        databaseBackend.updateAccount(account);
4923        sendPresence(account);
4924    }
4925
4926    public List<PresenceTemplate> getPresenceTemplates(Account account) {
4927        List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
4928        for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
4929            if (!templates.contains(template)) {
4930                templates.add(0, template);
4931            }
4932        }
4933        return templates;
4934    }
4935
4936    public void saveConversationAsBookmark(Conversation conversation, String name) {
4937        final Account account = conversation.getAccount();
4938        final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
4939        final String nick = conversation.getJid().getResource();
4940        if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
4941            bookmark.setNick(nick);
4942        }
4943        if (!TextUtils.isEmpty(name)) {
4944            bookmark.setBookmarkName(name);
4945        }
4946        bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
4947        createBookmark(account, bookmark);
4948        bookmark.setConversation(conversation);
4949    }
4950
4951    public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
4952        boolean performedVerification = false;
4953        final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
4954        for (XmppUri.Fingerprint fp : fingerprints) {
4955            if (fp.type == XmppUri.FingerprintType.OMEMO) {
4956                String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4957                FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4958                if (fingerprintStatus != null) {
4959                    if (!fingerprintStatus.isVerified()) {
4960                        performedVerification = true;
4961                        axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4962                    }
4963                } else {
4964                    axolotlService.preVerifyFingerprint(contact, fingerprint);
4965                }
4966            }
4967        }
4968        return performedVerification;
4969    }
4970
4971    public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
4972        final AxolotlService axolotlService = account.getAxolotlService();
4973        boolean verifiedSomething = false;
4974        for (XmppUri.Fingerprint fp : fingerprints) {
4975            if (fp.type == XmppUri.FingerprintType.OMEMO) {
4976                String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4977                Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
4978                FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4979                if (fingerprintStatus != null) {
4980                    if (!fingerprintStatus.isVerified()) {
4981                        axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4982                        verifiedSomething = true;
4983                    }
4984                } else {
4985                    axolotlService.preVerifyFingerprint(account, fingerprint);
4986                    verifiedSomething = true;
4987                }
4988            }
4989        }
4990        return verifiedSomething;
4991    }
4992
4993    public boolean blindTrustBeforeVerification() {
4994        return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
4995    }
4996
4997    public ShortcutService getShortcutService() {
4998        return mShortcutService;
4999    }
5000
5001    public void pushMamPreferences(Account account, Element prefs) {
5002        IqPacket set = new IqPacket(IqPacket.TYPE.SET);
5003        set.addChild(prefs);
5004        sendIqPacket(account, set, null);
5005    }
5006
5007    public void evictPreview(String uuid) {
5008        if (mBitmapCache.remove(uuid) != null) {
5009            Log.d(Config.LOGTAG, "deleted cached preview");
5010        }
5011    }
5012
5013    public interface OnMamPreferencesFetched {
5014        void onPreferencesFetched(Element prefs);
5015
5016        void onPreferencesFetchFailed();
5017    }
5018
5019    public interface OnAccountCreated {
5020        void onAccountCreated(Account account);
5021
5022        void informUser(int r);
5023    }
5024
5025    public interface OnMoreMessagesLoaded {
5026        void onMoreMessagesLoaded(int count, Conversation conversation);
5027
5028        void informUser(int r);
5029    }
5030
5031    public interface OnAccountPasswordChanged {
5032        void onPasswordChangeSucceeded();
5033
5034        void onPasswordChangeFailed();
5035    }
5036
5037    public interface OnRoomDestroy {
5038        void onRoomDestroySucceeded();
5039
5040        void onRoomDestroyFailed();
5041    }
5042
5043    public interface OnAffiliationChanged {
5044        void onAffiliationChangedSuccessful(Jid jid);
5045
5046        void onAffiliationChangeFailed(Jid jid, int resId);
5047    }
5048
5049    public interface OnConversationUpdate {
5050        void onConversationUpdate();
5051    }
5052
5053    public interface OnJingleRtpConnectionUpdate {
5054        void onJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state);
5055
5056        void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices);
5057    }
5058
5059    public interface OnAccountUpdate {
5060        void onAccountUpdate();
5061    }
5062
5063    public interface OnCaptchaRequested {
5064        void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
5065    }
5066
5067    public interface OnRosterUpdate {
5068        void onRosterUpdate();
5069    }
5070
5071    public interface OnMucRosterUpdate {
5072        void onMucRosterUpdate();
5073    }
5074
5075    public interface OnConferenceConfigurationFetched {
5076        void onConferenceConfigurationFetched(Conversation conversation);
5077
5078        void onFetchFailed(Conversation conversation, String errorCondition);
5079    }
5080
5081    public interface OnConferenceJoined {
5082        void onConferenceJoined(Conversation conversation);
5083    }
5084
5085    public interface OnConfigurationPushed {
5086        void onPushSucceeded();
5087
5088        void onPushFailed();
5089    }
5090
5091    public interface OnShowErrorToast {
5092        void onShowErrorToast(int resId);
5093    }
5094
5095    public class XmppConnectionBinder extends Binder {
5096        public XmppConnectionService getService() {
5097            return XmppConnectionService.this;
5098        }
5099    }
5100
5101    private class InternalEventReceiver extends BroadcastReceiver {
5102
5103        @Override
5104        public void onReceive(final Context context, final Intent intent) {
5105            onStartCommand(intent, 0, 0);
5106        }
5107    }
5108
5109    private class RestrictedEventReceiver extends BroadcastReceiver {
5110
5111        private final Collection<String> allowedActions;
5112
5113        private RestrictedEventReceiver(final Collection<String> allowedActions) {
5114            this.allowedActions = allowedActions;
5115        }
5116
5117        @Override
5118        public void onReceive(final Context context, final Intent intent) {
5119            final String action = intent == null ? null : intent.getAction();
5120            if (allowedActions.contains(action)) {
5121                onStartCommand(intent,0,0);
5122            } else {
5123                Log.e(Config.LOGTAG,"restricting broadcast of event "+action);
5124            }
5125        }
5126    }
5127
5128    public static class OngoingCall {
5129        public final AbstractJingleConnection.Id id;
5130        public final Set<Media> media;
5131        public final boolean reconnecting;
5132
5133        public OngoingCall(AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
5134            this.id = id;
5135            this.media = media;
5136            this.reconnecting = reconnecting;
5137        }
5138
5139        @Override
5140        public boolean equals(Object o) {
5141            if (this == o) return true;
5142            if (o == null || getClass() != o.getClass()) return false;
5143            OngoingCall that = (OngoingCall) o;
5144            return reconnecting == that.reconnecting && Objects.equal(id, that.id) && Objects.equal(media, that.media);
5145        }
5146
5147        @Override
5148        public int hashCode() {
5149            return Objects.hashCode(id, media, reconnecting);
5150        }
5151    }
5152}