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