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