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