XmppConnectionService.java

   1package eu.siacs.conversations.services;
   2
   3import static eu.siacs.conversations.utils.Compatibility.s;
   4import static eu.siacs.conversations.utils.Random.SECURE_RANDOM;
   5
   6import android.Manifest;
   7import android.annotation.SuppressLint;
   8import android.annotation.TargetApi;
   9import android.app.AlarmManager;
  10import android.app.KeyguardManager;
  11import android.app.Notification;
  12import android.app.NotificationManager;
  13import android.app.PendingIntent;
  14import android.app.Service;
  15import android.content.BroadcastReceiver;
  16import android.content.ComponentName;
  17import android.content.Context;
  18import android.content.Intent;
  19import android.content.IntentFilter;
  20import android.content.SharedPreferences;
  21import android.content.pm.PackageManager;
  22import android.content.pm.ServiceInfo;
  23import android.database.ContentObserver;
  24import android.graphics.Bitmap;
  25import android.graphics.drawable.AnimatedImageDrawable;
  26import android.graphics.drawable.BitmapDrawable;
  27import android.graphics.drawable.Drawable;
  28import android.media.AudioManager;
  29import android.net.ConnectivityManager;
  30import android.net.Network;
  31import android.net.NetworkCapabilities;
  32import android.net.NetworkInfo;
  33import android.net.Uri;
  34import android.os.Binder;
  35import android.os.Build;
  36import android.os.Bundle;
  37import android.os.Environment;
  38import android.os.IBinder;
  39import android.os.Messenger;
  40import android.os.PowerManager;
  41import android.os.PowerManager.WakeLock;
  42import android.os.SystemClock;
  43import android.preference.PreferenceManager;
  44import android.provider.ContactsContract;
  45import android.provider.DocumentsContract;
  46import android.security.KeyChain;
  47import android.text.TextUtils;
  48import android.util.DisplayMetrics;
  49import android.util.Log;
  50import android.util.LruCache;
  51import android.util.Pair;
  52
  53import androidx.annotation.BoolRes;
  54import androidx.annotation.IntegerRes;
  55import androidx.annotation.NonNull;
  56import androidx.annotation.Nullable;
  57import androidx.core.app.RemoteInput;
  58import androidx.core.content.ContextCompat;
  59import androidx.core.util.Consumer;
  60
  61import com.cheogram.android.EmojiSearch;
  62import com.cheogram.android.WebxdcUpdate;
  63
  64import com.google.common.base.Objects;
  65import com.google.common.base.Optional;
  66import com.google.common.base.Strings;
  67import com.google.common.collect.Multimap;
  68import com.google.common.collect.Collections2;
  69import com.google.common.collect.Iterables;
  70import com.google.common.io.Files;
  71
  72import com.kedia.ogparser.JsoupProxy;
  73import com.kedia.ogparser.OpenGraphCallback;
  74import com.kedia.ogparser.OpenGraphParser;
  75import com.kedia.ogparser.OpenGraphResult;
  76
  77import org.conscrypt.Conscrypt;
  78import org.jxmpp.stringprep.libidn.LibIdnXmppStringprep;
  79import org.openintents.openpgp.IOpenPgpService2;
  80import org.openintents.openpgp.util.OpenPgpApi;
  81import org.openintents.openpgp.util.OpenPgpServiceConnection;
  82
  83import java.io.File;
  84import java.io.FileInputStream;
  85import java.io.IOException;
  86import java.net.URI;
  87import java.security.Security;
  88import java.security.cert.CertificateException;
  89import java.security.cert.X509Certificate;
  90import java.util.ArrayList;
  91import java.util.Arrays;
  92import java.util.Collection;
  93import java.util.Collections;
  94import java.util.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            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + previousBookmarks.size() + " bookmarks have been removed");
