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