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