2411            for (Jid jid : previousBookmarks) {
2412                processDeletedBookmark(account, jid);
2413            }
2414        }
2415        account.setBookmarks(bookmarks);
2416    }
2417
2418    public void processDeletedBookmark(Account account, Jid jid) {
2419        final Conversation conversation = find(account, jid);
2420        if (conversation != null && conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2421            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving destroyed conference (" + conversation.getJid() + ") after receiving pep");
2422            archiveConversation(conversation, false);
2423        }
2424    }
2425
2426    private void processModifiedBookmark(final Bookmark bookmark, final boolean pep) {
2427        final Account account = bookmark.getAccount();
2428        Conversation conversation = find(bookmark);
2429        if (conversation != null) {
2430            if (conversation.getMode() != Conversation.MODE_MULTI) {
2431                return;
2432            }
2433            bookmark.setConversation(conversation);
2434            if (pep && !bookmark.autojoin()) {
2435                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conference (" + conversation.getJid() + ") after receiving pep");
2436                archiveConversation(conversation, false);
2437            } else {
2438                final MucOptions mucOptions = conversation.getMucOptions();
2439                if (mucOptions.getError() == MucOptions.Error.NICK_IN_USE) {
2440                    final String current = mucOptions.getActualNick();
2441                    final String proposed = mucOptions.getProposedNick();
2442                    if (current != null && !current.equals(proposed)) {
2443                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": proposed nick changed after bookmark push " + current + "->" + proposed);
2444                        joinMuc(conversation);
2445                    }
2446                }
2447            }
2448        } else if (bookmark.autojoin()) {
2449            conversation = findOrCreateConversation(account, bookmark.getFullJid(), true, true, false);
2450            bookmark.setConversation(conversation);
2451        }
2452    }
2453
2454    public void processModifiedBookmark(final Bookmark bookmark) {
2455        processModifiedBookmark(bookmark, true);
2456    }
2457
2458    public void createBookmark(final Account account, final Bookmark bookmark) {
2459        account.putBookmark(bookmark);
2460        final XmppConnection connection = account.getXmppConnection();
2461        if (connection == null) {
2462            Log.d(Config.LOGTAG, account.getJid().asBareJid()+": no connection. ignoring bookmark creation");
2463        } else if (connection.getFeatures().bookmarks2()) {
2464            Log.d(Config.LOGTAG,account.getJid().asBareJid() + ": pushing bookmark via Bookmarks 2");
2465            final Element item = mIqGenerator.publishBookmarkItem(bookmark);
2466            pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS2, item, bookmark.getJid().asBareJid().toEscapedString(), PublishOptions.persistentWhitelistAccessMaxItems());
2467        } else if (connection.getFeatures().bookmarksConversion()) {
2468            pushBookmarksPep(account);
2469        } else {
2470            pushBookmarksPrivateXml(account);
2471        }
2472    }
2473
2474    public void deleteBookmark(final Account account, final Bookmark bookmark) {
2475        if (bookmark.getJid().toString().equals("discuss@conference.soprani.ca")) {
2476            getPreferences().edit().putBoolean("cheogram_sopranica_bookmark_deleted", true).apply();
2477        }
2478        account.removeBookmark(bookmark);
2479        final XmppConnection connection = account.getXmppConnection();
2480        if (connection == null) return;
2481
2482        if (connection.getFeatures().bookmarks2()) {
2483            final IqPacket request = mIqGenerator.deleteItem(Namespace.BOOKMARKS2, bookmark.getJid().asBareJid().toEscapedString());
2484            Log.d(Config.LOGTAG,account.getJid().asBareJid() + ": removing bookmark via Bookmarks 2");
2485            sendIqPacket(account, request, (a, response) -> {
2486                if (response.getType() == IqPacket.TYPE.ERROR) {
2487                    Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": unable to delete bookmark " + response.getErrorCondition());
2488                }
2489            });
2490        } else if (connection.getFeatures().bookmarksConversion()) {
2491            pushBookmarksPep(account);
2492        } else {
2493            pushBookmarksPrivateXml(account);
2494        }
2495    }
2496
2497    private void pushBookmarksPrivateXml(Account account) {
2498        if (!account.areBookmarksLoaded()) return;
2499
2500        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
2501        IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
2502        Element query = iqPacket.query("jabber:iq:private");
2503        Element storage = query.addChild("storage", "storage:bookmarks");
2504        for (final Bookmark bookmark : account.getBookmarks()) {
2505            storage.addChild(bookmark);
2506        }
2507        sendIqPacket(account, iqPacket, mDefaultIqHandler);
2508    }
2509
2510    private void pushBookmarksPep(Account account) {
2511        if (!account.areBookmarksLoaded()) return;
2512
2513        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
2514        final Element storage = new Element("storage", "storage:bookmarks");
2515        for (final Bookmark bookmark : account.getBookmarks()) {
2516            storage.addChild(bookmark);
2517        }
2518        pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS, storage, "current", PublishOptions.persistentWhitelistAccess());
2519
2520    }
2521
2522    private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options) {
2523        pushNodeAndEnforcePublishOptions(account, node, element, id, options, true);
2524
2525    }
2526
2527    private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options, final boolean retry) {
2528        final IqPacket packet = mIqGenerator.publishElement(node, element, id, options);
2529        sendIqPacket(account, packet, (a, response) -> {
2530            if (response.getType() == IqPacket.TYPE.RESULT) {
2531                return;
2532            }
2533            if (retry && PublishOptions.preconditionNotMet(response)) {
2534                pushNodeConfiguration(account, node, options, new OnConfigurationPushed() {
2535                    @Override
2536                    public void onPushSucceeded() {
2537                        pushNodeAndEnforcePublishOptions(account, node, element, id, options, false);
2538                    }
2539
2540                    @Override
2541                    public void onPushFailed() {
2542                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to push node configuration (" + node + ")");
2543                    }
2544                });
2545            } else {
2546                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error publishing "+node+" (retry=" + retry + ") " + response);
2547            }
2548        });
2549    }
2550
2551    private void restoreFromDatabase() {
2552        synchronized (this.conversations) {
2553            final Map<String, Account> accountLookupTable = new Hashtable<>();
2554            for (Account account : this.accounts) {
2555                accountLookupTable.put(account.getUuid(), account);
2556            }
2557            Log.d(Config.LOGTAG, "restoring conversations...");
2558            final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
2559            this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
2560            for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
2561                Conversation conversation = iterator.next();
2562                Account account = accountLookupTable.get(conversation.getAccountUuid());
2563                if (account != null) {
2564                    conversation.setAccount(account);
2565                } else {
2566                    Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
2567                    iterator.remove();
2568                }
2569            }
2570            long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
2571            Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
2572            Runnable runnable = () -> {
2573                if (DatabaseBackend.requiresMessageIndexRebuild()) {
2574                    DatabaseBackend.getInstance(this).rebuildMessagesIndex();
2575                }
2576                mutedMucUsers = databaseBackend.loadMutedMucUsers();
2577                final long deletionDate = getAutomaticMessageDeletionDate();
2578                mLastExpiryRun.set(SystemClock.elapsedRealtime());
2579                if (deletionDate > 0) {
2580                    Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
2581                    databaseBackend.expireOldMessages(deletionDate);
2582                }
2583                Log.d(Config.LOGTAG, "restoring roster...");
2584                for (final Account account : accounts) {
2585                    databaseBackend.readRoster(account.getRoster());
2586                    account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
2587                }
2588                getDrawableCache().evictAll();
2589                loadPhoneContacts();
2590                Log.d(Config.LOGTAG, "restoring messages...");
2591                final long startMessageRestore = SystemClock.elapsedRealtime();
2592                final Conversation quickLoad = QuickLoader.get(this.conversations);
2593                if (quickLoad != null) {
2594                    restoreMessages(quickLoad);
2595                    updateConversationUi();
2596                    final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
2597                    Log.d(Config.LOGTAG, "quickly restored " + quickLoad.getName() + " after " + diffMessageRestore + "ms");
2598                }
2599                for (Conversation conversation : this.conversations) {
2600                    if (quickLoad != conversation) {
2601                        restoreMessages(conversation);
2602                    }
2603                }
2604                mNotificationService.finishBacklog();
2605                restoredFromDatabaseLatch.countDown();
2606                final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
2607                Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
2608                updateConversationUi();
2609            };
2610            mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
2611        }
2612    }
2613
2614    private void restoreMessages(Conversation conversation) {
2615        conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
2616        conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
2617        conversation.findUnreadMessagesAndCalls(mNotificationService::pushFromBacklog);
2618    }
2619
2620    public void loadPhoneContacts() {
2621        mContactMergerExecutor.execute(() -> {
2622            final Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
2623            Log.d(Config.LOGTAG, "start merging phone contacts with roster");
2624            for (final Account account : accounts) {
2625                final List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts(JabberIdContact.class);
2626                for (final JabberIdContact jidContact : contacts.values()) {
2627                    final Contact contact = account.getRoster().getContact(jidContact.getJid());
2628                    boolean needsCacheClean = contact.setPhoneContact(jidContact);
2629                    if (needsCacheClean) {
2630                        getAvatarService().clear(contact);
2631                    }
2632                    withSystemAccounts.remove(contact);
2633                }
2634                for (final Contact contact : withSystemAccounts) {
2635                    boolean needsCacheClean = contact.unsetPhoneContact(JabberIdContact.class);
2636                    if (needsCacheClean) {
2637                        getAvatarService().clear(contact);
2638                    }
2639                }
2640            }
2641            Log.d(Config.LOGTAG, "finished merging phone contacts");
2642            mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
2643            updateRosterUi();
2644            mQuickConversationsService.considerSync();
2645        });
2646    }
2647
2648
2649    public void syncRoster(final Account account) {
2650        mRosterSyncTaskManager.execute(account, () -> {
2651            unregisterPhoneAccounts(account);
2652            databaseBackend.writeRoster(account.getRoster());
2653            try { Thread.sleep(500); } catch (InterruptedException e) { }
2654        });
2655    }
2656
2657    public List<Conversation> getConversations() {
2658        return this.conversations;
2659    }
2660
2661    private void markFileDeleted(final File file) {
2662        synchronized (FILENAMES_TO_IGNORE_DELETION) {
2663            if (FILENAMES_TO_IGNORE_DELETION.remove(file.getAbsolutePath())) {
2664                Log.d(Config.LOGTAG, "ignored deletion of " + file.getAbsolutePath());
2665                return;
2666            }
2667        }
2668        final boolean isInternalFile = fileBackend.isInternalFile(file);
2669        final List<String> uuids = databaseBackend.markFileAsDeleted(file, isInternalFile);
2670        Log.d(Config.LOGTAG, "deleted file " + file.getAbsolutePath() + " internal=" + isInternalFile + ", database hits=" + uuids.size());
2671        markUuidsAsDeletedFiles(uuids);
2672    }
2673
2674    private void markUuidsAsDeletedFiles(List<String> uuids) {
2675        boolean deleted = false;
2676        for (Conversation conversation : getConversations()) {
2677            deleted |= conversation.markAsDeleted(uuids);
2678        }
2679        for (final String uuid : uuids) {
2680            evictPreview(uuid);
2681        }
2682        if (deleted) {
2683            updateConversationUi();
2684        }
2685    }
2686
2687    private void markChangedFiles(List<DatabaseBackend.FilePathInfo> infos) {
2688        boolean changed = false;
2689        for (Conversation conversation : getConversations()) {
2690            changed |= conversation.markAsChanged(infos);
2691        }
2692        if (changed) {
2693            updateConversationUi();
2694        }
2695    }
2696
2697    public void populateWithOrderedConversations(final List<Conversation> list) {
2698        populateWithOrderedConversations(list, true, true);
2699    }
2700
2701    public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload) {
2702        populateWithOrderedConversations(list, includeNoFileUpload, true);
2703    }
2704
2705    public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload, final boolean sort) {
2706        final List<String> orderedUuids;
2707        if (sort) {
2708            orderedUuids = null;
2709        } else {
2710            orderedUuids = new ArrayList<>();
2711            for (Conversation conversation : list) {
2712                orderedUuids.add(conversation.getUuid());
2713            }
2714        }
2715        list.clear();
2716        if (includeNoFileUpload) {
2717            list.addAll(getConversations());
2718        } else {
2719            for (Conversation conversation : getConversations()) {
2720                if (conversation.getMode() == Conversation.MODE_SINGLE
2721                        || (conversation.getAccount().httpUploadAvailable() && conversation.getMucOptions().participating())) {
2722                    list.add(conversation);
2723                }
2724            }
2725        }
2726        try {
2727            if (orderedUuids != null) {
2728                Collections.sort(list, (a, b) -> {
2729                    final int indexA = orderedUuids.indexOf(a.getUuid());
2730                    final int indexB = orderedUuids.indexOf(b.getUuid());
2731                    if (indexA == -1 || indexB == -1 || indexA == indexB) {
2732                        return a.compareTo(b);
2733                    }
2734                    return indexA - indexB;
2735                });
2736            } else {
2737                Collections.sort(list);
2738            }
2739        } catch (IllegalArgumentException e) {
2740            //ignore
2741        }
2742    }
2743
2744    public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
2745        if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
2746            return;
2747        } else if (timestamp == 0) {
2748            return;
2749        }
2750        Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
2751        final Runnable runnable = () -> {
2752            final Account account = conversation.getAccount();
2753            List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
2754            if (messages.size() > 0) {
2755                conversation.addAll(0, messages);
2756                callback.onMoreMessagesLoaded(messages.size(), conversation);
2757            } else if (conversation.hasMessagesLeftOnServer()
2758                    && account.isOnlineAndConnected()
2759                    && conversation.getLastClearHistory().getTimestamp() == 0) {
2760                final boolean mamAvailable;
2761                if (conversation.getMode() == Conversation.MODE_SINGLE) {
2762                    mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
2763                } else {
2764                    mamAvailable = conversation.getMucOptions().mamSupport();
2765                }
2766                if (mamAvailable) {
2767                    MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
2768                    if (query != null) {
2769                        query.setCallback(callback);
2770                        callback.informUser(R.string.fetching_history_from_server);
2771                    } else {
2772                        callback.informUser(R.string.not_fetching_history_retention_period);
2773                    }
2774
2775                }
2776            }
2777        };
2778        mDatabaseReaderExecutor.execute(runnable);
2779    }
2780
2781    public List<Account> getAccounts() {
2782        return this.accounts;
2783    }
2784
2785
2786    /**
2787     * 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)
2788     */
2789    public List<Conversation> findAllConferencesWith(Contact contact) {
2790        final ArrayList<Conversation> results = new ArrayList<>();
2791        for (final Conversation c : conversations) {
2792            if (c.getMode() != Conversation.MODE_MULTI) {
2793                continue;
2794            }
2795            final MucOptions mucOptions = c.getMucOptions();
2796            if (c.getJid().asBareJid().equals(contact.getJid().asBareJid()) || (mucOptions != null && mucOptions.isContactInRoom(contact))) {
2797                results.add(c);
2798            }
2799        }
2800        return results;
2801    }
2802
2803    public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
2804        for (final Conversation conversation : haystack) {
2805            if (conversation.getContact() == contact) {
2806                return conversation;
2807            }
2808        }
2809        return null;
2810    }
2811
2812    public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
2813        if (jid == null) {
2814            return null;
2815        }
2816        for (final Conversation conversation : haystack) {
2817            if ((account == null || conversation.getAccount() == account)
2818                    && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
2819                return conversation;
2820            }
2821        }
2822        return null;
2823    }
2824
2825    public boolean isConversationsListEmpty(final Conversation ignore) {
2826        synchronized (this.conversations) {
2827            final int size = this.conversations.size();
2828            return size == 0 || size == 1 && this.conversations.get(0) == ignore;
2829        }
2830    }
2831
2832    public boolean isConversationStillOpen(final Conversation conversation) {
2833        synchronized (this.conversations) {
2834            for (Conversation current : this.conversations) {
2835                if (current == conversation) {
2836                    return true;
2837                }
2838            }
2839        }
2840        return false;
2841    }
2842
2843    public void maybeRegisterWithMuc(Conversation c, String nickArg) {
2844        final var nick = nickArg == null ? c.getMucOptions().getSelf().getFullJid().getResource() : nickArg;
2845        final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
2846        register.query(Namespace.REGISTER);
2847        register.setTo(c.getJid().asBareJid());
2848        sendIqPacket(c.getAccount(), register, (a, response) -> {
2849            if (response.getType() == IqPacket.TYPE.RESULT) {
2850                final Element query = response.query(Namespace.REGISTER);
2851                String username = query.findChildContent("username", Namespace.REGISTER);
2852                if (username == null) username = query.findChildContent("nick", Namespace.REGISTER);
2853                if (username != null && username.equals(nick)) {
2854                    // Already registered with this nick, done
2855                    Log.d(Config.LOGTAG, "Already registered with " + c.getJid().asBareJid() + " as " + username);
2856                    return;
2857                }
2858                Data form = Data.parse(query.findChild("x", Namespace.DATA));
2859                if (form != null) {
2860                    final var field = form.getFieldByName("muc#register_roomnick");
2861                    if (field != null && nick.equals(field.getValue())) {
2862                        Log.d(Config.LOGTAG, "Already registered with " + c.getJid().asBareJid() + " as " + field.getValue());
2863                        return;
2864                    }
2865                }
2866                if (form == null || !"form".equals(form.getFormType()) || !form.getFields().stream().anyMatch(f -> f.isRequired() && !"muc#register_roomnick".equals(f.getFieldName()))) {
2867                    // No form, result form, or no required fields other than nickname, let's just send nickname
2868                    if (form == null || !"form".equals(form.getFormType())) {
2869                        form = new Data();
2870                        form.put("FORM_TYPE", "http://jabber.org/protocol/muc#register");
2871                    }
2872                    form.put("muc#register_roomnick", nick);
2873                    form.submit();
2874                    final IqPacket finish = new IqPacket(IqPacket.TYPE.SET);
2875                    finish.query(Namespace.REGISTER).addChild(form);
2876                    finish.setTo(c.getJid().asBareJid());
2877                    sendIqPacket(c.getAccount(), finish, (a2, response2) -> {
2878                        if (response.getType() == IqPacket.TYPE.RESULT) {
2879                            Log.w(Config.LOGTAG, "Success registering with channel " + c.getJid().asBareJid() + "/" + nick);
2880                        } else {
2881                            Log.w(Config.LOGTAG, "Error registering with channel: " + response2);
2882                        }
2883                    });
2884                } else {
2885                    // TODO: offer registration form to user
2886                    Log.d(Config.LOGTAG, "Complex registration form for " + c.getJid().asBareJid() + ": " + response);
2887                }
2888            } else {
2889                // We said maybe. Guess not
2890                Log.d(Config.LOGTAG, "Could not register with " + c.getJid().asBareJid() + ": " + response);
2891            }
2892        });
2893    }
2894
2895    public void deregisterWithMuc(Conversation c) {
2896        final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
2897        register.query(Namespace.REGISTER).addChild("remove");
2898        register.setTo(c.getJid().asBareJid());
2899        sendIqPacket(c.getAccount(), register, (a, response) -> {
2900            if (response.getType() == IqPacket.TYPE.RESULT) {
2901                Log.d(Config.LOGTAG, "deregistered with " + c.getJid().asBareJid());
2902            } else {
2903                Log.w(Config.LOGTAG, "Could not deregister with " + c.getJid().asBareJid() + ": " + response);
2904            }
2905        });
2906    }
2907
2908    public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
2909        return this.findOrCreateConversation(account, jid, muc, false, async);
2910    }
2911
2912    public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
2913        return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async, null);
2914    }
2915
2916    public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
2917        return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, query, async, null);
2918    }
2919
2920    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) {
2921        synchronized (this.conversations) {
2922            Conversation conversation = find(account, jid);
2923            if (conversation != null) {
2924                return conversation;
2925            }
2926            conversation = databaseBackend.findConversation(account, jid);
2927            final boolean loadMessagesFromDb;
2928            if (conversation != null) {
2929                conversation.setStatus(Conversation.STATUS_AVAILABLE);
2930                conversation.setAccount(account);
2931                if (muc) {
2932                    conversation.setMode(Conversation.MODE_MULTI);
2933                    conversation.setContactJid(jid);
2934                    if (password != null) conversation.getMucOptions().setPassword(password);
2935                } else {
2936                    conversation.setMode(Conversation.MODE_SINGLE);
2937                    conversation.setContactJid(jid.asBareJid());
2938                }
2939                databaseBackend.updateConversation(conversation);
2940                loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
2941            } else {
2942                String conversationName;
2943                Contact contact = account.getRoster().getContact(jid);
2944                if (contact != null) {
2945                    conversationName = contact.getDisplayName();
2946                } else {
2947                    conversationName = jid.getLocal();
2948                }
2949                if (muc) {
2950                    conversation = new Conversation(conversationName, account, jid,
2951                            Conversation.MODE_MULTI);
2952                    if (password != null) conversation.getMucOptions().setPassword(password);
2953                } else {
2954                    conversation = new Conversation(conversationName, account, jid.asBareJid(),
2955                            Conversation.MODE_SINGLE);
2956                }
2957                this.databaseBackend.createConversation(conversation);
2958                loadMessagesFromDb = false;
2959            }
2960            final Conversation c = conversation;
2961            final Runnable runnable = () -> {
2962                if (loadMessagesFromDb) {
2963                    c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
2964                    updateConversationUi();
2965                    c.messagesLoaded.set(true);
2966                }
2967                if (account.getXmppConnection() != null
2968                        && !c.getContact().isBlocked()
2969                        && account.getXmppConnection().getFeatures().mam()
2970                        && !muc) {
2971                    if (query == null) {
2972                        mMessageArchiveService.query(c);
2973                    } else {
2974                        if (query.getConversation() == null) {
2975                            mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
2976                        }
2977                    }
2978                }
2979                if (joinAfterCreate) {
2980                    joinMuc(c);
2981                }
2982            };
2983            if (async) {
2984                mDatabaseReaderExecutor.execute(runnable);
2985            } else {
2986                runnable.run();
2987            }
2988            this.conversations.add(conversation);
2989            updateConversationUi();
2990            return conversation;
2991        }
2992    }
2993
2994    public void archiveConversation(Conversation conversation) {
2995        archiveConversation(conversation, true);
2996    }
2997
2998    private void archiveConversation(Conversation conversation, final boolean maySynchronizeWithBookmarks) {
2999        if (isOnboarding()) return;
3000
3001        getNotificationService().clear(conversation);
3002        conversation.setStatus(Conversation.STATUS_ARCHIVED);
3003        conversation.setNextMessage(null);
3004        synchronized (this.conversations) {
3005            getMessageArchiveService().kill(conversation);
3006            if (conversation.getMode() == Conversation.MODE_MULTI) {
3007                if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
3008                    final Bookmark bookmark = conversation.getBookmark();
3009                    if (maySynchronizeWithBookmarks && bookmark != null) {
3010                        if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
3011                            Account account = bookmark.getAccount();
3012                            bookmark.setConversation(null);
3013                            deleteBookmark(account, bookmark);
3014                        } else if (bookmark.autojoin()) {
3015                            bookmark.setAutojoin(false);
3016                            createBookmark(bookmark.getAccount(), bookmark);
3017                        }
3018                    }
3019                }
3020                deregisterWithMuc(conversation);
3021                leaveMuc(conversation);
3022            } else {
3023                if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
3024                    stopPresenceUpdatesTo(conversation.getContact());
3025                }
3026            }
3027            updateConversation(conversation);
3028            this.conversations.remove(conversation);
3029            updateConversationUi();
3030        }
3031    }
3032
3033    public void stopPresenceUpdatesTo(Contact contact) {
3034        Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
3035        sendPresencePacket(contact.getAccount(), mPresenceGenerator.stopPresenceUpdatesTo(contact));
3036        contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
3037    }
3038
3039    public void createAccount(final Account account) {
3040        account.initAccountServices(this);
3041        databaseBackend.createAccount(account);
3042        if (CallIntegration.hasSystemFeature(this)) {
3043            CallIntegrationConnectionService.togglePhoneAccountAsync(this, account);
3044        }
3045        this.accounts.add(account);
3046        this.reconnectAccountInBackground(account);
3047        updateAccountUi();
3048        syncEnabledAccountSetting();
3049        toggleForegroundService();
3050    }
3051
3052    private void syncEnabledAccountSetting() {
3053        final boolean hasEnabledAccounts = hasEnabledAccounts();
3054        getPreferences().edit().putBoolean(SystemEventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
3055        toggleSetProfilePictureActivity(hasEnabledAccounts);
3056    }
3057
3058    private void toggleSetProfilePictureActivity(final boolean enabled) {
3059        try {
3060            final ComponentName name = new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
3061            final int targetState = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
3062            getPackageManager().setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
3063        } catch (IllegalStateException e) {
3064            Log.d(Config.LOGTAG, "unable to toggle profile picture activity");
3065        }
3066    }
3067
3068    public boolean reconfigurePushDistributor() {
3069        return this.unifiedPushBroker.reconfigurePushDistributor();
3070    }
3071
3072    private Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints(final UnifiedPushBroker.PushTargetMessenger pushTargetMessenger) {
3073        return this.unifiedPushBroker.renewUnifiedPushEndpoints(pushTargetMessenger);
3074    }
3075
3076    public Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints() {
3077        return this.unifiedPushBroker.renewUnifiedPushEndpoints(null);
3078    }
3079
3080    private void provisionAccount(final String address, final String password) {
3081        final Jid jid = Jid.ofEscaped(address);
3082        final Account account = new Account(jid, password);
3083        account.setOption(Account.OPTION_DISABLED, true);
3084        Log.d(Config.LOGTAG, jid.asBareJid().toEscapedString() + ": provisioning account");
3085        createAccount(account);
3086    }
3087
3088    public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
3089        new Thread(() -> {
3090            try {
3091                final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
3092                final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
3093                if (cert == null) {
3094                    callback.informUser(R.string.unable_to_parse_certificate);
3095                    return;
3096                }
3097                Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
3098                if (info == null) {
3099                    callback.informUser(R.string.certificate_does_not_contain_jid);
3100                    return;
3101                }
3102                if (findAccountByJid(info.first) == null) {
3103                    final Account account = new Account(info.first, "");
3104                    account.setPrivateKeyAlias(alias);
3105                    account.setOption(Account.OPTION_DISABLED, true);
3106                    account.setOption(Account.OPTION_FIXED_USERNAME, true);
3107                    account.setDisplayName(info.second);
3108                    createAccount(account);
3109                    callback.onAccountCreated(account);
3110                    if (Config.X509_VERIFICATION) {
3111                        try {
3112                            getMemorizingTrustManager().getNonInteractive(account.getServer(), null, 0, null).checkClientTrusted(chain, "RSA");
3113                        } catch (CertificateException e) {
3114                            callback.informUser(R.string.certificate_chain_is_not_trusted);
3115                        }
3116                    }
3117                } else {
3118                    callback.informUser(R.string.account_already_exists);
3119                }
3120            } catch (Exception e) {
3121                callback.informUser(R.string.unable_to_parse_certificate);
3122            }
3123        }).start();
3124
3125    }
3126
3127    public void updateKeyInAccount(final Account account, final String alias) {
3128        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
3129        try {
3130            X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
3131            Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
3132            Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
3133            if (info == null) {
3134                showErrorToastInUi(R.string.certificate_does_not_contain_jid);
3135                return;
3136            }
3137            if (account.getJid().asBareJid().equals(info.first)) {
3138                account.setPrivateKeyAlias(alias);
3139                account.setDisplayName(info.second);
3140                databaseBackend.updateAccount(account);
3141                if (Config.X509_VERIFICATION) {
3142                    try {
3143                        getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
3144                    } catch (CertificateException e) {
3145                        showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
3146                    }
3147                    account.getAxolotlService().regenerateKeys(true);
3148                }
3149            } else {
3150                showErrorToastInUi(R.string.jid_does_not_match_certificate);
3151            }
3152        } catch (Exception e) {
3153            e.printStackTrace();
3154        }
3155    }
3156
3157    public boolean updateAccount(final Account account) {
3158        if (databaseBackend.updateAccount(account)) {
3159            Integer color = account.getColorToSave();
3160            if (color == null) {
3161                getPreferences().edit().remove("account_color:" + account.getUuid()).commit();
3162            } else {
3163                getPreferences().edit().putInt("account_color:" + account.getUuid(), color.intValue()).commit();
3164            }
3165            account.setShowErrorNotification(true);
3166            this.statusListener.onStatusChanged(account);
3167            databaseBackend.updateAccount(account);
3168            reconnectAccountInBackground(account);
3169            updateAccountUi();
3170            getNotificationService().updateErrorNotification();
3171            toggleForegroundService();
3172            syncEnabledAccountSetting();
3173            mChannelDiscoveryService.cleanCache();
3174            if (CallIntegration.hasSystemFeature(this)) {
3175                CallIntegrationConnectionService.togglePhoneAccountAsync(this, account);
3176            }
3177            return true;
3178        } else {
3179            return false;
3180        }
3181    }
3182
3183    public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
3184        final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
3185        sendIqPacket(account, iq, (a, packet) -> {
3186            if (packet.getType() == IqPacket.TYPE.RESULT) {
3187                a.setPassword(newPassword);
3188                a.setOption(Account.OPTION_MAGIC_CREATE, false);
3189                databaseBackend.updateAccount(a);
3190                callback.onPasswordChangeSucceeded();
3191            } else {
3192                callback.onPasswordChangeFailed();
3193            }
3194        });
3195    }
3196
3197    public void unregisterAccount(final Account account, final Consumer<Boolean> callback) {
3198        final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
3199        final Element query = iqPacket.addChild("query",Namespace.REGISTER);
3200        query.addChild("remove");
3201        sendIqPacket(account, iqPacket, (a, response) -> {
3202            if (response.getType() == IqPacket.TYPE.RESULT) {
3203                deleteAccount(a);
3204                callback.accept(true);
3205            } else {
3206                callback.accept(false);
3207            }
3208        });
3209    }
3210
3211    public void deleteAccount(final Account account) {
3212        getPreferences().edit().remove("onboarding_continued").commit();
3213        final boolean connected = account.getStatus() == Account.State.ONLINE;
3214        synchronized (this.conversations) {
3215            if (connected) {
3216                account.getAxolotlService().deleteOmemoIdentity();
3217            }
3218            for (final Conversation conversation : conversations) {
3219                if (conversation.getAccount() == account) {
3220                    if (conversation.getMode() == Conversation.MODE_MULTI) {
3221                        if (connected) {
3222                            leaveMuc(conversation);
3223                        }
3224                    }
3225                    conversations.remove(conversation);
3226                    mNotificationService.clear(conversation);
3227                }
3228            }
3229            new Thread(() -> {
3230                for (final Contact contact : account.getRoster().getContacts()) {
3231                    contact.unregisterAsPhoneAccount(this);
3232                }
3233            }).start();
3234            if (account.getXmppConnection() != null) {
3235                new Thread(() -> disconnect(account, !connected)).start();
3236            }
3237            final Runnable runnable = () -> {
3238                if (!databaseBackend.deleteAccount(account)) {
3239                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
3240                }
3241            };
3242            mDatabaseWriterExecutor.execute(runnable);
3243            this.accounts.remove(account);
3244            if (CallIntegration.hasSystemFeature(this)) {
3245                CallIntegrationConnectionService.unregisterPhoneAccount(this, account);
3246            }
3247            this.mRosterSyncTaskManager.clear(account);
3248            updateAccountUi();
3249            mNotificationService.updateErrorNotification();
3250            syncEnabledAccountSetting();
3251            toggleForegroundService();
3252        }
3253    }
3254
3255    public void setOnConversationListChangedListener(OnConversationUpdate listener) {
3256        final boolean remainingListeners;
3257        synchronized (LISTENER_LOCK) {
3258            remainingListeners = checkListeners();
3259            if (!this.mOnConversationUpdates.add(listener)) {
3260                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as ConversationListChangedListener");
3261            }
3262            this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
3263        }
3264        if (remainingListeners) {
3265            switchToForeground();
3266        }
3267    }
3268
3269    public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
3270        final boolean remainingListeners;
3271        synchronized (LISTENER_LOCK) {
3272            this.mOnConversationUpdates.remove(listener);
3273            this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
3274            remainingListeners = checkListeners();
3275        }
3276        if (remainingListeners) {
3277            switchToBackground();
3278        }
3279    }
3280
3281    public void setOnShowErrorToastListener(OnShowErrorToast listener) {
3282        final boolean remainingListeners;
3283        synchronized (LISTENER_LOCK) {
3284            remainingListeners = checkListeners();
3285            if (!this.mOnShowErrorToasts.add(listener)) {
3286                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnShowErrorToastListener");
3287            }
3288        }
3289        if (remainingListeners) {
3290            switchToForeground();
3291        }
3292    }
3293
3294    public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
3295        final boolean remainingListeners;
3296        synchronized (LISTENER_LOCK) {
3297            this.mOnShowErrorToasts.remove(onShowErrorToast);
3298            remainingListeners = checkListeners();
3299        }
3300        if (remainingListeners) {
3301            switchToBackground();
3302        }
3303    }
3304
3305    public void setOnAccountListChangedListener(OnAccountUpdate listener) {
3306        final boolean remainingListeners;
3307        synchronized (LISTENER_LOCK) {
3308            remainingListeners = checkListeners();
3309            if (!this.mOnAccountUpdates.add(listener)) {
3310                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnAccountListChangedtListener");
3311            }
3312        }
3313        if (remainingListeners) {
3314            switchToForeground();
3315        }
3316    }
3317
3318    public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
3319        final boolean remainingListeners;
3320        synchronized (LISTENER_LOCK) {
3321            this.mOnAccountUpdates.remove(listener);
3322            remainingListeners = checkListeners();
3323        }
3324        if (remainingListeners) {
3325            switchToBackground();
3326        }
3327    }
3328
3329    public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
3330        final boolean remainingListeners;
3331        synchronized (LISTENER_LOCK) {
3332            remainingListeners = checkListeners();
3333            if (!this.mOnCaptchaRequested.add(listener)) {
3334                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnCaptchaRequestListener");
3335            }
3336        }
3337        if (remainingListeners) {
3338            switchToForeground();
3339        }
3340    }
3341
3342    public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
3343        final boolean remainingListeners;
3344        synchronized (LISTENER_LOCK) {
3345            this.mOnCaptchaRequested.remove(listener);
3346            remainingListeners = checkListeners();
3347        }
3348        if (remainingListeners) {
3349            switchToBackground();
3350        }
3351    }
3352
3353    public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
3354        final boolean remainingListeners;
3355        synchronized (LISTENER_LOCK) {
3356            remainingListeners = checkListeners();
3357            if (!this.mOnRosterUpdates.add(listener)) {
3358                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnRosterUpdateListener");
3359            }
3360        }
3361        if (remainingListeners) {
3362            switchToForeground();
3363        }
3364    }
3365
3366    public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
3367        final boolean remainingListeners;
3368        synchronized (LISTENER_LOCK) {
3369            this.mOnRosterUpdates.remove(listener);
3370            remainingListeners = checkListeners();
3371        }
3372        if (remainingListeners) {
3373            switchToBackground();
3374        }
3375    }
3376
3377    public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
3378        final boolean remainingListeners;
3379        synchronized (LISTENER_LOCK) {
3380            remainingListeners = checkListeners();
3381            if (!this.mOnUpdateBlocklist.add(listener)) {
3382                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnUpdateBlocklistListener");
3383            }
3384        }
3385        if (remainingListeners) {
3386            switchToForeground();
3387        }
3388    }
3389
3390    public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
3391        final boolean remainingListeners;
3392        synchronized (LISTENER_LOCK) {
3393            this.mOnUpdateBlocklist.remove(listener);
3394            remainingListeners = checkListeners();
3395        }
3396        if (remainingListeners) {
3397            switchToBackground();
3398        }
3399    }
3400
3401    public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
3402        final boolean remainingListeners;
3403        synchronized (LISTENER_LOCK) {
3404            remainingListeners = checkListeners();
3405            if (!this.mOnKeyStatusUpdated.add(listener)) {
3406                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnKeyStatusUpdateListener");
3407            }
3408        }
3409        if (remainingListeners) {
3410            switchToForeground();
3411        }
3412    }
3413
3414    public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
3415        final boolean remainingListeners;
3416        synchronized (LISTENER_LOCK) {
3417            this.mOnKeyStatusUpdated.remove(listener);
3418            remainingListeners = checkListeners();
3419        }
3420        if (remainingListeners) {
3421            switchToBackground();
3422        }
3423    }
3424
3425    public void setOnRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
3426        final boolean remainingListeners;
3427        synchronized (LISTENER_LOCK) {
3428            remainingListeners = checkListeners();
3429            if (!this.onJingleRtpConnectionUpdate.add(listener)) {
3430                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnJingleRtpConnectionUpdate");
3431            }
3432        }
3433        if (remainingListeners) {
3434            switchToForeground();
3435        }
3436    }
3437
3438    public void removeRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
3439        final boolean remainingListeners;
3440        synchronized (LISTENER_LOCK) {
3441            this.onJingleRtpConnectionUpdate.remove(listener);
3442            remainingListeners = checkListeners();
3443        }
3444        if (remainingListeners) {
3445            switchToBackground();
3446        }
3447    }
3448
3449    public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
3450        final boolean remainingListeners;
3451        synchronized (LISTENER_LOCK) {
3452            remainingListeners = checkListeners();
3453            if (!this.mOnMucRosterUpdate.add(listener)) {
3454                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnMucRosterListener");
3455            }
3456        }
3457        if (remainingListeners) {
3458            switchToForeground();
3459        }
3460    }
3461
3462    public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
3463        final boolean remainingListeners;
3464        synchronized (LISTENER_LOCK) {
3465            this.mOnMucRosterUpdate.remove(listener);
3466            remainingListeners = checkListeners();
3467        }
3468        if (remainingListeners) {
3469            switchToBackground();
3470        }
3471    }
3472
3473    public boolean checkListeners() {
3474        return (this.mOnAccountUpdates.size() == 0
3475                && this.mOnConversationUpdates.size() == 0
3476                && this.mOnRosterUpdates.size() == 0
3477                && this.mOnCaptchaRequested.size() == 0
3478                && this.mOnMucRosterUpdate.size() == 0
3479                && this.mOnUpdateBlocklist.size() == 0
3480                && this.mOnShowErrorToasts.size() == 0
3481                && this.onJingleRtpConnectionUpdate.size() == 0
3482                && this.mOnKeyStatusUpdated.size() == 0);
3483    }
3484
3485    private void switchToForeground() {
3486        toggleSoftDisabled(false);
3487        final boolean broadcastLastActivity = broadcastLastActivity();
3488        for (Conversation conversation : getConversations()) {
3489            if (conversation.getMode() == Conversation.MODE_MULTI) {
3490                conversation.getMucOptions().resetChatState();
3491            } else {
3492                conversation.setIncomingChatState(Config.DEFAULT_CHAT_STATE);
3493            }
3494        }
3495        for (Account account : getAccounts()) {
3496            if (account.getStatus() == Account.State.ONLINE) {
3497                account.deactivateGracePeriod();
3498                final XmppConnection connection = account.getXmppConnection();
3499                if (connection != null) {
3500                    if (connection.getFeatures().csi()) {
3501                        connection.sendActive();
3502                    }
3503                    if (broadcastLastActivity) {
3504                        sendPresence(account, false); //send new presence but don't include idle because we are not
3505                    }
3506                }
3507            }
3508        }
3509        Log.d(Config.LOGTAG, "app switched into foreground");
3510    }
3511
3512    private void switchToBackground() {
3513        final boolean broadcastLastActivity = broadcastLastActivity();
3514        if (broadcastLastActivity) {
3515            mLastActivity = System.currentTimeMillis();
3516            final SharedPreferences.Editor editor = getPreferences().edit();
3517            editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
3518            editor.apply();
3519        }
3520        for (Account account : getAccounts()) {
3521            if (account.getStatus() == Account.State.ONLINE) {
3522                XmppConnection connection = account.getXmppConnection();
3523                if (connection != null) {
3524                    if (broadcastLastActivity) {
3525                        sendPresence(account, true);
3526                    }
3527                    if (connection.getFeatures().csi()) {
3528                        connection.sendInactive();
3529                    }
3530                }
3531            }
3532        }
3533        this.mNotificationService.setIsInForeground(false);
3534        Log.d(Config.LOGTAG, "app switched into background");
3535    }
3536
3537    private void connectMultiModeConversations(Account account) {
3538        List<Conversation> conversations = getConversations();
3539        for (Conversation conversation : conversations) {
3540            if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
3541                joinMuc(conversation);
3542            }
3543        }
3544    }
3545
3546    public void mucSelfPingAndRejoin(final Conversation conversation) {
3547        final Account account = conversation.getAccount();
3548        synchronized (account.inProgressConferenceJoins) {
3549            if (account.inProgressConferenceJoins.contains(conversation)) {
3550                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because join is already under way");
3551                return;
3552            }
3553        }
3554        synchronized (account.inProgressConferencePings) {
3555            if (!account.inProgressConferencePings.add(conversation)) {
3556                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because ping is already under way");
3557                return;
3558            }
3559        }
3560        final Jid self = conversation.getMucOptions().getSelf().getFullJid();
3561        final IqPacket ping = new IqPacket(IqPacket.TYPE.GET);
3562        ping.setTo(self);
3563        ping.addChild("ping", Namespace.PING);
3564        sendIqPacket(conversation.getAccount(), ping, (a, response) -> {
3565            if (response.getType() == IqPacket.TYPE.ERROR) {
3566                Element error = response.findChild("error");
3567                if (error == null || error.hasChild("service-unavailable") || error.hasChild("feature-not-implemented") || error.hasChild("item-not-found")) {
3568                    Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back as ignorable error");
3569                } else {
3570                    Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " failed. attempting rejoin");
3571                    joinMuc(conversation);
3572                }
3573            } else if (response.getType() == IqPacket.TYPE.RESULT) {
3574                Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back fine");
3575            }
3576            synchronized (account.inProgressConferencePings) {
3577                account.inProgressConferencePings.remove(conversation);
3578            }
3579        });
3580    }
3581    public void joinMuc(Conversation conversation) {
3582        joinMuc(conversation, null, false);
3583    }
3584
3585    public void joinMuc(Conversation conversation, boolean followedInvite) {
3586        joinMuc(conversation, null, followedInvite);
3587    }
3588
3589    private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
3590        joinMuc(conversation, onConferenceJoined, false);
3591    }
3592
3593    private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
3594        final Account account = conversation.getAccount();
3595        synchronized (account.pendingConferenceJoins) {
3596            account.pendingConferenceJoins.remove(conversation);
3597        }
3598        synchronized (account.pendingConferenceLeaves) {
3599            account.pendingConferenceLeaves.remove(conversation);
3600        }
3601        if (account.getStatus() == Account.State.ONLINE) {
3602            synchronized (account.inProgressConferenceJoins) {
3603                account.inProgressConferenceJoins.add(conversation);
3604            }
3605            if (Config.MUC_LEAVE_BEFORE_JOIN) {
3606                sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
3607            }
3608            conversation.resetMucOptions();
3609            if (onConferenceJoined != null) {
3610                conversation.getMucOptions().flagNoAutoPushConfiguration();
3611            }
3612            conversation.setHasMessagesLeftOnServer(false);
3613            fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
3614
3615                private void join(Conversation conversation) {
3616                    Account account = conversation.getAccount();
3617                    final MucOptions mucOptions = conversation.getMucOptions();
3618
3619                    if (mucOptions.nonanonymous() && !mucOptions.membersOnly() && !conversation.getBooleanAttribute("accept_non_anonymous", false)) {
3620                        synchronized (account.inProgressConferenceJoins) {
3621                            account.inProgressConferenceJoins.remove(conversation);
3622                        }
3623                        mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
3624                        updateConversationUi();
3625                        if (onConferenceJoined != null) {
3626                            onConferenceJoined.onConferenceJoined(conversation);
3627                        }
3628                        return;
3629                    }
3630
3631                    final Jid joinJid = mucOptions.getSelf().getFullJid();
3632                    Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
3633                    PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null, mucOptions.getSelf().getNick());
3634                    packet.setTo(joinJid);
3635                    Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
3636                    if (conversation.getMucOptions().getPassword() != null) {
3637                        x.addChild("password").setContent(mucOptions.getPassword());
3638                    }
3639
3640                    if (mucOptions.mamSupport()) {
3641                        // Use MAM instead of the limited muc history to get history
3642                        x.addChild("history").setAttribute("maxchars", "0");
3643                    } else {
3644                        // Fallback to muc history
3645                        x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
3646                    }
3647                    sendPresencePacket(account, packet);
3648                    if (onConferenceJoined != null) {
3649                        onConferenceJoined.onConferenceJoined(conversation);
3650                    }
3651                    if (!joinJid.equals(conversation.getJid())) {
3652                        conversation.setContactJid(joinJid);
3653                        databaseBackend.updateConversation(conversation);
3654                    }
3655
3656                    maybeRegisterWithMuc(conversation, null);
3657
3658                    if (mucOptions.mamSupport()) {
3659                        getMessageArchiveService().catchupMUC(conversation);
3660                    }
3661                    if (mucOptions.isPrivateAndNonAnonymous()) {
3662                        fetchConferenceMembers(conversation);
3663
3664                        if (followedInvite) {
3665                            final Bookmark bookmark = conversation.getBookmark();
3666                            if (bookmark != null) {
3667                                if (!bookmark.autojoin()) {
3668                                    bookmark.setAutojoin(true);
3669                                    createBookmark(account, bookmark);
3670                                }
3671                            } else {
3672                                saveConversationAsBookmark(conversation, null);
3673                            }
3674                        }
3675                    }
3676                    synchronized (account.inProgressConferenceJoins) {
3677                        account.inProgressConferenceJoins.remove(conversation);
3678                        sendUnsentMessages(conversation);
3679                    }
3680                }
3681
3682                @Override
3683                public void onConferenceConfigurationFetched(Conversation conversation) {
3684                    if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3685                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
3686                        return;
3687                    }
3688                    join(conversation);
3689                }
3690
3691                @Override
3692                public void onFetchFailed(final Conversation conversation, final String errorCondition) {
3693                    if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3694                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
3695                        return;
3696                    }
3697                    if ("remote-server-not-found".equals(errorCondition)) {
3698                        synchronized (account.inProgressConferenceJoins) {
3699                            account.inProgressConferenceJoins.remove(conversation);
3700                        }
3701                        conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
3702                        updateConversationUi();
3703                    } else {
3704                        join(conversation);
3705                        fetchConferenceConfiguration(conversation);
3706                    }
3707                }
3708            });
3709            updateConversationUi();
3710        } else {
3711            synchronized (account.pendingConferenceJoins) {
3712                account.pendingConferenceJoins.add(conversation);
3713            }
3714            conversation.resetMucOptions();
3715            conversation.setHasMessagesLeftOnServer(false);
3716            updateConversationUi();
3717        }
3718    }
3719
3720    private void fetchConferenceMembers(final Conversation conversation) {
3721        final Account account = conversation.getAccount();
3722        final AxolotlService axolotlService = account.getAxolotlService();
3723        final String[] affiliations = {"member", "admin", "owner"};
3724        OnIqPacketReceived callback = new OnIqPacketReceived() {
3725
3726            private int i = 0;
3727            private boolean success = true;
3728
3729            @Override
3730            public void onIqPacketReceived(Account account, IqPacket packet) {
3731                final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
3732                Element query = packet.query("http://jabber.org/protocol/muc#admin");
3733                if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
3734                    for (Element child : query.getChildren()) {
3735                        if ("item".equals(child.getName())) {
3736                            MucOptions.User user = AbstractParser.parseItem(conversation, child);
3737                            if (!user.realJidMatchesAccount()) {
3738                                boolean isNew = conversation.getMucOptions().updateUser(user);
3739                                Contact contact = user.getContact();
3740                                if (omemoEnabled
3741                                        && isNew
3742                                        && user.getRealJid() != null
3743                                        && (contact == null || !contact.mutualPresenceSubscription())
3744                                        && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
3745                                    axolotlService.fetchDeviceIds(user.getRealJid());
3746                                }
3747                            }
3748                        }
3749                    }
3750                } else {
3751                    success = false;
3752                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
3753                }
3754                ++i;
3755                if (i >= affiliations.length) {
3756                    List<Jid> members = conversation.getMucOptions().getMembers(true);
3757                    if (success) {
3758                        List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
3759                        boolean changed = false;
3760                        for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
3761                            Jid jid = iterator.next();
3762                            if (!members.contains(jid) && !members.contains(jid.getDomain())) {
3763                                iterator.remove();
3764                                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
3765                                changed = true;
3766                            }
3767                        }
3768                        if (changed) {
3769                            conversation.setAcceptedCryptoTargets(cryptoTargets);
3770                            updateConversation(conversation);
3771                        }
3772                    }
3773                    getAvatarService().clear(conversation);
3774                    updateMucRosterUi();
3775                    updateConversationUi();
3776                }
3777            }
3778        };
3779        for (String affiliation : affiliations) {
3780            sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
3781        }
3782        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
3783    }
3784
3785    public void providePasswordForMuc(final Conversation conversation, final String password) {
3786        if (conversation.getMode() == Conversation.MODE_MULTI) {
3787            conversation.getMucOptions().setPassword(password);
3788            if (conversation.getBookmark() != null) {
3789                final Bookmark bookmark = conversation.getBookmark();
3790                bookmark.setAutojoin(true);
3791                createBookmark(conversation.getAccount(), bookmark);
3792            }
3793            updateConversation(conversation);
3794            joinMuc(conversation);
3795        }
3796    }
3797
3798    public void deleteAvatar(final Account account) {
3799        final AtomicBoolean executed = new AtomicBoolean(false);
3800        final Runnable onDeleted =
3801                () -> {
3802                    if (executed.compareAndSet(false, true)) {
3803                        account.setAvatar(null);
3804                        databaseBackend.updateAccount(account);
3805                        getAvatarService().clear(account);
3806                        updateAccountUi();
3807                    }
3808                };
3809        deleteVcardAvatar(account, onDeleted);
3810        deletePepNode(account, Namespace.AVATAR_DATA);
3811        deletePepNode(account, Namespace.AVATAR_METADATA, onDeleted);
3812    }
3813
3814    public void deletePepNode(final Account account, final String node) {
3815        deletePepNode(account, node, null);
3816    }
3817
3818    private void deletePepNode(final Account account, final String node, final Runnable runnable) {
3819        final IqPacket request = mIqGenerator.deleteNode(node);
3820        sendIqPacket(account, request, (a, packet) -> {
3821            if (packet.getType() == IqPacket.TYPE.RESULT) {
3822                Log.d(Config.LOGTAG,a.getJid().asBareJid()+": successfully deleted pep node "+node);
3823                if (runnable != null) {
3824                    runnable.run();
3825                }
3826            } else {
3827                Log.d(Config.LOGTAG,a.getJid().asBareJid()+": failed to delete "+ packet);
3828            }
3829        });
3830    }
3831
3832    private void deleteVcardAvatar(final Account account, @NonNull final Runnable runnable) {
3833        final IqPacket retrieveVcard = mIqGenerator.retrieveVcardAvatar(account.getJid().asBareJid());
3834        sendIqPacket(account, retrieveVcard, (a, response) -> {
3835            if (response.getType() != IqPacket.TYPE.RESULT) {
3836                Log.d(Config.LOGTAG,a.getJid().asBareJid()+": no vCard set. nothing to do");
3837                return;
3838            }
3839            final Element vcard = response.findChild("vCard", "vcard-temp");
3840            if (vcard == null) {
3841                Log.d(Config.LOGTAG,a.getJid().asBareJid()+": no vCard set. nothing to do");
3842                return;
3843            }
3844            Element photo = vcard.findChild("PHOTO");
3845            if (photo == null) {
3846                photo = vcard.addChild("PHOTO");
3847            }
3848            photo.clearChildren();
3849            IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3850            publication.setTo(a.getJid().asBareJid());
3851            publication.addChild(vcard);
3852            sendIqPacket(account, publication, (a1, publicationResponse) -> {
3853                if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3854                    Log.d(Config.LOGTAG,a1.getJid().asBareJid()+": successfully deleted vcard avatar");
3855                    runnable.run();
3856                } else {
3857                    Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
3858                }
3859            });
3860        });
3861    }
3862
3863    private boolean hasEnabledAccounts() {
3864        if (this.accounts == null) {
3865            return false;
3866        }
3867        for (final Account account : this.accounts) {
3868            if (account.isConnectionEnabled()) {
3869                return true;
3870            }
3871        }
3872        return false;
3873    }
3874
3875
3876    public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
3877        getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
3878    }
3879
3880    public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3881        getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
3882    }
3883
3884
3885    public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3886        new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
3887    }
3888
3889    public void persistSelfNick(final MucOptions.User self) {
3890        final Conversation conversation = self.getConversation();
3891        final boolean tookProposedNickFromBookmark = conversation.getMucOptions().isTookProposedNickFromBookmark();
3892        Jid full = self.getFullJid();
3893        if (!full.equals(conversation.getJid())) {
3894            Log.d(Config.LOGTAG, "nick changed. updating");
3895            conversation.setContactJid(full);
3896            databaseBackend.updateConversation(conversation);
3897        }
3898
3899        final String nick = self.getNick();
3900        final Bookmark bookmark = conversation.getBookmark();
3901        final String bookmarkedNick = bookmark == null ? null : bookmark.getNick();
3902        if (bookmark != null && (tookProposedNickFromBookmark || Strings.isNullOrEmpty(bookmarkedNick)) && !nick.equals(bookmarkedNick)) {
3903            final Account account = conversation.getAccount();
3904            final String defaultNick = MucOptions.defaultNick(account);
3905            if (Strings.isNullOrEmpty(bookmarkedNick) && full.getResource().equals(defaultNick)) {
3906                return;
3907            }
3908            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persist nick '" + nick + "' into bookmark for " + conversation.getJid().asBareJid());
3909            bookmark.setNick(nick);
3910            createBookmark(bookmark.getAccount(), bookmark);
3911        }
3912    }
3913
3914    public void presenceToMuc(final Conversation conversation) {
3915        final MucOptions options = conversation.getMucOptions();
3916        if (options.online()) {
3917            Account account = conversation.getAccount();
3918            final Jid joinJid = options.getSelf().getFullJid();
3919            final PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous(), options.getSelf().getNick());
3920            packet.setTo(joinJid);
3921            sendPresencePacket(account, packet);
3922        }
3923    }
3924
3925    public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
3926        final MucOptions options = conversation.getMucOptions();
3927        final Jid joinJid = options.createJoinJid(nick);
3928        if (joinJid == null) {
3929            return false;
3930        }
3931        if (options.online()) {
3932            maybeRegisterWithMuc(conversation, nick);
3933
3934            Account account = conversation.getAccount();
3935            options.setOnRenameListener(new OnRenameListener() {
3936
3937                @Override
3938                public void onSuccess() {
3939                    final PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous(), nick);
3940                    packet.setTo(joinJid);
3941                    sendPresencePacket(account, packet);
3942                    callback.success(conversation);
3943                }
3944
3945                @Override
3946                public void onFailure() {
3947                    callback.error(R.string.nick_in_use, conversation);
3948                }
3949            });
3950
3951            final PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous(), nick);
3952            packet.setTo(joinJid);
3953            sendPresencePacket(account, packet);
3954        } else {
3955            conversation.setContactJid(joinJid);
3956            databaseBackend.updateConversation(conversation);
3957            if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
3958                Bookmark bookmark = conversation.getBookmark();
3959                if (bookmark != null) {
3960                    bookmark.setNick(nick);
3961                    createBookmark(bookmark.getAccount(), bookmark);
3962                }
3963                joinMuc(conversation);
3964            }
3965        }
3966        return true;
3967    }
3968
3969    public void leaveMuc(Conversation conversation) {
3970        leaveMuc(conversation, false);
3971    }
3972
3973    private void leaveMuc(Conversation conversation, boolean now) {
3974        final Account account = conversation.getAccount();
3975        synchronized (account.pendingConferenceJoins) {
3976            account.pendingConferenceJoins.remove(conversation);
3977        }
3978        synchronized (account.pendingConferenceLeaves) {
3979            account.pendingConferenceLeaves.remove(conversation);
3980        }
3981        if (account.getStatus() == Account.State.ONLINE || now) {
3982            sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
3983            conversation.getMucOptions().setOffline();
3984            Bookmark bookmark = conversation.getBookmark();
3985            if (bookmark != null) {
3986                bookmark.setConversation(null);
3987            }
3988            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
3989        } else {
3990            synchronized (account.pendingConferenceLeaves) {
3991                account.pendingConferenceLeaves.add(conversation);
3992            }
3993        }
3994    }
3995
3996    public String findConferenceServer(final Account account) {
3997        String server;
3998        if (account.getXmppConnection() != null) {
3999            server = account.getXmppConnection().getMucServer();
4000            if (server != null) {
4001                return server;
4002            }
4003        }
4004        for (Account other : getAccounts()) {
4005            if (other != account && other.getXmppConnection() != null) {
4006                server = other.getXmppConnection().getMucServer();
4007                if (server != null) {
4008                    return server;
4009                }
4010            }
4011        }
4012        return null;
4013    }
4014
4015
4016    public void createPublicChannel(final Account account, final String name, final Jid address, final UiCallback<Conversation> callback) {
4017        joinMuc(findOrCreateConversation(account, address, true, false, true), conversation -> {
4018            final Bundle configuration = IqGenerator.defaultChannelConfiguration();
4019            if (!TextUtils.isEmpty(name)) {
4020                configuration.putString("muc#roomconfig_roomname", name);
4021            }
4022            pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
4023                @Override
4024                public void onPushSucceeded() {
4025                    saveConversationAsBookmark(conversation, name);
4026                    callback.success(conversation);
4027                }
4028
4029                @Override
4030                public void onPushFailed() {
4031                    if (conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
4032                        callback.error(R.string.unable_to_set_channel_configuration, conversation);
4033                    } else {
4034                        callback.error(R.string.joined_an_existing_channel, conversation);
4035                    }
4036                }
4037            });
4038        });
4039    }
4040
4041    public boolean createAdhocConference(final Account account,
4042                                         final String name,
4043                                         final Iterable<Jid> jids,
4044                                         final UiCallback<Conversation> callback) {
4045        Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
4046        if (account.getStatus() == Account.State.ONLINE) {
4047            try {
4048                String server = findConferenceServer(account);
4049                if (server == null) {
4050                    if (callback != null) {
4051                        callback.error(R.string.no_conference_server_found, null);
4052                    }
4053                    return false;
4054                }
4055                final Jid jid = Jid.of(CryptoHelper.pronounceable(), server, null);
4056                final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
4057                joinMuc(conversation, new OnConferenceJoined() {
4058                    @Override
4059                    public void onConferenceJoined(final Conversation conversation) {
4060                        final Bundle configuration = IqGenerator.defaultGroupChatConfiguration();
4061                        if (!TextUtils.isEmpty(name)) {
4062                            configuration.putString("muc#roomconfig_roomname", name);
4063                        }
4064                        pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
4065                            @Override
4066                            public void onPushSucceeded() {
4067                                for (Jid invite : jids) {
4068                                    invite(conversation, invite);
4069                                }
4070                                for (String resource : account.getSelfContact().getPresences().toResourceArray()) {
4071                                    if (resource == null || "".equals(resource)) continue;
4072                                    Jid other = account.getJid().withResource(resource);
4073                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending direct invite to " + other);
4074                                    directInvite(conversation, other);
4075                                }
4076                                saveConversationAsBookmark(conversation, name);
4077                                if (callback != null) {
4078                                    callback.success(conversation);
4079                                }
4080                            }
4081
4082                            @Override
4083                            public void onPushFailed() {
4084                                archiveConversation(conversation);
4085                                if (callback != null) {
4086                                    callback.error(R.string.conference_creation_failed, conversation);
4087                                }
4088                            }
4089                        });
4090                    }
4091                });
4092                return true;
4093            } catch (IllegalArgumentException e) {
4094                if (callback != null) {
4095                    callback.error(R.string.conference_creation_failed, null);
4096                }
4097                return false;
4098            }
4099        } else {
4100            if (callback != null) {
4101                callback.error(R.string.not_connected_try_again, null);
4102            }
4103            return false;
4104        }
4105    }
4106
4107    public void checkIfMuc(final Account account, final Jid jid, Consumer<Boolean> cb) {
4108        if (jid.isDomainJid()) {
4109            // Spec basically says MUC needs to have a node
4110            // And also specifies that MUC and MUC service should have the same identity...
4111            cb.accept(false);
4112            return;
4113        }
4114
4115        IqPacket request = mIqGenerator.queryDiscoInfo(jid.asBareJid());
4116        sendIqPacket(account, request, (acct, reply) -> {
4117            ServiceDiscoveryResult result = new ServiceDiscoveryResult(reply);
4118            cb.accept(
4119                result.getFeatures().contains("http://jabber.org/protocol/muc") &&
4120                result.hasIdentity("conference", null)
4121            );
4122        });
4123    }
4124
4125    public void fetchConferenceConfiguration(final Conversation conversation) {
4126        fetchConferenceConfiguration(conversation, null);
4127    }
4128
4129    public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
4130        IqPacket request = mIqGenerator.queryDiscoInfo(conversation.getJid().asBareJid());
4131        sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
4132            @Override
4133            public void onIqPacketReceived(Account account, IqPacket packet) {
4134                if (packet.getType() == IqPacket.TYPE.RESULT) {
4135                    final MucOptions mucOptions = conversation.getMucOptions();
4136                    final Bookmark bookmark = conversation.getBookmark();
4137                    final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
4138
4139                    if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
4140                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
4141                        updateConversation(conversation);
4142                    }
4143
4144                    if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
4145                        if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
4146                            createBookmark(account, bookmark);
4147                        }
4148                    }
4149
4150
4151                    if (callback != null) {
4152                        callback.onConferenceConfigurationFetched(conversation);
4153                    }
4154
4155
4156                    updateConversationUi();
4157                } else if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
4158                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received timeout waiting for conference configuration fetch");
4159                } else {
4160                    if (callback != null) {
4161                        callback.onFetchFailed(conversation, packet.getErrorCondition());
4162                    }
4163                }
4164            }
4165        });
4166    }
4167
4168    public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
4169        pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
4170    }
4171
4172    public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
4173        Log.d(Config.LOGTAG, "pushing node configuration");
4174        sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
4175            @Override
4176            public void onIqPacketReceived(Account account, IqPacket packet) {
4177                if (packet.getType() == IqPacket.TYPE.RESULT) {
4178                    Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
4179                    Element configuration = pubsub == null ? null : pubsub.findChild("configure");
4180                    Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
4181                    if (x != null) {
4182                        Data data = Data.parse(x);
4183                        data.submit(options);
4184                        sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
4185                            @Override
4186                            public void onIqPacketReceived(Account account, IqPacket packet) {
4187                                if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
4188                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully changed node configuration for node " + node);
4189                                    callback.onPushSucceeded();
4190                                } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
4191                                    callback.onPushFailed();
4192                                }
4193                            }
4194                        });
4195                    } else if (callback != null) {
4196                        callback.onPushFailed();
4197                    }
4198                } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
4199                    callback.onPushFailed();
4200                }
4201            }
4202        });
4203    }
4204
4205    public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
4206        if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
4207            conversation.setAttribute("accept_non_anonymous", true);
4208            updateConversation(conversation);
4209        }
4210        if (options.containsKey("muc#roomconfig_moderatedroom")) {
4211            final boolean moderated = "1".equals(options.getString("muc#roomconfig_moderatedroom"));
4212            options.putString("members_by_default", moderated ? "0" : "1");
4213        }
4214        final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4215        request.setTo(conversation.getJid().asBareJid());
4216        request.query("http://jabber.org/protocol/muc#owner");
4217        sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
4218            @Override
4219            public void onIqPacketReceived(Account account, IqPacket packet) {
4220                if (packet.getType() == IqPacket.TYPE.RESULT) {
4221                    final Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
4222                    data.submit(options);
4223                    final IqPacket set = new IqPacket(IqPacket.TYPE.SET);
4224                    set.setTo(conversation.getJid().asBareJid());
4225                    set.query("http://jabber.org/protocol/muc#owner").addChild(data);
4226                    sendIqPacket(account, set, new OnIqPacketReceived() {
4227                        @Override
4228                        public void onIqPacketReceived(Account account, IqPacket packet) {
4229                            if (callback != null) {
4230                                if (packet.getType() == IqPacket.TYPE.RESULT) {
4231                                    callback.onPushSucceeded();
4232                                } else {
4233                                    callback.onPushFailed();
4234                                }
4235                            }
4236                        }
4237                    });
4238                } else {
4239                    if (callback != null) {
4240                        callback.onPushFailed();
4241                    }
4242                }
4243            }
4244        });
4245    }
4246
4247    public void pushSubjectToConference(final Conversation conference, final String subject) {
4248        MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
4249        this.sendMessagePacket(conference.getAccount(), packet);
4250    }
4251
4252    public void requestVoice(final Account account, final Jid jid) {
4253        MessagePacket packet = this.getMessageGenerator().requestVoice(jid);
4254        this.sendMessagePacket(account, packet);
4255    }
4256
4257    public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
4258        final Jid jid = user.asBareJid();
4259        final IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
4260        sendIqPacket(conference.getAccount(), request, (account, response) -> {
4261            if (response.getType() == IqPacket.TYPE.RESULT) {
4262                conference.getMucOptions().changeAffiliation(jid, affiliation);
4263                getAvatarService().clear(conference);
4264                if (callback != null) {
4265                    callback.onAffiliationChangedSuccessful(jid);
4266                } else {
4267                    Log.d(Config.LOGTAG, "changed affiliation of " + user + " to " + affiliation);
4268                }
4269            } else if (callback != null) {
4270                callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
4271            } else {
4272                Log.d(Config.LOGTAG, "unable to change affiliation");
4273            }
4274        });
4275    }
4276
4277    public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) {
4278        IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
4279        sendIqPacket(conference.getAccount(), request, (account, packet) -> {
4280            if (packet.getType() != IqPacket.TYPE.RESULT) {
4281                Log.d(Config.LOGTAG, account.getJid().asBareJid() + " unable to change role of " + nick);
4282            }
4283        });
4284    }
4285
4286    public void moderateMessage(final Account account, final Message m, final String reason) {
4287        IqPacket request = this.mIqGenerator.moderateMessage(account, m, reason);
4288        sendIqPacket(account, request, (a, packet) -> {
4289            if (packet.getType() != IqPacket.TYPE.RESULT) {
4290                showErrorToastInUi(R.string.unable_to_moderate);
4291                Log.d(Config.LOGTAG, a.getJid().asBareJid() + " unable to moderate: " + packet);
4292            }
4293        });
4294    }
4295
4296    public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
4297        IqPacket request = new IqPacket(IqPacket.TYPE.SET);
4298        request.setTo(conversation.getJid().asBareJid());
4299        request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
4300        sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
4301            @Override
4302            public void onIqPacketReceived(Account account, IqPacket packet) {
4303                if (packet.getType() == IqPacket.TYPE.RESULT) {
4304                    if (callback != null) {
4305                        callback.onRoomDestroySucceeded();
4306                    }
4307                } else if (packet.getType() == IqPacket.TYPE.ERROR) {
4308                    if (callback != null) {
4309                        callback.onRoomDestroyFailed();
4310                    }
4311                }
4312            }
4313        });
4314    }
4315
4316    private void disconnect(final Account account, boolean force) {
4317        final XmppConnection connection = account.getXmppConnection();
4318        if (connection == null) {
4319            return;
4320        }
4321        if (!force) {
4322            final List<Conversation> conversations = getConversations();
4323            for (Conversation conversation : conversations) {
4324                if (conversation.getAccount() == account) {
4325                    if (conversation.getMode() == Conversation.MODE_MULTI) {
4326                        leaveMuc(conversation, true);
4327                    }
4328                }
4329            }
4330            sendOfflinePresence(account);
4331        }
4332        connection.disconnect(force);
4333    }
4334
4335    @Override
4336    public IBinder onBind(Intent intent) {
4337        return mBinder;
4338    }
4339
4340    public void updateMessage(Message message) {
4341        updateMessage(message, true);
4342    }
4343
4344    public void updateMessage(Message message, boolean includeBody) {
4345        databaseBackend.updateMessage(message, includeBody);
4346        updateConversationUi();
4347    }
4348
4349    public void createMessageAsync(final Message message) {
4350        mDatabaseWriterExecutor.execute(() -> databaseBackend.createMessage(message));
4351    }
4352
4353    public void updateMessage(Message message, String uuid) {
4354        if (!databaseBackend.updateMessage(message, uuid)) {
4355            Log.e(Config.LOGTAG, "error updated message in DB after edit");
4356        }
4357        updateConversationUi();
4358    }
4359
4360    protected void syncDirtyContacts(Account account) {
4361        for (Contact contact : account.getRoster().getContacts()) {
4362            if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
4363                pushContactToServer(contact);
4364            }
4365            if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
4366                deleteContactOnServer(contact);
4367            }
4368        }
4369    }
4370
4371    protected void unregisterPhoneAccounts(final Account account) {
4372        for (final Contact contact : account.getRoster().getContacts()) {
4373            if (!contact.showInRoster()) {
4374                contact.unregisterAsPhoneAccount(this);
4375            }
4376        }
4377    }
4378
4379    public void createContact(final Contact contact, final boolean autoGrant) {
4380        createContact(contact, autoGrant, null);
4381    }
4382
4383    public void createContact(final Contact contact, final boolean autoGrant, final String preAuth) {
4384        if (autoGrant) {
4385            contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
4386            contact.setOption(Contact.Options.ASKING);
4387        }
4388        pushContactToServer(contact, preAuth);
4389    }
4390
4391    public void pushContactToServer(final Contact contact) {
4392        pushContactToServer(contact, null);
4393    }
4394
4395    private void pushContactToServer(final Contact contact, final String preAuth) {
4396        contact.resetOption(Contact.Options.DIRTY_DELETE);
4397        contact.setOption(Contact.Options.DIRTY_PUSH);
4398        final Account account = contact.getAccount();
4399        if (account.getStatus() == Account.State.ONLINE) {
4400            final boolean ask = contact.getOption(Contact.Options.ASKING);
4401            final boolean sendUpdates = contact
4402                    .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
4403                    && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
4404            final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
4405            iq.query(Namespace.ROSTER).addChild(contact.asElement());
4406            account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
4407            if (sendUpdates) {
4408                sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
4409            }
4410            if (ask) {
4411                sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact, preAuth));
4412            }
4413        } else {
4414            syncRoster(contact.getAccount());
4415        }
4416    }
4417
4418    public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
4419        new Thread(() -> {
4420            final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
4421            final int size = Config.AVATAR_SIZE;
4422            final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
4423            if (avatar != null) {
4424                if (!getFileBackend().save(avatar)) {
4425                    callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
4426                    return;
4427                }
4428                avatar.owner = conversation.getJid().asBareJid();
4429                publishMucAvatar(conversation, avatar, callback);
4430            } else {
4431                callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
4432            }
4433        }).start();
4434    }
4435
4436    public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
4437        new Thread(() -> {
4438            final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
4439            final int size = Config.AVATAR_SIZE;
4440            final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
4441            if (avatar != null) {
4442                if (!getFileBackend().save(avatar)) {
4443                    Log.d(Config.LOGTAG, "unable to save vcard");
4444                    callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
4445                    return;
4446                }
4447                publishAvatar(account, avatar, callback);
4448            } else {
4449                callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
4450            }
4451        }).start();
4452
4453    }
4454
4455    private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
4456        final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
4457        sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
4458            boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
4459            if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
4460                Element vcard = response.findChild("vCard", "vcard-temp");
4461                if (vcard == null) {
4462                    vcard = new Element("vCard", "vcard-temp");
4463                }
4464                Element photo = vcard.findChild("PHOTO");
4465                if (photo == null) {
4466                    photo = vcard.addChild("PHOTO");
4467                }
4468                photo.clearChildren();
4469                photo.addChild("TYPE").setContent(avatar.type);
4470                photo.addChild("BINVAL").setContent(avatar.image);
4471                IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
4472                publication.setTo(conversation.getJid().asBareJid());
4473                publication.addChild(vcard);
4474                sendIqPacket(account, publication, (a1, publicationResponse) -> {
4475                    if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
4476                        callback.onAvatarPublicationSucceeded();
4477                    } else {
4478                        Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
4479                        callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
4480                    }
4481                });
4482            } else {
4483                Log.d(Config.LOGTAG, "failed to request vcard " + response);
4484                callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
4485            }
4486        });
4487    }
4488
4489    public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
4490        final Bundle options;
4491        if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
4492            options = PublishOptions.openAccess();
4493        } else {
4494            options = null;
4495        }
4496        publishAvatar(account, avatar, options, true, callback);
4497    }
4498
4499    public void publishAvatar(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
4500        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": publishing avatar. options=" + options);
4501        IqPacket packet = this.mIqGenerator.publishAvatar(avatar, options);
4502        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4503
4504            @Override
4505            public void onIqPacketReceived(Account account, IqPacket result) {
4506                if (result.getType() == IqPacket.TYPE.RESULT) {
4507                    publishAvatarMetadata(account, avatar, options, true, callback);
4508                } else if (retry && PublishOptions.preconditionNotMet(result)) {
4509                    pushNodeConfiguration(account, Namespace.AVATAR_DATA, options, new OnConfigurationPushed() {
4510                        @Override
4511                        public void onPushSucceeded() {
4512                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar node");
4513                            publishAvatar(account, avatar, options, false, callback);
4514                        }
4515
4516                        @Override
4517                        public void onPushFailed() {
4518                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar node");
4519                            publishAvatar(account, avatar, null, false, callback);
4520                        }
4521                    });
4522                } else {
4523                    Element error = result.findChild("error");
4524                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
4525                    if (callback != null) {
4526                        callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
4527                    }
4528                }
4529            }
4530        });
4531    }
4532
4533    public void publishAvatarMetadata(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
4534        final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
4535        sendIqPacket(account, packet, new OnIqPacketReceived() {
4536            @Override
4537            public void onIqPacketReceived(Account account, IqPacket result) {
4538                if (result.getType() == IqPacket.TYPE.RESULT) {
4539                    if (account.setAvatar(avatar.getFilename())) {
4540                        getAvatarService().clear(account);
4541                        databaseBackend.updateAccount(account);
4542                        notifyAccountAvatarHasChanged(account);
4543                    }
4544                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
4545                    if (callback != null) {
4546                        callback.onAvatarPublicationSucceeded();
4547                    }
4548                } else if (retry && PublishOptions.preconditionNotMet(result)) {
4549                    pushNodeConfiguration(account, Namespace.AVATAR_METADATA, options, new OnConfigurationPushed() {
4550                        @Override
4551                        public void onPushSucceeded() {
4552                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar meta data node");
4553                            publishAvatarMetadata(account, avatar, options, false, callback);
4554                        }
4555
4556                        @Override
4557                        public void onPushFailed() {
4558                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar meta data node");
4559                            publishAvatarMetadata(account, avatar, null, false, callback);
4560                        }
4561                    });
4562                } else {
4563                    if (callback != null) {
4564                        callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
4565                    }
4566                }
4567            }
4568        });
4569    }
4570
4571    public void republishAvatarIfNeeded(Account account) {
4572        if (account.getAxolotlService().isPepBroken()) {
4573            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
4574            return;
4575        }
4576        IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4577        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4578
4579            private Avatar parseAvatar(IqPacket packet) {
4580                Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
4581                if (pubsub != null) {
4582                    Element items = pubsub.findChild("items");
4583                    if (items != null) {
4584                        return Avatar.parseMetadata(items);
4585                    }
4586                }
4587                return null;
4588            }
4589
4590            private boolean errorIsItemNotFound(IqPacket packet) {
4591                Element error = packet.findChild("error");
4592                return packet.getType() == IqPacket.TYPE.ERROR
4593                        && error != null
4594                        && error.hasChild("item-not-found");
4595            }
4596
4597            @Override
4598            public void onIqPacketReceived(Account account, IqPacket packet) {
4599                if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
4600                    Avatar serverAvatar = parseAvatar(packet);
4601                    if (serverAvatar == null && account.getAvatar() != null) {
4602                        Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
4603                        if (avatar != null) {
4604                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
4605                            publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
4606                        } else {
4607                            Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
4608                        }
4609                    }
4610                }
4611            }
4612        });
4613    }
4614
4615    public void fetchAvatar(Account account, Avatar avatar) {
4616        fetchAvatar(account, avatar, null);
4617    }
4618
4619    public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4620        if (databaseBackend.isBlockedMedia(avatar.cid())) {
4621            if (callback != null) callback.error(0, null);
4622            return;
4623        }
4624
4625        final String KEY = generateFetchKey(account, avatar);
4626        synchronized (this.mInProgressAvatarFetches) {
4627            if (mInProgressAvatarFetches.add(KEY)) {
4628                switch (avatar.origin) {
4629                    case PEP:
4630                        this.mInProgressAvatarFetches.add(KEY);
4631                        fetchAvatarPep(account, avatar, callback);
4632                        break;
4633                    case VCARD:
4634                        this.mInProgressAvatarFetches.add(KEY);
4635                        fetchAvatarVcard(account, avatar, callback);
4636                        break;
4637                }
4638            } else if (avatar.origin == Avatar.Origin.PEP) {
4639                mOmittedPepAvatarFetches.add(KEY);
4640            } else {
4641                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": already fetching " + avatar.origin + " avatar for " + avatar.owner);
4642            }
4643        }
4644    }
4645
4646    private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4647        IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
4648        sendIqPacket(account, packet, (a, result) -> {
4649            synchronized (mInProgressAvatarFetches) {
4650                mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
4651            }
4652            final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
4653            if (result.getType() == IqPacket.TYPE.RESULT) {
4654                avatar.image = mIqParser.avatarData(result);
4655                if (avatar.image != null) {
4656                    if (getFileBackend().save(avatar)) {
4657                        if (a.getJid().asBareJid().equals(avatar.owner)) {
4658                            if (a.setAvatar(avatar.getFilename())) {
4659                                databaseBackend.updateAccount(a);
4660                            }
4661                            getAvatarService().clear(a);
4662                            updateConversationUi();
4663                            updateAccountUi();
4664                        } else {
4665                            final Contact contact = a.getRoster().getContact(avatar.owner);
4666                            contact.setAvatar(avatar);
4667                            syncRoster(account);
4668                            getAvatarService().clear(contact);
4669                            updateConversationUi();
4670                            updateRosterUi();
4671                        }
4672                        if (callback != null) {
4673                            callback.success(avatar);
4674                        }
4675                        Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": successfully fetched pep avatar for " + avatar.owner);
4676                        return;
4677                    }
4678                } else {
4679
4680                    Log.d(Config.LOGTAG, ERROR + "(parsing error)");
4681                }
4682            } else {
4683                Element error = result.findChild("error");
4684                if (error == null) {
4685                    Log.d(Config.LOGTAG, ERROR + "(server error)");
4686                } else {
4687                    Log.d(Config.LOGTAG, ERROR + error.toString());
4688                }
4689            }
4690            if (callback != null) {
4691                callback.error(0, null);
4692            }
4693
4694        });
4695    }
4696
4697    private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4698        IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
4699        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4700            @Override
4701            public void onIqPacketReceived(Account account, IqPacket packet) {
4702                final boolean previouslyOmittedPepFetch;
4703                synchronized (mInProgressAvatarFetches) {
4704                    final String KEY = generateFetchKey(account, avatar);
4705                    mInProgressAvatarFetches.remove(KEY);
4706                    previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
4707                }
4708                if (packet.getType() == IqPacket.TYPE.RESULT) {
4709                    Element vCard = packet.findChild("vCard", "vcard-temp");
4710                    Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
4711                    String image = photo != null ? photo.findChildContent("BINVAL") : null;
4712                    if (image != null) {
4713                        avatar.image = image;
4714                        if (getFileBackend().save(avatar)) {
4715                            Log.d(Config.LOGTAG, account.getJid().asBareJid()
4716                                    + ": successfully fetched vCard avatar for " + avatar.owner + " omittedPep=" + previouslyOmittedPepFetch);
4717                            if (avatar.owner.isBareJid()) {
4718                                if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
4719                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
4720                                    account.setAvatar(avatar.getFilename());
4721                                    databaseBackend.updateAccount(account);
4722                                    getAvatarService().clear(account);
4723                                    updateAccountUi();
4724                                } else {
4725                                    final Contact contact = account.getRoster().getContact(avatar.owner);
4726                                    contact.setAvatar(avatar, previouslyOmittedPepFetch);
4727                                    syncRoster(account);
4728                                    getAvatarService().clear(contact);
4729                                    updateRosterUi();
4730                                }
4731                                updateConversationUi();
4732                            } else {
4733                                Conversation conversation = find(account, avatar.owner.asBareJid());
4734                                if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
4735                                    MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
4736                                    if (user != null) {
4737                                        if (user.setAvatar(avatar)) {
4738                                            getAvatarService().clear(user);
4739                                            updateConversationUi();
4740                                            updateMucRosterUi();
4741                                        }
4742                                        if (user.getRealJid() != null) {
4743                                            Contact contact = account.getRoster().getContact(user.getRealJid());
4744                                            contact.setAvatar(avatar);
4745                                            syncRoster(account);
4746                                            getAvatarService().clear(contact);
4747                                            updateRosterUi();
4748                                        }
4749                                    }
4750                                }
4751                            }
4752                        }
4753                    }
4754                }
4755            }
4756        });
4757    }
4758
4759    public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
4760        IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4761        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4762
4763            @Override
4764            public void onIqPacketReceived(Account account, IqPacket packet) {
4765                if (packet.getType() == IqPacket.TYPE.RESULT) {
4766                    Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
4767                    if (pubsub != null) {
4768                        Element items = pubsub.findChild("items");
4769                        if (items != null) {
4770                            Avatar avatar = Avatar.parseMetadata(items);
4771                            if (avatar != null) {
4772                                avatar.owner = account.getJid().asBareJid();
4773                                if (fileBackend.isAvatarCached(avatar)) {
4774                                    if (account.setAvatar(avatar.getFilename())) {
4775                                        databaseBackend.updateAccount(account);
4776                                    }
4777                                    getAvatarService().clear(account);
4778                                    callback.success(avatar);
4779                                } else {
4780                                    fetchAvatarPep(account, avatar, callback);
4781                                }
4782                                return;
4783                            }
4784                        }
4785                    }
4786                }
4787                callback.error(0, null);
4788            }
4789        });
4790    }
4791
4792    public void notifyAccountAvatarHasChanged(final Account account) {
4793        final XmppConnection connection = account.getXmppConnection();
4794        if (connection != null && connection.getFeatures().bookmarksConversion()) {
4795            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar changed. resending presence to online group chats");
4796            for (Conversation conversation : conversations) {
4797                if (conversation.getAccount() == account && conversation.getMode() == Conversational.MODE_MULTI) {
4798                    presenceToMuc(conversation);
4799                }
4800            }
4801        }
4802    }
4803
4804    public void fetchVcard4(Account account, final Contact contact, final Consumer<Element> callback) {
4805        IqPacket packet = this.mIqGenerator.retrieveVcard4(contact.getJid());
4806        sendIqPacket(account, packet, (a, result) -> {
4807            if (result.getType() == IqPacket.TYPE.RESULT) {
4808                final Element item = mIqParser.getItem(result);
4809                if (item != null) {
4810                    final Element vcard4 = item.findChild("vcard", Namespace.VCARD4);
4811                    if (vcard4 != null) {
4812                        if (callback != null) {
4813                            callback.accept(vcard4);
4814                        }
4815                        return;
4816                    }
4817                }
4818            } else {
4819                Element error = result.findChild("error");
4820                if (error == null) {
4821                    Log.d(Config.LOGTAG, "fetchVcard4 (server error)");
4822                } else {
4823                    Log.d(Config.LOGTAG, "fetchVcard4 " + error.toString());
4824                }
4825            }
4826            if (callback != null) {
4827                callback.accept(null);
4828            }
4829
4830        });
4831    }
4832
4833    public void deleteContactOnServer(Contact contact) {
4834        contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
4835        contact.resetOption(Contact.Options.DIRTY_PUSH);
4836        contact.setOption(Contact.Options.DIRTY_DELETE);
4837        Account account = contact.getAccount();
4838        if (account.getStatus() == Account.State.ONLINE) {
4839            IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
4840            Element item = iq.query(Namespace.ROSTER).addChild("item");
4841            item.setAttribute("jid", contact.getJid());
4842            item.setAttribute("subscription", "remove");
4843            account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
4844        }
4845    }
4846
4847    public void updateConversation(final Conversation conversation) {
4848        mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
4849    }
4850
4851    private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
4852        synchronized (account) {
4853            final XmppConnection existingConnection = account.getXmppConnection();
4854            final XmppConnection connection;
4855            if (existingConnection != null) {
4856                connection = existingConnection;
4857            } else if (account.isConnectionEnabled()) {
4858                connection = createConnection(account);
4859                account.setXmppConnection(connection);
4860            } else {
4861                return;
4862            }
4863            final boolean hasInternet = hasInternetConnection();
4864            if (account.isConnectionEnabled() && hasInternet) {
4865                if (!force) {
4866                    disconnect(account, false);
4867                }
4868                Thread thread = new Thread(connection);
4869                connection.setInteractive(interactive);
4870                connection.prepareNewConnection();
4871                connection.interrupt();
4872                thread.start();
4873                scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
4874            } else {
4875                disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
4876                account.getRoster().clearPresences();
4877                connection.resetEverything();
4878                final AxolotlService axolotlService = account.getAxolotlService();
4879                if (axolotlService != null) {
4880                    axolotlService.resetBrokenness();
4881                }
4882                if (!hasInternet) {
4883                    account.setStatus(Account.State.NO_INTERNET);
4884                }
4885            }
4886        }
4887    }
4888
4889    public void reconnectAccountInBackground(final Account account) {
4890        new Thread(() -> reconnectAccount(account, false, true)).start();
4891    }
4892
4893    public void invite(final Conversation conversation, final Jid contact) {
4894        Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
4895        final MucOptions.User user = conversation.getMucOptions().findUserByRealJid(contact.asBareJid());
4896        if (user == null || user.getAffiliation() == MucOptions.Affiliation.OUTCAST) {
4897            changeAffiliationInConference(conversation, contact, MucOptions.Affiliation.NONE, null);
4898        }
4899        final MessagePacket packet = mMessageGenerator.invite(conversation, contact);
4900        sendMessagePacket(conversation.getAccount(), packet);
4901    }
4902
4903    public void directInvite(Conversation conversation, Jid jid) {
4904        MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
4905        sendMessagePacket(conversation.getAccount(), packet);
4906    }
4907
4908    public void resetSendingToWaiting(Account account) {
4909        for (Conversation conversation : getConversations()) {
4910            if (conversation.getAccount() == account) {
4911                conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
4912            }
4913        }
4914    }
4915
4916    public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
4917        return markMessage(account, recipient, uuid, status, null);
4918    }
4919
4920    public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
4921        if (uuid == null) {
4922            return null;
4923        }
4924        for (Conversation conversation : getConversations()) {
4925            if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
4926                final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
4927                if (message != null) {
4928                    markMessage(message, status, errorMessage);
4929                }
4930                return message;
4931            }
4932        }
4933        return null;
4934    }
4935
4936    public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId) {
4937        return markMessage(conversation, uuid, status, serverMessageId, null, null);
4938    }
4939
4940    public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId, final LocalizedContent body, final Element html) {
4941        if (uuid == null) {
4942            return false;
4943        } else {
4944            final Message message = conversation.findSentMessageWithUuid(uuid);
4945            if (message != null) {
4946                if (message.getServerMsgId() == null) {
4947                    message.setServerMsgId(serverMessageId);
4948                }
4949                if (message.getEncryption() == Message.ENCRYPTION_NONE
4950                        && message.isTypeText()
4951                        && isBodyModified(message, body)) {
4952                    message.setBody(body.content);
4953                    message.setHtml(html);
4954                    if (body.count > 1) {
4955                        message.setBodyLanguage(body.language);
4956                    }
4957                    markMessage(message, status, null, true);
4958                } else {
4959                    markMessage(message, status);
4960                }
4961                return true;
4962            } else {
4963                return false;
4964            }
4965        }
4966    }
4967
4968    private static boolean isBodyModified(final Message message, final LocalizedContent body) {
4969        if (body == null || body.content == null) {
4970            return false;
4971        }
4972        return !body.content.equals(message.getBody());
4973    }
4974
4975    public void markMessage(Message message, int status) {
4976        markMessage(message, status, null);
4977    }
4978
4979
4980    public void markMessage(final Message message, final int status, final String errorMessage) {
4981        markMessage(message, status, errorMessage, false);
4982    }
4983
4984    public void markMessage(final Message message, final int status, final String errorMessage, final boolean includeBody) {
4985        final int oldStatus = message.getStatus();
4986        if (status == Message.STATUS_SEND_FAILED && (oldStatus == Message.STATUS_SEND_RECEIVED || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
4987            return;
4988        }
4989        if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
4990            return;
4991        }
4992        message.setErrorMessage(errorMessage);
4993        message.setStatus(status);
4994        databaseBackend.updateMessage(message, includeBody);
4995        updateConversationUi();
4996        if (oldStatus != status && status == Message.STATUS_SEND_FAILED) {
4997            mNotificationService.pushFailedDelivery(message);
4998        }
4999    }
5000
5001    public SharedPreferences getPreferences() {
5002        return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
5003    }
5004
5005    public long getAutomaticMessageDeletionDate() {
5006        final long timeout = getLongPreference(AppSettings.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
5007        return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
5008    }
5009
5010    public long getLongPreference(String name, @IntegerRes int res) {
5011        long defaultValue = getResources().getInteger(res);
5012        try {
5013            return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
5014        } catch (NumberFormatException e) {
5015            return defaultValue;
5016        }
5017    }
5018
5019    public boolean getBooleanPreference(String name, @BoolRes int res) {
5020        return getPreferences().getBoolean(name, getResources().getBoolean(res));
5021    }
5022
5023    public boolean confirmMessages() {
5024        return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
5025    }
5026
5027    public boolean allowMessageCorrection() {
5028        return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
5029    }
5030
5031    public boolean sendChatStates() {
5032        return getBooleanPreference("chat_states", R.bool.chat_states);
5033    }
5034
5035    public boolean useTorToConnect() {
5036        return getBooleanPreference("use_tor", R.bool.use_tor);
5037    }
5038
5039    public boolean showExtendedConnectionOptions() {
5040        return getBooleanPreference("show_connection_options", R.bool.show_connection_options);
5041    }
5042
5043    public boolean broadcastLastActivity() {
5044        return getBooleanPreference(AppSettings.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
5045    }
5046
5047    public int unreadCount() {
5048        int count = 0;
5049        for (Conversation conversation : getConversations()) {
5050            count += conversation.unreadCount();
5051        }
5052        return count;
5053    }
5054
5055
5056    private <T> List<T> threadSafeList(Set<T> set) {
5057        synchronized (LISTENER_LOCK) {
5058            return set.isEmpty() ? Collections.emptyList() : new ArrayList<>(set);
5059        }
5060    }
5061
5062    public void showErrorToastInUi(int resId) {
5063        for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
5064            listener.onShowErrorToast(resId);
5065        }
5066    }
5067
5068    public void updateConversationUi() {
5069        updateConversationUi(false);
5070    }
5071
5072    public void updateConversationUi(boolean newCaps) {
5073        for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
5074            listener.onConversationUpdate(newCaps);
5075        }
5076    }
5077
5078    public void notifyJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state) {
5079        for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
5080            listener.onJingleRtpConnectionUpdate(account, with, sessionId, state);
5081        }
5082    }
5083
5084    public void notifyJingleRtpConnectionUpdate(CallIntegration.AudioDevice selectedAudioDevice, Set<CallIntegration.AudioDevice> availableAudioDevices) {
5085        for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
5086            listener.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
5087        }
5088    }
5089
5090    public void updateAccountUi() {
5091        for (final OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
5092            listener.onAccountUpdate();
5093        }
5094    }
5095
5096    public void updateRosterUi() {
5097        for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
5098            listener.onRosterUpdate();
5099        }
5100    }
5101
5102    public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
5103        if (mOnCaptchaRequested.size() > 0) {
5104            DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
5105            Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
5106                    (int) (captcha.getHeight() * metrics.scaledDensity), false);
5107            for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
5108                listener.onCaptchaRequested(account, id, data, scaled);
5109            }
5110            return true;
5111        }
5112        return false;
5113    }
5114
5115    public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
5116        for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
5117            listener.OnUpdateBlocklist(status);
5118        }
5119    }
5120
5121    public void updateMucRosterUi() {
5122        for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
5123            listener.onMucRosterUpdate();
5124        }
5125    }
5126
5127    public void keyStatusUpdated(AxolotlService.FetchStatus report) {
5128        for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
5129            listener.onKeyStatusUpdated(report);
5130        }
5131    }
5132
5133    public Account findAccountByJid(final Jid jid) {
5134        for (final Account account : this.accounts) {
5135            if (account.getJid().asBareJid().equals(jid.asBareJid())) {
5136                return account;
5137            }
5138        }
5139        return null;
5140    }
5141
5142    public Account findAccountByUuid(final String uuid) {
5143        for (Account account : this.accounts) {
5144            if (account.getUuid().equals(uuid)) {
5145                return account;
5146            }
5147        }
5148        return null;
5149    }
5150
5151    public Conversation findConversationByUuid(String uuid) {
5152        for (Conversation conversation : getConversations()) {
5153            if (conversation.getUuid().equals(uuid)) {
5154                return conversation;
5155            }
5156        }
5157        return null;
5158    }
5159
5160    public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
5161        List<Conversation> findings = new ArrayList<>();
5162        for (Conversation c : getConversations()) {
5163            if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid().asBareJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
5164                findings.add(c);
5165            }
5166        }
5167        return findings.size() == 1 ? findings.get(0) : null;
5168    }
5169
5170    public boolean markRead(final Conversation conversation, boolean dismiss) {
5171        return markRead(conversation, null, dismiss).size() > 0;
5172    }
5173
5174    public void markRead(final Conversation conversation) {
5175        markRead(conversation, null, true);
5176    }
5177
5178    public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
5179        if (dismiss) {
5180            mNotificationService.clear(conversation);
5181        }
5182        final List<Message> readMessages = conversation.markRead(upToUuid);
5183        if (readMessages.size() > 0) {
5184            Runnable runnable = () -> {
5185                for (Message message : readMessages) {
5186                    databaseBackend.updateMessage(message, false);
5187                }
5188            };
5189            mDatabaseWriterExecutor.execute(runnable);
5190            updateConversationUi();
5191            updateUnreadCountBadge();
5192            return readMessages;
5193        } else {
5194            return readMessages;
5195        }
5196    }
5197
5198    public synchronized void updateUnreadCountBadge() {
5199        int count = unreadCount();
5200        if (unreadCount != count) {
5201            Log.d(Config.LOGTAG, "update unread count to " + count);
5202            if (count > 0) {
5203                ShortcutBadger.applyCount(getApplicationContext(), count);
5204            } else {
5205                ShortcutBadger.removeCount(getApplicationContext());
5206            }
5207            unreadCount = count;
5208        }
5209    }
5210
5211    public void sendReadMarker(final Conversation conversation, final String upToUuid) {
5212        final boolean isPrivateAndNonAnonymousMuc =
5213                conversation.getMode() == Conversation.MODE_MULTI
5214                        && conversation.isPrivateAndNonAnonymous();
5215        final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
5216        if (readMessages.isEmpty()) {
5217            return;
5218        }
5219        final var account = conversation.getAccount();
5220        final var connection = account.getXmppConnection();
5221        updateConversationUi();
5222        final var last =
5223                Iterables.getLast(
5224                        Collections2.filter(
5225                                readMessages,
5226                                m ->
5227                                        !m.isPrivateMessage()
5228                                                && m.getStatus() == Message.STATUS_RECEIVED),
5229                        null);
5230        if (last == null) {
5231            return;
5232        }
5233
5234        final boolean sendDisplayedMarker =
5235                confirmMessages()
5236                        && (last.trusted() || isPrivateAndNonAnonymousMuc)
5237                        && last.getRemoteMsgId() != null
5238                        && (last.markable || isPrivateAndNonAnonymousMuc);
5239        final boolean serverAssist =
5240                connection != null && connection.getFeatures().mdsServerAssist();
5241
5242        final String stanzaId = last.getServerMsgId();
5243
5244        if (sendDisplayedMarker && serverAssist) {
5245            final var mdsDisplayed = mIqGenerator.mdsDisplayed(stanzaId, conversation);
5246            final MessagePacket packet = mMessageGenerator.confirm(last);
5247            packet.addChild(mdsDisplayed);
5248            if (!last.isPrivateMessage()) {
5249                packet.setTo(packet.getTo().asBareJid());
5250            }
5251            Log.d(Config.LOGTAG,account.getJid().asBareJid()+": server assisted "+packet);
5252            this.sendMessagePacket(account, packet);
5253        } else {
5254            publishMds(last);
5255            // read markers will be sent after MDS to flush the CSI stanza queue
5256            if (sendDisplayedMarker) {
5257                Log.d(
5258                        Config.LOGTAG,
5259                        conversation.getAccount().getJid().asBareJid()
5260                                + ": sending displayed marker to "
5261                                + last.getCounterpart().toString());
5262                final MessagePacket packet = mMessageGenerator.confirm(last);
5263                this.sendMessagePacket(account, packet);
5264            }
5265        }
5266    }
5267
5268    private void publishMds(@Nullable final Message message) {
5269        final String stanzaId = message == null ? null : message.getServerMsgId();
5270        if (Strings.isNullOrEmpty(stanzaId)) {
5271            return;
5272        }
5273        final Conversation conversation;
5274        final var conversational = message.getConversation();
5275        if (conversational instanceof Conversation c) {
5276            conversation = c;
5277        } else {
5278            return;
5279        }
5280        final var account = conversation.getAccount();
5281        final var connection = account.getXmppConnection();
5282        if (connection == null || !connection.getFeatures().mds()) {
5283            return;
5284        }
5285        final Jid itemId;
5286        if (message.isPrivateMessage()) {
5287            itemId = message.getCounterpart();
5288        } else {
5289            itemId = conversation.getJid().asBareJid();
5290        }
5291        Log.d(Config.LOGTAG,"publishing mds for "+itemId+"/"+stanzaId);
5292        publishMds(account, itemId, stanzaId, conversation);
5293    }
5294
5295    private void publishMds(
5296            final Account account, final Jid itemId, final String stanzaId, final Conversation conversation) {
5297        final var item = mIqGenerator.mdsDisplayed(stanzaId, conversation);
5298        pushNodeAndEnforcePublishOptions(
5299                account,
5300                Namespace.MDS_DISPLAYED,
5301                item,
5302                itemId.toEscapedString(),
5303                PublishOptions.persistentWhitelistAccessMaxItems());
5304    }
5305
5306    public MemorizingTrustManager getMemorizingTrustManager() {
5307        return this.mMemorizingTrustManager;
5308    }
5309
5310    public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
5311        this.mMemorizingTrustManager = trustManager;
5312    }
5313
5314    public void updateMemorizingTrustManager() {
5315        final MemorizingTrustManager trustManager;
5316        final var appSettings = new AppSettings(this);
5317        if (appSettings.isTrustSystemCAStore()) {
5318            trustManager = new MemorizingTrustManager(getApplicationContext());
5319        } else {
5320            trustManager = new MemorizingTrustManager(getApplicationContext(), null);
5321        }
5322        setMemorizingTrustManager(trustManager);
5323    }
5324
5325    public LruCache<String, Drawable> getDrawableCache() {
5326        return this.mDrawableCache;
5327    }
5328
5329    public Collection<String> getKnownHosts() {
5330        final Set<String> hosts = new HashSet<>();
5331        for (final Account account : getAccounts()) {
5332            hosts.add(account.getServer());
5333            for (final Contact contact : account.getRoster().getContacts()) {
5334                if (contact.showInRoster()) {
5335                    final String server = contact.getServer();
5336                    if (server != null) {
5337                        hosts.add(server);
5338                    }
5339                }
5340            }
5341        }
5342        if (Config.QUICKSY_DOMAIN != null) {
5343            hosts.remove(Config.QUICKSY_DOMAIN.toEscapedString()); //we only want to show this when we type a e164 number
5344        }
5345        if (Config.MAGIC_CREATE_DOMAIN != null) {
5346            hosts.add(Config.MAGIC_CREATE_DOMAIN);
5347        }
5348        hosts.add("chat.above.im");
5349        return hosts;
5350    }
5351
5352    public Collection<String> getKnownConferenceHosts() {
5353        final Set<String> mucServers = new HashSet<>();
5354        for (final Account account : accounts) {
5355            if (account.getXmppConnection() != null) {
5356                mucServers.addAll(account.getXmppConnection().getMucServers());
5357                for (final Bookmark bookmark : account.getBookmarks()) {
5358                    final Jid jid = bookmark.getJid();
5359                    final String s = jid == null ? null : jid.getDomain().toEscapedString();
5360                    if (s != null) {
5361                        mucServers.add(s);
5362                    }
5363                }
5364            }
5365        }
5366        return mucServers;
5367    }
5368
5369    public void sendMessagePacket(Account account, MessagePacket packet) {
5370        final XmppConnection connection = account.getXmppConnection();
5371        if (connection != null) {
5372            connection.sendMessagePacket(packet);
5373        }
5374    }
5375
5376    public void sendPresencePacket(Account account, PresencePacket packet) {
5377        XmppConnection connection = account.getXmppConnection();
5378        if (connection != null) {
5379            connection.sendPresencePacket(packet);
5380        }
5381    }
5382
5383    public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
5384        final XmppConnection connection = account.getXmppConnection();
5385        if (connection != null) {
5386            IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
5387            connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
5388        }
5389    }
5390
5391    public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
5392        sendIqPacket(account, packet, callback, null);
5393    }
5394
5395    public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback, Long timeout) {
5396        final XmppConnection connection = account.getXmppConnection();
5397        if (connection != null) {
5398            connection.sendIqPacket(packet, callback, timeout);
5399        } else if (callback != null) {
5400            callback.onIqPacketReceived(account, new IqPacket(IqPacket.TYPE.TIMEOUT));
5401        }
5402    }
5403
5404    public void sendPresence(final Account account) {
5405        sendPresence(account, checkListeners() && broadcastLastActivity());
5406    }
5407
5408    private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
5409        final Presence.Status status;
5410        if (manuallyChangePresence()) {
5411            status = account.getPresenceStatus();
5412        } else {
5413            status = getTargetPresence();
5414        }
5415        final PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
5416        if (mLastActivity > 0 && includeIdleTimestamp) {
5417            long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
5418            packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
5419        }
5420        sendPresencePacket(account, packet);
5421    }
5422
5423    private void deactivateGracePeriod() {
5424        for (Account account : getAccounts()) {
5425            account.deactivateGracePeriod();
5426        }
5427    }
5428
5429    public void refreshAllPresences() {
5430        boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
5431        for (Account account : getAccounts()) {
5432            if (account.isConnectionEnabled()) {
5433                sendPresence(account, includeIdleTimestamp);
5434            }
5435        }
5436    }
5437
5438    private void refreshAllFcmTokens() {
5439        for (Account account : getAccounts()) {
5440            if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
5441                mPushManagementService.registerPushTokenOnServer(account);
5442            }
5443        }
5444    }
5445
5446
5447
5448    private void sendOfflinePresence(final Account account) {
5449        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
5450        sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
5451    }
5452
5453    public MessageGenerator getMessageGenerator() {
5454        return this.mMessageGenerator;
5455    }
5456
5457    public PresenceGenerator getPresenceGenerator() {
5458        return this.mPresenceGenerator;
5459    }
5460
5461    public IqGenerator getIqGenerator() {
5462        return this.mIqGenerator;
5463    }
5464
5465    public IqParser getIqParser() {
5466        return this.mIqParser;
5467    }
5468
5469    public JingleConnectionManager getJingleConnectionManager() {
5470        return this.mJingleConnectionManager;
5471    }
5472
5473    private boolean hasJingleRtpConnection(final Account account) {
5474        return this.mJingleConnectionManager.hasJingleRtpConnection(account);
5475    }
5476
5477    public MessageArchiveService getMessageArchiveService() {
5478        return this.mMessageArchiveService;
5479    }
5480
5481    public QuickConversationsService getQuickConversationsService() {
5482        return this.mQuickConversationsService;
5483    }
5484
5485    public List<Contact> findContacts(Jid jid, String accountJid) {
5486        ArrayList<Contact> contacts = new ArrayList<>();
5487        for (Account account : getAccounts()) {
5488            if ((account.isEnabled() || accountJid != null)
5489                    && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
5490                Contact contact = account.getRoster().getContactFromContactList(jid);
5491                if (contact != null) {
5492                    contacts.add(contact);
5493                }
5494            }
5495        }
5496        return contacts;
5497    }
5498
5499    public Conversation findFirstMuc(Jid jid) {
5500        return findFirstMuc(jid, null);
5501    }
5502
5503    public Conversation findFirstMuc(Jid jid, String accountJid) {
5504        for (Conversation conversation : getConversations()) {
5505            if ((conversation.getAccount().isEnabled() || accountJid != null)
5506                    && (accountJid == null || accountJid.equals(conversation.getAccount().getJid().asBareJid().toString()))
5507                    && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
5508                return conversation;
5509            }
5510        }
5511        return null;
5512    }
5513
5514    public NotificationService getNotificationService() {
5515        return this.mNotificationService;
5516    }
5517
5518    public HttpConnectionManager getHttpConnectionManager() {
5519        return this.mHttpConnectionManager;
5520    }
5521
5522    public void resendFailedMessages(final Message message) {
5523        final Collection<Message> messages = new ArrayList<>();
5524        Message current = message;
5525        while (current.getStatus() == Message.STATUS_SEND_FAILED) {
5526            messages.add(current);
5527            if (current.mergeable(current.next())) {
5528                current = current.next();
5529            } else {
5530                break;
5531            }
5532        }
5533        for (final Message msg : messages) {
5534            msg.setTime(System.currentTimeMillis());
5535            markMessage(msg, Message.STATUS_WAITING);
5536            this.resendMessage(msg, false);
5537        }
5538        if (message.getConversation() instanceof Conversation) {
5539            ((Conversation) message.getConversation()).sort();
5540        }
5541        updateConversationUi();
5542    }
5543
5544    public void clearConversationHistory(final Conversation conversation) {
5545        final long clearDate;
5546        final String reference;
5547        if (conversation.countMessages() > 0) {
5548            Message latestMessage = conversation.getLatestMessage();
5549            clearDate = latestMessage.getTimeSent() + 1000;
5550            reference = latestMessage.getServerMsgId();
5551        } else {
5552            clearDate = System.currentTimeMillis();
5553            reference = null;
5554        }
5555        conversation.clearMessages();
5556        conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
5557        conversation.setLastClearHistory(clearDate, reference);
5558        Runnable runnable = () -> {
5559            databaseBackend.deleteMessagesInConversation(conversation);
5560            databaseBackend.updateConversation(conversation);
5561        };
5562        mDatabaseWriterExecutor.execute(runnable);
5563    }
5564
5565    public boolean sendBlockRequest(final Blockable blockable, final boolean reportSpam, final String serverMsgId) {
5566        if (blockable != null && blockable.getBlockedJid() != null) {
5567            final Jid jid = blockable.getBlockedJid();
5568            this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam, serverMsgId), (a, response) -> {
5569                if (response.getType() == IqPacket.TYPE.RESULT) {
5570                    a.getBlocklist().add(jid);
5571                    updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
5572                }
5573            });
5574            if (blockable.getBlockedJid().isFullJid()) {
5575                return false;
5576            } else if (removeBlockedConversations(blockable.getAccount(), jid)) {
5577                updateConversationUi();
5578                return true;
5579            } else {
5580                return false;
5581            }
5582        } else {
5583            return false;
5584        }
5585    }
5586
5587    public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
5588        boolean removed = false;
5589        synchronized (this.conversations) {
5590            boolean domainJid = blockedJid.getLocal() == null;
5591            for (Conversation conversation : this.conversations) {
5592                boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
5593                        || blockedJid.equals(conversation.getJid().asBareJid());
5594                if (conversation.getAccount() == account
5595                        && conversation.getMode() == Conversation.MODE_SINGLE
5596                        && jidMatches) {
5597                    this.conversations.remove(conversation);
5598                    markRead(conversation);
5599                    conversation.setStatus(Conversation.STATUS_ARCHIVED);
5600                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
5601                    updateConversation(conversation);
5602                    removed = true;
5603                }
5604            }
5605        }
5606        return removed;
5607    }
5608
5609    public void sendUnblockRequest(final Blockable blockable) {
5610        if (blockable != null && blockable.getJid() != null) {
5611            final Jid jid = blockable.getBlockedJid();
5612            this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
5613                @Override
5614                public void onIqPacketReceived(final Account account, final IqPacket packet) {
5615                    if (packet.getType() == IqPacket.TYPE.RESULT) {
5616                        account.getBlocklist().remove(jid);
5617                        updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
5618                    }
5619                }
5620            });
5621        }
5622    }
5623
5624    public void publishDisplayName(Account account) {
5625        String displayName = account.getDisplayName();
5626        final IqPacket request;
5627        if (TextUtils.isEmpty(displayName)) {
5628            request = mIqGenerator.deleteNode(Namespace.NICK);
5629        } else {
5630            request = mIqGenerator.publishNick(displayName);
5631        }
5632        mAvatarService.clear(account);
5633        sendIqPacket(account, request, (account1, packet) -> {
5634            if (packet.getType() == IqPacket.TYPE.ERROR) {
5635                Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": unable to modify nick name " + packet);
5636            }
5637        });
5638    }
5639
5640    public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
5641        ServiceDiscoveryResult result = discoCache.get(key);
5642        if (result != null) {
5643            return result;
5644        } else {
5645            if (key.first == null || key.second == null) return null;
5646            result = databaseBackend.findDiscoveryResult(key.first, key.second);
5647            if (result != null) {
5648                discoCache.put(key, result);
5649            }
5650            return result;
5651        }
5652    }
5653
5654    public void fetchFromGateway(Account account, final Jid jid, final String input, final OnGatewayResult callback) {
5655        IqPacket request = new IqPacket(input == null ? IqPacket.TYPE.GET : IqPacket.TYPE.SET);
5656        request.setTo(jid);
5657        Element query = request.query("jabber:iq:gateway");
5658        if (input != null) {
5659            Element prompt = query.addChild("prompt");
5660            prompt.setContent(input);
5661        }
5662        sendIqPacket(account, request, (Account acct, IqPacket packet) -> {
5663            if (packet.getType() == IqPacket.TYPE.RESULT) {
5664                callback.onGatewayResult(packet.query().findChildContent(input == null ? "prompt" : "jid"), null);
5665            } else {
5666                Element error = packet.findChild("error");
5667                callback.onGatewayResult(null, error == null ? null : error.findChildContent("text"));
5668            }
5669        });
5670    }
5671
5672    public void fetchCaps(Account account, final Jid jid, final Presence presence) {
5673        fetchCaps(account, jid, presence, null);
5674    }
5675
5676    public void fetchCaps(Account account, final Jid jid, final Presence presence, Runnable cb) {
5677        final Pair<String, String> key = presence == null ? null : new Pair<>(presence.getHash(), presence.getVer());
5678        final ServiceDiscoveryResult disco = key == null ? null : getCachedServiceDiscoveryResult(key);
5679
5680        if (disco != null) {
5681            presence.setServiceDiscoveryResult(disco);
5682            final Contact contact = account.getRoster().getContact(jid);
5683            if (contact.refreshRtpCapability()) {
5684                syncRoster(account);
5685            }
5686            if (disco.hasIdentity("gateway", "pstn")) {
5687                contact.registerAsPhoneAccount(this);
5688                mQuickConversationsService.considerSyncBackground(false);
5689            }
5690            updateConversationUi(true);
5691        } else {
5692            final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
5693            request.setTo(jid);
5694            final String node = presence == null ? null : presence.getNode();
5695            final String ver = presence == null ? null : presence.getVer();
5696            final Element query = request.query(Namespace.DISCO_INFO);
5697            if (node != null && ver != null) {
5698                query.setAttribute("node", node + "#" + ver);
5699            }
5700            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + (key == null ? "" : key.second) + " to " + jid);
5701            sendIqPacket(account, request, (a, response) -> {
5702                if (response.getType() == IqPacket.TYPE.RESULT) {
5703                    final ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
5704                    if (presence == null || presence.getVer() == null || presence.getVer().equals(discoveryResult.getVer())) {
5705                        databaseBackend.insertDiscoveryResult(discoveryResult);
5706                        injectServiceDiscoveryResult(a.getRoster(), presence == null ? null : presence.getHash(), presence == null ? null : presence.getVer(), jid.getResource(), discoveryResult);
5707                        if (discoveryResult.hasIdentity("gateway", "pstn")) {
5708                            final Contact contact = account.getRoster().getContact(jid);
5709                            contact.registerAsPhoneAccount(this);
5710                            mQuickConversationsService.considerSyncBackground(false);
5711                        }
5712                        updateConversationUi(true);
5713                        if (cb != null) cb.run();
5714                    } else {
5715                        Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
5716                    }
5717                } else {
5718                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to fetch caps from " + jid);
5719                }
5720            });
5721        }
5722    }
5723
5724    public void fetchCommands(Account account, final Jid jid, OnIqPacketReceived callback) {
5725        final IqPacket request = mIqGenerator.queryDiscoItems(jid, "http://jabber.org/protocol/commands");
5726        sendIqPacket(account, request, callback);
5727    }
5728
5729    private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, String resource, ServiceDiscoveryResult disco) {
5730        boolean rosterNeedsSync = false;
5731        for (final Contact contact : roster.getContacts()) {
5732            boolean serviceDiscoverySet = false;
5733            Presence onePresence = contact.getPresences().get(resource == null ? "" : resource);
5734            if (onePresence != null) {
5735                onePresence.setServiceDiscoveryResult(disco);
5736                serviceDiscoverySet = true;
5737            } else if (resource == null && hash == null && ver == null) {
5738                Presence p = new Presence(Presence.Status.OFFLINE, null, null, null, "");
5739                p.setServiceDiscoveryResult(disco);
5740                contact.updatePresence("", p);
5741                serviceDiscoverySet = true;
5742            }
5743            if (hash != null && ver != null) {
5744                for (final Presence presence : contact.getPresences().getPresences()) {
5745                    if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
5746                        presence.setServiceDiscoveryResult(disco);
5747                        serviceDiscoverySet = true;
5748                    }
5749                }
5750            }
5751            if (serviceDiscoverySet) {
5752                rosterNeedsSync |= contact.refreshRtpCapability();
5753            }
5754        }
5755        if (rosterNeedsSync) {
5756            syncRoster(roster.getAccount());
5757        }
5758    }
5759
5760    public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
5761        final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
5762        IqPacket request = new IqPacket(IqPacket.TYPE.GET);
5763        request.addChild("prefs", version.namespace);
5764        sendIqPacket(account, request, (account1, packet) -> {
5765            Element prefs = packet.findChild("prefs", version.namespace);
5766            if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
5767                callback.onPreferencesFetched(prefs);
5768            } else {
5769                callback.onPreferencesFetchFailed();
5770            }
5771        });
5772    }
5773
5774    public PushManagementService getPushManagementService() {
5775        return mPushManagementService;
5776    }
5777
5778    public void changeStatus(Account account, PresenceTemplate template, String signature) {
5779        if (!template.getStatusMessage().isEmpty()) {
5780            databaseBackend.insertPresenceTemplate(template);
5781        }
5782        account.setPgpSignature(signature);
5783        account.setPresenceStatus(template.getStatus());
5784        account.setPresenceStatusMessage(template.getStatusMessage());
5785        databaseBackend.updateAccount(account);
5786        sendPresence(account);
5787    }
5788
5789    public List<PresenceTemplate> getPresenceTemplates(Account account) {
5790        List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
5791        for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
5792            if (!templates.contains(template)) {
5793                templates.add(0, template);
5794            }
5795        }
5796        return templates;
5797    }
5798
5799    public void saveConversationAsBookmark(final Conversation conversation, final String name) {
5800        final Account account = conversation.getAccount();
5801        final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
5802        String nick = conversation.getMucOptions().getActualNick();
5803        if (nick == null) nick = conversation.getJid().getResource();
5804        if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
5805            bookmark.setNick(nick);
5806        }
5807        if (!TextUtils.isEmpty(name)) {
5808            bookmark.setBookmarkName(name);
5809        }
5810        bookmark.setAutojoin(true);
5811        createBookmark(account, bookmark);
5812        bookmark.setConversation(conversation);
5813    }
5814
5815    public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
5816        boolean performedVerification = false;
5817        final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
5818        for (XmppUri.Fingerprint fp : fingerprints) {
5819            if (fp.type == XmppUri.FingerprintType.OMEMO) {
5820                String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
5821                FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
5822                if (fingerprintStatus != null) {
5823                    if (!fingerprintStatus.isVerified()) {
5824                        performedVerification = true;
5825                        axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
5826                    }
5827                } else {
5828                    axolotlService.preVerifyFingerprint(contact, fingerprint);
5829                }
5830            }
5831        }
5832        return performedVerification;
5833    }
5834
5835    public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
5836        final AxolotlService axolotlService = account.getAxolotlService();
5837        boolean verifiedSomething = false;
5838        for (XmppUri.Fingerprint fp : fingerprints) {
5839            if (fp.type == XmppUri.FingerprintType.OMEMO) {
5840                String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
5841                Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
5842                FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
5843                if (fingerprintStatus != null) {
5844                    if (!fingerprintStatus.isVerified()) {
5845                        axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
5846                        verifiedSomething = true;
5847                    }
5848                } else {
5849                    axolotlService.preVerifyFingerprint(account, fingerprint);
5850                    verifiedSomething = true;
5851                }
5852            }
5853        }
5854        return verifiedSomething;
5855    }
5856
5857    public boolean blindTrustBeforeVerification() {
5858        return getBooleanPreference(AppSettings.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
5859    }
5860
5861    public ShortcutService getShortcutService() {
5862        return mShortcutService;
5863    }
5864
5865    public void pushMamPreferences(Account account, Element prefs) {
5866        IqPacket set = new IqPacket(IqPacket.TYPE.SET);
5867        set.addChild(prefs);
5868        sendIqPacket(account, set, null);
5869    }
5870
5871    public void evictPreview(File f) {
5872        if (f == null) return;
5873
5874        if (mDrawableCache.remove(f.getAbsolutePath()) != null) {
5875            Log.d(Config.LOGTAG, "deleted cached preview");
5876        }
5877    }
5878
5879    public void evictPreview(String uuid) {
5880        if (mDrawableCache.remove(uuid) != null) {
5881            Log.d(Config.LOGTAG, "deleted cached preview");
5882        }
5883    }
5884
5885    public interface OnMamPreferencesFetched {
5886        void onPreferencesFetched(Element prefs);
5887
5888        void onPreferencesFetchFailed();
5889    }
5890
5891    public interface OnAccountCreated {
5892        void onAccountCreated(Account account);
5893
5894        void informUser(int r);
5895    }
5896
5897    public interface OnMoreMessagesLoaded {
5898        void onMoreMessagesLoaded(int count, Conversation conversation);
5899
5900        void informUser(int r);
5901    }
5902
5903    public interface OnAccountPasswordChanged {
5904        void onPasswordChangeSucceeded();
5905
5906        void onPasswordChangeFailed();
5907    }
5908
5909    public interface OnRoomDestroy {
5910        void onRoomDestroySucceeded();
5911
5912        void onRoomDestroyFailed();
5913    }
5914
5915    public interface OnAffiliationChanged {
5916        void onAffiliationChangedSuccessful(Jid jid);
5917
5918        void onAffiliationChangeFailed(Jid jid, int resId);
5919    }
5920
5921    public interface OnConversationUpdate {
5922        default void onConversationUpdate() { onConversationUpdate(false); }
5923        default void onConversationUpdate(boolean newCaps) { onConversationUpdate(); }
5924    }
5925
5926    public interface OnJingleRtpConnectionUpdate {
5927        void onJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state);
5928
5929        void onAudioDeviceChanged(CallIntegration.AudioDevice selectedAudioDevice, Set<CallIntegration.AudioDevice> availableAudioDevices);
5930    }
5931
5932    public interface OnAccountUpdate {
5933        void onAccountUpdate();
5934    }
5935
5936    public interface OnCaptchaRequested {
5937        void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
5938    }
5939
5940    public interface OnRosterUpdate {
5941        void onRosterUpdate();
5942    }
5943
5944    public interface OnMucRosterUpdate {
5945        void onMucRosterUpdate();
5946    }
5947
5948    public interface OnConferenceConfigurationFetched {
5949        void onConferenceConfigurationFetched(Conversation conversation);
5950
5951        void onFetchFailed(Conversation conversation, String errorCondition);
5952    }
5953
5954    public interface OnConferenceJoined {
5955        void onConferenceJoined(Conversation conversation);
5956    }
5957
5958    public interface OnConfigurationPushed {
5959        void onPushSucceeded();
5960
5961        void onPushFailed();
5962    }
5963
5964    public interface OnShowErrorToast {
5965        void onShowErrorToast(int resId);
5966    }
5967
5968    public class XmppConnectionBinder extends Binder {
5969        public XmppConnectionService getService() {
5970            return XmppConnectionService.this;
5971        }
5972    }
5973
5974    private class InternalEventReceiver extends BroadcastReceiver {
5975
5976        @Override
5977        public void onReceive(final Context context, final Intent intent) {
5978            onStartCommand(intent, 0, 0);
5979        }
5980    }
5981
5982    private class RestrictedEventReceiver extends BroadcastReceiver {
5983
5984        private final Collection<String> allowedActions;
5985
5986        private RestrictedEventReceiver(final Collection<String> allowedActions) {
5987            this.allowedActions = allowedActions;
5988        }
5989
5990        @Override
5991        public void onReceive(final Context context, final Intent intent) {
5992            final String action = intent == null ? null : intent.getAction();
5993            if (allowedActions.contains(action)) {
5994                onStartCommand(intent,0,0);
5995            } else {
5996                Log.e(Config.LOGTAG,"restricting broadcast of event "+action);
5997            }
5998        }
5999    }
6000
6001    public static class OngoingCall {
6002        public final AbstractJingleConnection.Id id;
6003        public final Set<Media> media;
6004        public final boolean reconnecting;
6005
6006        public OngoingCall(AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
6007            this.id = id;
6008            this.media = media;
6009            this.reconnecting = reconnecting;
6010        }
6011
6012        @Override
6013        public boolean equals(Object o) {
6014            if (this == o) return true;
6015            if (o == null || getClass() != o.getClass()) return false;
6016            OngoingCall that = (OngoingCall) o;
6017            return reconnecting == that.reconnecting && Objects.equal(id, that.id) && Objects.equal(media, that.media);
6018        }
6019
6020        @Override
6021        public int hashCode() {
6022            return Objects.hashCode(id, media, reconnecting);
6023        }
6024    }
6025
6026    public static void toggleForegroundService(final XmppConnectionService service) {
6027        if (service == null) {
6028            return;
6029        }
6030        service.toggleForegroundService();
6031    }
6032
6033    public static void toggleForegroundService(final ConversationsActivity activity) {
6034        if (activity == null) {
6035            return;
6036        }
6037        toggleForegroundService(activity.xmppConnectionService);
6038    }
6039
6040    public static class BlockedMediaException extends Exception { }
6041}