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