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