XmppConnectionService.java

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