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