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