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