XmppConnectionService.java

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