XmppConnectionService.java

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