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