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