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