XmppConnectionService.java

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