XmppConnectionService.java

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