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