XmppConnectionService.java

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