XmppConnectionService.java

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