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