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        if (!account.areBookmarksLoaded()) return;
1898
1899        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
1900        IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1901        Element query = iqPacket.query("jabber:iq:private");
1902        Element storage = query.addChild("storage", "storage:bookmarks");
1903        for (Bookmark bookmark : account.getBookmarks()) {
1904            storage.addChild(bookmark);
1905        }
1906        sendIqPacket(account, iqPacket, mDefaultIqHandler);
1907    }
1908
1909    private void pushBookmarksPep(Account account) {
1910        if (!account.areBookmarksLoaded()) return;
1911
1912        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
1913        Element storage = new Element("storage", "storage:bookmarks");
1914        for (Bookmark bookmark : account.getBookmarks()) {
1915            storage.addChild(bookmark);
1916        }
1917        pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS, storage, "current", PublishOptions.persistentWhitelistAccess());
1918
1919    }
1920
1921    private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options) {
1922        pushNodeAndEnforcePublishOptions(account, node, element, id, options, true);
1923
1924    }
1925
1926    private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options, final boolean retry) {
1927        final IqPacket packet = mIqGenerator.publishElement(node, element, id, options);
1928        sendIqPacket(account, packet, (a, response) -> {
1929            if (response.getType() == IqPacket.TYPE.RESULT) {
1930                return;
1931            }
1932            if (retry && PublishOptions.preconditionNotMet(response)) {
1933                pushNodeConfiguration(account, node, options, new OnConfigurationPushed() {
1934                    @Override
1935                    public void onPushSucceeded() {
1936                        pushNodeAndEnforcePublishOptions(account, node, element, id, options, false);
1937                    }
1938
1939                    @Override
1940                    public void onPushFailed() {
1941                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to push node configuration (" + node + ")");
1942                    }
1943                });
1944            } else {
1945                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error publishing bookmarks (retry=" + retry + ") " + response);
1946            }
1947        });
1948    }
1949
1950    private void restoreFromDatabase() {
1951        synchronized (this.conversations) {
1952            final Map<String, Account> accountLookupTable = new Hashtable<>();
1953            for (Account account : this.accounts) {
1954                accountLookupTable.put(account.getUuid(), account);
1955            }
1956            Log.d(Config.LOGTAG, "restoring conversations...");
1957            final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
1958            this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1959            for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
1960                Conversation conversation = iterator.next();
1961                Account account = accountLookupTable.get(conversation.getAccountUuid());
1962                if (account != null) {
1963                    conversation.setAccount(account);
1964                } else {
1965                    Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
1966                    iterator.remove();
1967                }
1968            }
1969            long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
1970            Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
1971            Runnable runnable = () -> {
1972                if (DatabaseBackend.requiresMessageIndexRebuild()) {
1973                    DatabaseBackend.getInstance(this).rebuildMessagesIndex();
1974                }
1975                final long deletionDate = getAutomaticMessageDeletionDate();
1976                mLastExpiryRun.set(SystemClock.elapsedRealtime());
1977                if (deletionDate > 0) {
1978                    Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
1979                    databaseBackend.expireOldMessages(deletionDate);
1980                }
1981                Log.d(Config.LOGTAG, "restoring roster...");
1982                for (Account account : accounts) {
1983                    databaseBackend.readRoster(account.getRoster());
1984                    account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1985                }
1986                getBitmapCache().evictAll();
1987                loadPhoneContacts();
1988                Log.d(Config.LOGTAG, "restoring messages...");
1989                final long startMessageRestore = SystemClock.elapsedRealtime();
1990                final Conversation quickLoad = QuickLoader.get(this.conversations);
1991                if (quickLoad != null) {
1992                    restoreMessages(quickLoad);
1993                    updateConversationUi();
1994                    final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1995                    Log.d(Config.LOGTAG, "quickly restored " + quickLoad.getName() + " after " + diffMessageRestore + "ms");
1996                }
1997                for (Conversation conversation : this.conversations) {
1998                    if (quickLoad != conversation) {
1999                        restoreMessages(conversation);
2000                    }
2001                }
2002                mNotificationService.finishBacklog(false);
2003                restoredFromDatabaseLatch.countDown();
2004                final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
2005                Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
2006                updateConversationUi();
2007            };
2008            mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
2009        }
2010    }
2011
2012    private void restoreMessages(Conversation conversation) {
2013        conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
2014        conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
2015        conversation.findUnreadMessagesAndCalls(mNotificationService::pushFromBacklog);
2016    }
2017
2018    public void loadPhoneContacts() {
2019        mContactMergerExecutor.execute(() -> {
2020            Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
2021            Log.d(Config.LOGTAG, "start merging phone contacts with roster");
2022            for (Account account : accounts) {
2023                List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts(JabberIdContact.class);
2024                for (JabberIdContact jidContact : contacts.values()) {
2025                    final Contact contact = account.getRoster().getContact(jidContact.getJid());
2026                    boolean needsCacheClean = contact.setPhoneContact(jidContact);
2027                    if (needsCacheClean) {
2028                        getAvatarService().clear(contact);
2029                    }
2030                    withSystemAccounts.remove(contact);
2031                }
2032                for (Contact contact : withSystemAccounts) {
2033                    boolean needsCacheClean = contact.unsetPhoneContact(JabberIdContact.class);
2034                    if (needsCacheClean) {
2035                        getAvatarService().clear(contact);
2036                    }
2037                }
2038            }
2039            Log.d(Config.LOGTAG, "finished merging phone contacts");
2040            mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
2041            updateRosterUi();
2042            mQuickConversationsService.considerSync();
2043        });
2044    }
2045
2046
2047    public void syncRoster(final Account account) {
2048        mRosterSyncTaskManager.execute(account, () -> {
2049            unregisterPhoneAccounts(account);
2050            databaseBackend.writeRoster(account.getRoster());
2051            try { Thread.sleep(500); } catch (InterruptedException e) { }
2052        });
2053    }
2054
2055    public List<Conversation> getConversations() {
2056        return this.conversations;
2057    }
2058
2059    private void markFileDeleted(final File file) {
2060        synchronized (FILENAMES_TO_IGNORE_DELETION) {
2061            if (FILENAMES_TO_IGNORE_DELETION.remove(file.getAbsolutePath())) {
2062                Log.d(Config.LOGTAG, "ignored deletion of " + file.getAbsolutePath());
2063                return;
2064            }
2065        }
2066        final boolean isInternalFile = fileBackend.isInternalFile(file);
2067        final List<String> uuids = databaseBackend.markFileAsDeleted(file, isInternalFile);
2068        Log.d(Config.LOGTAG, "deleted file " + file.getAbsolutePath() + " internal=" + isInternalFile + ", database hits=" + uuids.size());
2069        markUuidsAsDeletedFiles(uuids);
2070    }
2071
2072    private void markUuidsAsDeletedFiles(List<String> uuids) {
2073        boolean deleted = false;
2074        for (Conversation conversation : getConversations()) {
2075            deleted |= conversation.markAsDeleted(uuids);
2076        }
2077        for (final String uuid : uuids) {
2078            evictPreview(uuid);
2079        }
2080        if (deleted) {
2081            updateConversationUi();
2082        }
2083    }
2084
2085    private void markChangedFiles(List<DatabaseBackend.FilePathInfo> infos) {
2086        boolean changed = false;
2087        for (Conversation conversation : getConversations()) {
2088            changed |= conversation.markAsChanged(infos);
2089        }
2090        if (changed) {
2091            updateConversationUi();
2092        }
2093    }
2094
2095    public void populateWithOrderedConversations(final List<Conversation> list) {
2096        populateWithOrderedConversations(list, true, true);
2097    }
2098
2099    public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload) {
2100        populateWithOrderedConversations(list, includeNoFileUpload, true);
2101    }
2102
2103    public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload, final boolean sort) {
2104        final List<String> orderedUuids;
2105        if (sort) {
2106            orderedUuids = null;
2107        } else {
2108            orderedUuids = new ArrayList<>();
2109            for (Conversation conversation : list) {
2110                orderedUuids.add(conversation.getUuid());
2111            }
2112        }
2113        list.clear();
2114        if (includeNoFileUpload) {
2115            list.addAll(getConversations());
2116        } else {
2117            for (Conversation conversation : getConversations()) {
2118                if (conversation.getMode() == Conversation.MODE_SINGLE
2119                        || (conversation.getAccount().httpUploadAvailable() && conversation.getMucOptions().participating())) {
2120                    list.add(conversation);
2121                }
2122            }
2123        }
2124        try {
2125            if (orderedUuids != null) {
2126                Collections.sort(list, (a, b) -> {
2127                    final int indexA = orderedUuids.indexOf(a.getUuid());
2128                    final int indexB = orderedUuids.indexOf(b.getUuid());
2129                    if (indexA == -1 || indexB == -1 || indexA == indexB) {
2130                        return a.compareTo(b);
2131                    }
2132                    return indexA - indexB;
2133                });
2134            } else {
2135                Collections.sort(list);
2136            }
2137        } catch (IllegalArgumentException e) {
2138            //ignore
2139        }
2140    }
2141
2142    public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
2143        if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
2144            return;
2145        } else if (timestamp == 0) {
2146            return;
2147        }
2148        Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
2149        final Runnable runnable = () -> {
2150            final Account account = conversation.getAccount();
2151            List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
2152            if (messages.size() > 0) {
2153                conversation.addAll(0, messages);
2154                callback.onMoreMessagesLoaded(messages.size(), conversation);
2155            } else if (conversation.hasMessagesLeftOnServer()
2156                    && account.isOnlineAndConnected()
2157                    && conversation.getLastClearHistory().getTimestamp() == 0) {
2158                final boolean mamAvailable;
2159                if (conversation.getMode() == Conversation.MODE_SINGLE) {
2160                    mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
2161                } else {
2162                    mamAvailable = conversation.getMucOptions().mamSupport();
2163                }
2164                if (mamAvailable) {
2165                    MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
2166                    if (query != null) {
2167                        query.setCallback(callback);
2168                        callback.informUser(R.string.fetching_history_from_server);
2169                    } else {
2170                        callback.informUser(R.string.not_fetching_history_retention_period);
2171                    }
2172
2173                }
2174            }
2175        };
2176        mDatabaseReaderExecutor.execute(runnable);
2177    }
2178
2179    public List<Account> getAccounts() {
2180        return this.accounts;
2181    }
2182
2183
2184    /**
2185     * 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)
2186     */
2187    public List<Conversation> findAllConferencesWith(Contact contact) {
2188        final ArrayList<Conversation> results = new ArrayList<>();
2189        for (final Conversation c : conversations) {
2190            if (c.getMode() != Conversation.MODE_MULTI) {
2191                continue;
2192            }
2193            final MucOptions mucOptions = c.getMucOptions();
2194            if (c.getJid().asBareJid().equals(contact.getJid().asBareJid()) || (mucOptions != null && mucOptions.isContactInRoom(contact))) {
2195                results.add(c);
2196            }
2197        }
2198        return results;
2199    }
2200
2201    public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
2202        for (final Conversation conversation : haystack) {
2203            if (conversation.getContact() == contact) {
2204                return conversation;
2205            }
2206        }
2207        return null;
2208    }
2209
2210    public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
2211        if (jid == null) {
2212            return null;
2213        }
2214        for (final Conversation conversation : haystack) {
2215            if ((account == null || conversation.getAccount() == account)
2216                    && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
2217                return conversation;
2218            }
2219        }
2220        return null;
2221    }
2222
2223    public boolean isConversationsListEmpty(final Conversation ignore) {
2224        synchronized (this.conversations) {
2225            final int size = this.conversations.size();
2226            return size == 0 || size == 1 && this.conversations.get(0) == ignore;
2227        }
2228    }
2229
2230    public boolean isConversationStillOpen(final Conversation conversation) {
2231        synchronized (this.conversations) {
2232            for (Conversation current : this.conversations) {
2233                if (current == conversation) {
2234                    return true;
2235                }
2236            }
2237        }
2238        return false;
2239    }
2240
2241    public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
2242        return this.findOrCreateConversation(account, jid, muc, false, async);
2243    }
2244
2245    public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
2246        return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
2247    }
2248
2249    public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
2250        synchronized (this.conversations) {
2251            Conversation conversation = find(account, jid);
2252            if (conversation != null) {
2253                return conversation;
2254            }
2255            conversation = databaseBackend.findConversation(account, jid);
2256            final boolean loadMessagesFromDb;
2257            if (conversation != null) {
2258                conversation.setStatus(Conversation.STATUS_AVAILABLE);
2259                conversation.setAccount(account);
2260                if (muc) {
2261                    conversation.setMode(Conversation.MODE_MULTI);
2262                    conversation.setContactJid(jid);
2263                } else {
2264                    conversation.setMode(Conversation.MODE_SINGLE);
2265                    conversation.setContactJid(jid.asBareJid());
2266                }
2267                databaseBackend.updateConversation(conversation);
2268                loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
2269            } else {
2270                String conversationName;
2271                Contact contact = account.getRoster().getContact(jid);
2272                if (contact != null) {
2273                    conversationName = contact.getDisplayName();
2274                } else {
2275                    conversationName = jid.getLocal();
2276                }
2277                if (muc) {
2278                    conversation = new Conversation(conversationName, account, jid,
2279                            Conversation.MODE_MULTI);
2280                } else {
2281                    conversation = new Conversation(conversationName, account, jid.asBareJid(),
2282                            Conversation.MODE_SINGLE);
2283                }
2284                this.databaseBackend.createConversation(conversation);
2285                loadMessagesFromDb = false;
2286            }
2287            final Conversation c = conversation;
2288            final Runnable runnable = () -> {
2289                if (loadMessagesFromDb) {
2290                    c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
2291                    updateConversationUi();
2292                    c.messagesLoaded.set(true);
2293                }
2294                if (account.getXmppConnection() != null
2295                        && !c.getContact().isBlocked()
2296                        && account.getXmppConnection().getFeatures().mam()
2297                        && !muc) {
2298                    if (query == null) {
2299                        mMessageArchiveService.query(c);
2300                    } else {
2301                        if (query.getConversation() == null) {
2302                            mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
2303                        }
2304                    }
2305                }
2306                if (joinAfterCreate) {
2307                    joinMuc(c);
2308                }
2309            };
2310            if (async) {
2311                mDatabaseReaderExecutor.execute(runnable);
2312            } else {
2313                runnable.run();
2314            }
2315            this.conversations.add(conversation);
2316            updateConversationUi();
2317            return conversation;
2318        }
2319    }
2320
2321    public void archiveConversation(Conversation conversation) {
2322        archiveConversation(conversation, true);
2323    }
2324
2325    private void archiveConversation(Conversation conversation, final boolean maySynchronizeWithBookmarks) {
2326        getNotificationService().clear(conversation);
2327        conversation.setStatus(Conversation.STATUS_ARCHIVED);
2328        conversation.setNextMessage(null);
2329        synchronized (this.conversations) {
2330            getMessageArchiveService().kill(conversation);
2331            if (conversation.getMode() == Conversation.MODE_MULTI) {
2332                if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2333                    final Bookmark bookmark = conversation.getBookmark();
2334                    if (maySynchronizeWithBookmarks && bookmark != null && synchronizeWithBookmarks()) {
2335                        if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2336                            Account account = bookmark.getAccount();
2337                            bookmark.setConversation(null);
2338                            deleteBookmark(account, bookmark);
2339                        } else if (bookmark.autojoin()) {
2340                            bookmark.setAutojoin(false);
2341                            createBookmark(bookmark.getAccount(), bookmark);
2342                        }
2343                    }
2344                }
2345                leaveMuc(conversation);
2346            } else {
2347                if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2348                    stopPresenceUpdatesTo(conversation.getContact());
2349                }
2350            }
2351            updateConversation(conversation);
2352            this.conversations.remove(conversation);
2353            updateConversationUi();
2354        }
2355    }
2356
2357    public void stopPresenceUpdatesTo(Contact contact) {
2358        Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
2359        sendPresencePacket(contact.getAccount(), mPresenceGenerator.stopPresenceUpdatesTo(contact));
2360        contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2361    }
2362
2363    public void createAccount(final Account account) {
2364        account.initAccountServices(this);
2365        databaseBackend.createAccount(account);
2366        this.accounts.add(account);
2367        this.reconnectAccountInBackground(account);
2368        updateAccountUi();
2369        syncEnabledAccountSetting();
2370        toggleForegroundService();
2371    }
2372
2373    private void syncEnabledAccountSetting() {
2374        final boolean hasEnabledAccounts = hasEnabledAccounts();
2375        getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
2376        toggleSetProfilePictureActivity(hasEnabledAccounts);
2377    }
2378
2379    private void toggleSetProfilePictureActivity(final boolean enabled) {
2380        try {
2381            final ComponentName name = new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
2382            final int targetState = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
2383            getPackageManager().setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
2384        } catch (IllegalStateException e) {
2385            Log.d(Config.LOGTAG, "unable to toggle profile picture actvitiy");
2386        }
2387    }
2388
2389    private void provisionAccount(final String address, final String password) {
2390        final Jid jid = Jid.ofEscaped(address);
2391        final Account account = new Account(jid, password);
2392        account.setOption(Account.OPTION_DISABLED, true);
2393        Log.d(Config.LOGTAG, jid.asBareJid().toEscapedString() + ": provisioning account");
2394        createAccount(account);
2395    }
2396
2397    public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
2398        new Thread(() -> {
2399            try {
2400                final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
2401                final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
2402                if (cert == null) {
2403                    callback.informUser(R.string.unable_to_parse_certificate);
2404                    return;
2405                }
2406                Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
2407                if (info == null) {
2408                    callback.informUser(R.string.certificate_does_not_contain_jid);
2409                    return;
2410                }
2411                if (findAccountByJid(info.first) == null) {
2412                    final Account account = new Account(info.first, "");
2413                    account.setPrivateKeyAlias(alias);
2414                    account.setOption(Account.OPTION_DISABLED, true);
2415                    account.setOption(Account.OPTION_FIXED_USERNAME, true);
2416                    account.setDisplayName(info.second);
2417                    createAccount(account);
2418                    callback.onAccountCreated(account);
2419                    if (Config.X509_VERIFICATION) {
2420                        try {
2421                            getMemorizingTrustManager().getNonInteractive(account.getServer()).checkClientTrusted(chain, "RSA");
2422                        } catch (CertificateException e) {
2423                            callback.informUser(R.string.certificate_chain_is_not_trusted);
2424                        }
2425                    }
2426                } else {
2427                    callback.informUser(R.string.account_already_exists);
2428                }
2429            } catch (Exception e) {
2430                callback.informUser(R.string.unable_to_parse_certificate);
2431            }
2432        }).start();
2433
2434    }
2435
2436    public void updateKeyInAccount(final Account account, final String alias) {
2437        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
2438        try {
2439            X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
2440            Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
2441            Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
2442            if (info == null) {
2443                showErrorToastInUi(R.string.certificate_does_not_contain_jid);
2444                return;
2445            }
2446            if (account.getJid().asBareJid().equals(info.first)) {
2447                account.setPrivateKeyAlias(alias);
2448                account.setDisplayName(info.second);
2449                databaseBackend.updateAccount(account);
2450                if (Config.X509_VERIFICATION) {
2451                    try {
2452                        getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
2453                    } catch (CertificateException e) {
2454                        showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
2455                    }
2456                    account.getAxolotlService().regenerateKeys(true);
2457                }
2458            } else {
2459                showErrorToastInUi(R.string.jid_does_not_match_certificate);
2460            }
2461        } catch (Exception e) {
2462            e.printStackTrace();
2463        }
2464    }
2465
2466    public boolean updateAccount(final Account account) {
2467        if (databaseBackend.updateAccount(account)) {
2468            account.setShowErrorNotification(true);
2469            this.statusListener.onStatusChanged(account);
2470            databaseBackend.updateAccount(account);
2471            reconnectAccountInBackground(account);
2472            updateAccountUi();
2473            getNotificationService().updateErrorNotification();
2474            toggleForegroundService();
2475            syncEnabledAccountSetting();
2476            mChannelDiscoveryService.cleanCache();
2477            return true;
2478        } else {
2479            return false;
2480        }
2481    }
2482
2483    public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
2484        final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
2485        sendIqPacket(account, iq, (a, packet) -> {
2486            if (packet.getType() == IqPacket.TYPE.RESULT) {
2487                a.setPassword(newPassword);
2488                a.setOption(Account.OPTION_MAGIC_CREATE, false);
2489                databaseBackend.updateAccount(a);
2490                callback.onPasswordChangeSucceeded();
2491            } else {
2492                callback.onPasswordChangeFailed();
2493            }
2494        });
2495    }
2496
2497    public void deleteAccount(final Account account) {
2498        final boolean connected = account.getStatus() == Account.State.ONLINE;
2499        synchronized (this.conversations) {
2500            if (connected) {
2501                account.getAxolotlService().deleteOmemoIdentity();
2502            }
2503            for (final Conversation conversation : conversations) {
2504                if (conversation.getAccount() == account) {
2505                    if (conversation.getMode() == Conversation.MODE_MULTI) {
2506                        if (connected) {
2507                            leaveMuc(conversation);
2508                        }
2509                    }
2510                    conversations.remove(conversation);
2511                    mNotificationService.clear(conversation);
2512                }
2513            }
2514            new Thread(() -> {
2515                for (final Contact contact : account.getRoster().getContacts()) {
2516                    contact.unregisterAsPhoneAccount(this);
2517                }
2518            }).start();
2519            if (account.getXmppConnection() != null) {
2520                new Thread(() -> disconnect(account, !connected)).start();
2521            }
2522            final Runnable runnable = () -> {
2523                if (!databaseBackend.deleteAccount(account)) {
2524                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
2525                }
2526            };
2527            mDatabaseWriterExecutor.execute(runnable);
2528            this.accounts.remove(account);
2529            this.mRosterSyncTaskManager.clear(account);
2530            updateAccountUi();
2531            mNotificationService.updateErrorNotification();
2532            syncEnabledAccountSetting();
2533            toggleForegroundService();
2534        }
2535    }
2536
2537    public void setOnConversationListChangedListener(OnConversationUpdate listener) {
2538        final boolean remainingListeners;
2539        synchronized (LISTENER_LOCK) {
2540            remainingListeners = checkListeners();
2541            if (!this.mOnConversationUpdates.add(listener)) {
2542                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as ConversationListChangedListener");
2543            }
2544            this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2545        }
2546        if (remainingListeners) {
2547            switchToForeground();
2548        }
2549    }
2550
2551    public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
2552        final boolean remainingListeners;
2553        synchronized (LISTENER_LOCK) {
2554            this.mOnConversationUpdates.remove(listener);
2555            this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2556            remainingListeners = checkListeners();
2557        }
2558        if (remainingListeners) {
2559            switchToBackground();
2560        }
2561    }
2562
2563    public void setOnShowErrorToastListener(OnShowErrorToast listener) {
2564        final boolean remainingListeners;
2565        synchronized (LISTENER_LOCK) {
2566            remainingListeners = checkListeners();
2567            if (!this.mOnShowErrorToasts.add(listener)) {
2568                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnShowErrorToastListener");
2569            }
2570        }
2571        if (remainingListeners) {
2572            switchToForeground();
2573        }
2574    }
2575
2576    public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
2577        final boolean remainingListeners;
2578        synchronized (LISTENER_LOCK) {
2579            this.mOnShowErrorToasts.remove(onShowErrorToast);
2580            remainingListeners = checkListeners();
2581        }
2582        if (remainingListeners) {
2583            switchToBackground();
2584        }
2585    }
2586
2587    public void setOnAccountListChangedListener(OnAccountUpdate listener) {
2588        final boolean remainingListeners;
2589        synchronized (LISTENER_LOCK) {
2590            remainingListeners = checkListeners();
2591            if (!this.mOnAccountUpdates.add(listener)) {
2592                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnAccountListChangedtListener");
2593            }
2594        }
2595        if (remainingListeners) {
2596            switchToForeground();
2597        }
2598    }
2599
2600    public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
2601        final boolean remainingListeners;
2602        synchronized (LISTENER_LOCK) {
2603            this.mOnAccountUpdates.remove(listener);
2604            remainingListeners = checkListeners();
2605        }
2606        if (remainingListeners) {
2607            switchToBackground();
2608        }
2609    }
2610
2611    public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2612        final boolean remainingListeners;
2613        synchronized (LISTENER_LOCK) {
2614            remainingListeners = checkListeners();
2615            if (!this.mOnCaptchaRequested.add(listener)) {
2616                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnCaptchaRequestListener");
2617            }
2618        }
2619        if (remainingListeners) {
2620            switchToForeground();
2621        }
2622    }
2623
2624    public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2625        final boolean remainingListeners;
2626        synchronized (LISTENER_LOCK) {
2627            this.mOnCaptchaRequested.remove(listener);
2628            remainingListeners = checkListeners();
2629        }
2630        if (remainingListeners) {
2631            switchToBackground();
2632        }
2633    }
2634
2635    public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
2636        final boolean remainingListeners;
2637        synchronized (LISTENER_LOCK) {
2638            remainingListeners = checkListeners();
2639            if (!this.mOnRosterUpdates.add(listener)) {
2640                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnRosterUpdateListener");
2641            }
2642        }
2643        if (remainingListeners) {
2644            switchToForeground();
2645        }
2646    }
2647
2648    public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
2649        final boolean remainingListeners;
2650        synchronized (LISTENER_LOCK) {
2651            this.mOnRosterUpdates.remove(listener);
2652            remainingListeners = checkListeners();
2653        }
2654        if (remainingListeners) {
2655            switchToBackground();
2656        }
2657    }
2658
2659    public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2660        final boolean remainingListeners;
2661        synchronized (LISTENER_LOCK) {
2662            remainingListeners = checkListeners();
2663            if (!this.mOnUpdateBlocklist.add(listener)) {
2664                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnUpdateBlocklistListener");
2665            }
2666        }
2667        if (remainingListeners) {
2668            switchToForeground();
2669        }
2670    }
2671
2672    public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2673        final boolean remainingListeners;
2674        synchronized (LISTENER_LOCK) {
2675            this.mOnUpdateBlocklist.remove(listener);
2676            remainingListeners = checkListeners();
2677        }
2678        if (remainingListeners) {
2679            switchToBackground();
2680        }
2681    }
2682
2683    public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2684        final boolean remainingListeners;
2685        synchronized (LISTENER_LOCK) {
2686            remainingListeners = checkListeners();
2687            if (!this.mOnKeyStatusUpdated.add(listener)) {
2688                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnKeyStatusUpdateListener");
2689            }
2690        }
2691        if (remainingListeners) {
2692            switchToForeground();
2693        }
2694    }
2695
2696    public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
2697        final boolean remainingListeners;
2698        synchronized (LISTENER_LOCK) {
2699            this.mOnKeyStatusUpdated.remove(listener);
2700            remainingListeners = checkListeners();
2701        }
2702        if (remainingListeners) {
2703            switchToBackground();
2704        }
2705    }
2706
2707    public void setOnRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
2708        final boolean remainingListeners;
2709        synchronized (LISTENER_LOCK) {
2710            remainingListeners = checkListeners();
2711            if (!this.onJingleRtpConnectionUpdate.add(listener)) {
2712                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnJingleRtpConnectionUpdate");
2713            }
2714        }
2715        if (remainingListeners) {
2716            switchToForeground();
2717        }
2718    }
2719
2720    public void removeRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
2721        final boolean remainingListeners;
2722        synchronized (LISTENER_LOCK) {
2723            this.onJingleRtpConnectionUpdate.remove(listener);
2724            remainingListeners = checkListeners();
2725        }
2726        if (remainingListeners) {
2727            switchToBackground();
2728        }
2729    }
2730
2731    public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2732        final boolean remainingListeners;
2733        synchronized (LISTENER_LOCK) {
2734            remainingListeners = checkListeners();
2735            if (!this.mOnMucRosterUpdate.add(listener)) {
2736                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnMucRosterListener");
2737            }
2738        }
2739        if (remainingListeners) {
2740            switchToForeground();
2741        }
2742    }
2743
2744    public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
2745        final boolean remainingListeners;
2746        synchronized (LISTENER_LOCK) {
2747            this.mOnMucRosterUpdate.remove(listener);
2748            remainingListeners = checkListeners();
2749        }
2750        if (remainingListeners) {
2751            switchToBackground();
2752        }
2753    }
2754
2755    public boolean checkListeners() {
2756        return (this.mOnAccountUpdates.size() == 0
2757                && this.mOnConversationUpdates.size() == 0
2758                && this.mOnRosterUpdates.size() == 0
2759                && this.mOnCaptchaRequested.size() == 0
2760                && this.mOnMucRosterUpdate.size() == 0
2761                && this.mOnUpdateBlocklist.size() == 0
2762                && this.mOnShowErrorToasts.size() == 0
2763                && this.onJingleRtpConnectionUpdate.size() == 0
2764                && this.mOnKeyStatusUpdated.size() == 0);
2765    }
2766
2767    private void switchToForeground() {
2768        final boolean broadcastLastActivity = broadcastLastActivity();
2769        for (Conversation conversation : getConversations()) {
2770            if (conversation.getMode() == Conversation.MODE_MULTI) {
2771                conversation.getMucOptions().resetChatState();
2772            } else {
2773                conversation.setIncomingChatState(Config.DEFAULT_CHAT_STATE);
2774            }
2775        }
2776        for (Account account : getAccounts()) {
2777            if (account.getStatus() == Account.State.ONLINE) {
2778                account.deactivateGracePeriod();
2779                final XmppConnection connection = account.getXmppConnection();
2780                if (connection != null) {
2781                    if (connection.getFeatures().csi()) {
2782                        connection.sendActive();
2783                    }
2784                    if (broadcastLastActivity) {
2785                        sendPresence(account, false); //send new presence but don't include idle because we are not
2786                    }
2787                }
2788            }
2789        }
2790        Log.d(Config.LOGTAG, "app switched into foreground");
2791    }
2792
2793    private void switchToBackground() {
2794        final boolean broadcastLastActivity = broadcastLastActivity();
2795        if (broadcastLastActivity) {
2796            mLastActivity = System.currentTimeMillis();
2797            final SharedPreferences.Editor editor = getPreferences().edit();
2798            editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
2799            editor.apply();
2800        }
2801        for (Account account : getAccounts()) {
2802            if (account.getStatus() == Account.State.ONLINE) {
2803                XmppConnection connection = account.getXmppConnection();
2804                if (connection != null) {
2805                    if (broadcastLastActivity) {
2806                        sendPresence(account, true);
2807                    }
2808                    if (connection.getFeatures().csi()) {
2809                        connection.sendInactive();
2810                    }
2811                }
2812            }
2813        }
2814        this.mNotificationService.setIsInForeground(false);
2815        Log.d(Config.LOGTAG, "app switched into background");
2816    }
2817
2818    private void connectMultiModeConversations(Account account) {
2819        List<Conversation> conversations = getConversations();
2820        for (Conversation conversation : conversations) {
2821            if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2822                joinMuc(conversation);
2823            }
2824        }
2825    }
2826
2827    public void mucSelfPingAndRejoin(final Conversation conversation) {
2828        final Account account = conversation.getAccount();
2829        synchronized (account.inProgressConferenceJoins) {
2830            if (account.inProgressConferenceJoins.contains(conversation)) {
2831                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because join is already under way");
2832                return;
2833            }
2834        }
2835        synchronized (account.inProgressConferencePings) {
2836            if (!account.inProgressConferencePings.add(conversation)) {
2837                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because ping is already under way");
2838                return;
2839            }
2840        }
2841        final Jid self = conversation.getMucOptions().getSelf().getFullJid();
2842        final IqPacket ping = new IqPacket(IqPacket.TYPE.GET);
2843        ping.setTo(self);
2844        ping.addChild("ping", Namespace.PING);
2845        sendIqPacket(conversation.getAccount(), ping, (a, response) -> {
2846            if (response.getType() == IqPacket.TYPE.ERROR) {
2847                Element error = response.findChild("error");
2848                if (error == null || error.hasChild("service-unavailable") || error.hasChild("feature-not-implemented") || error.hasChild("item-not-found")) {
2849                    Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back as ignorable error");
2850                } else {
2851                    Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " failed. attempting rejoin");
2852                    joinMuc(conversation);
2853                }
2854            } else if (response.getType() == IqPacket.TYPE.RESULT) {
2855                Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back fine");
2856            }
2857            synchronized (account.inProgressConferencePings) {
2858                account.inProgressConferencePings.remove(conversation);
2859            }
2860        });
2861    }
2862
2863    public void joinMuc(Conversation conversation) {
2864        joinMuc(conversation, null, false);
2865    }
2866
2867    public void joinMuc(Conversation conversation, boolean followedInvite) {
2868        joinMuc(conversation, null, followedInvite);
2869    }
2870
2871    private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2872        joinMuc(conversation, onConferenceJoined, false);
2873    }
2874
2875    private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2876        final Account account = conversation.getAccount();
2877        synchronized (account.pendingConferenceJoins) {
2878            account.pendingConferenceJoins.remove(conversation);
2879        }
2880        synchronized (account.pendingConferenceLeaves) {
2881            account.pendingConferenceLeaves.remove(conversation);
2882        }
2883        if (account.getStatus() == Account.State.ONLINE) {
2884            synchronized (account.inProgressConferenceJoins) {
2885                account.inProgressConferenceJoins.add(conversation);
2886            }
2887            if (Config.MUC_LEAVE_BEFORE_JOIN) {
2888                sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
2889            }
2890            conversation.resetMucOptions();
2891            if (onConferenceJoined != null) {
2892                conversation.getMucOptions().flagNoAutoPushConfiguration();
2893            }
2894            conversation.setHasMessagesLeftOnServer(false);
2895            fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2896
2897                private void join(Conversation conversation) {
2898                    Account account = conversation.getAccount();
2899                    final MucOptions mucOptions = conversation.getMucOptions();
2900
2901                    if (mucOptions.nonanonymous() && !mucOptions.membersOnly() && !conversation.getBooleanAttribute("accept_non_anonymous", false)) {
2902                        synchronized (account.inProgressConferenceJoins) {
2903                            account.inProgressConferenceJoins.remove(conversation);
2904                        }
2905                        mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
2906                        updateConversationUi();
2907                        if (onConferenceJoined != null) {
2908                            onConferenceJoined.onConferenceJoined(conversation);
2909                        }
2910                        return;
2911                    }
2912
2913                    final Jid joinJid = mucOptions.getSelf().getFullJid();
2914                    Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
2915                    PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
2916                    packet.setTo(joinJid);
2917                    Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2918                    if (conversation.getMucOptions().getPassword() != null) {
2919                        x.addChild("password").setContent(mucOptions.getPassword());
2920                    }
2921
2922                    if (mucOptions.mamSupport()) {
2923                        // Use MAM instead of the limited muc history to get history
2924                        x.addChild("history").setAttribute("maxchars", "0");
2925                    } else {
2926                        // Fallback to muc history
2927                        x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
2928                    }
2929                    sendPresencePacket(account, packet);
2930                    if (onConferenceJoined != null) {
2931                        onConferenceJoined.onConferenceJoined(conversation);
2932                    }
2933                    if (!joinJid.equals(conversation.getJid())) {
2934                        conversation.setContactJid(joinJid);
2935                        databaseBackend.updateConversation(conversation);
2936                    }
2937
2938                    if (mucOptions.mamSupport()) {
2939                        getMessageArchiveService().catchupMUC(conversation);
2940                    }
2941                    if (mucOptions.isPrivateAndNonAnonymous()) {
2942                        fetchConferenceMembers(conversation);
2943
2944                        if (followedInvite) {
2945                            final Bookmark bookmark = conversation.getBookmark();
2946                            if (bookmark != null) {
2947                                if (!bookmark.autojoin()) {
2948                                    bookmark.setAutojoin(true);
2949                                    createBookmark(account, bookmark);
2950                                }
2951                            } else {
2952                                saveConversationAsBookmark(conversation, null);
2953                            }
2954                        }
2955                    }
2956                    synchronized (account.inProgressConferenceJoins) {
2957                        account.inProgressConferenceJoins.remove(conversation);
2958                        sendUnsentMessages(conversation);
2959                    }
2960                }
2961
2962                @Override
2963                public void onConferenceConfigurationFetched(Conversation conversation) {
2964                    if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2965                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
2966                        return;
2967                    }
2968                    join(conversation);
2969                }
2970
2971                @Override
2972                public void onFetchFailed(final Conversation conversation, final String errorCondition) {
2973                    if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2974                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
2975                        return;
2976                    }
2977                    if ("remote-server-not-found".equals(errorCondition)) {
2978                        synchronized (account.inProgressConferenceJoins) {
2979                            account.inProgressConferenceJoins.remove(conversation);
2980                        }
2981                        conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2982                        updateConversationUi();
2983                    } else {
2984                        join(conversation);
2985                        fetchConferenceConfiguration(conversation);
2986                    }
2987                }
2988            });
2989            updateConversationUi();
2990        } else {
2991            synchronized (account.pendingConferenceJoins) {
2992                account.pendingConferenceJoins.add(conversation);
2993            }
2994            conversation.resetMucOptions();
2995            conversation.setHasMessagesLeftOnServer(false);
2996            updateConversationUi();
2997        }
2998    }
2999
3000    private void fetchConferenceMembers(final Conversation conversation) {
3001        final Account account = conversation.getAccount();
3002        final AxolotlService axolotlService = account.getAxolotlService();
3003        final String[] affiliations = {"member", "admin", "owner"};
3004        OnIqPacketReceived callback = new OnIqPacketReceived() {
3005
3006            private int i = 0;
3007            private boolean success = true;
3008
3009            @Override
3010            public void onIqPacketReceived(Account account, IqPacket packet) {
3011                final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
3012                Element query = packet.query("http://jabber.org/protocol/muc#admin");
3013                if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
3014                    for (Element child : query.getChildren()) {
3015                        if ("item".equals(child.getName())) {
3016                            MucOptions.User user = AbstractParser.parseItem(conversation, child);
3017                            if (!user.realJidMatchesAccount()) {
3018                                boolean isNew = conversation.getMucOptions().updateUser(user);
3019                                Contact contact = user.getContact();
3020                                if (omemoEnabled
3021                                        && isNew
3022                                        && user.getRealJid() != null
3023                                        && (contact == null || !contact.mutualPresenceSubscription())
3024                                        && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
3025                                    axolotlService.fetchDeviceIds(user.getRealJid());
3026                                }
3027                            }
3028                        }
3029                    }
3030                } else {
3031                    success = false;
3032                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
3033                }
3034                ++i;
3035                if (i >= affiliations.length) {
3036                    List<Jid> members = conversation.getMucOptions().getMembers(true);
3037                    if (success) {
3038                        List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
3039                        boolean changed = false;
3040                        for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
3041                            Jid jid = iterator.next();
3042                            if (!members.contains(jid) && !members.contains(jid.getDomain())) {
3043                                iterator.remove();
3044                                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
3045                                changed = true;
3046                            }
3047                        }
3048                        if (changed) {
3049                            conversation.setAcceptedCryptoTargets(cryptoTargets);
3050                            updateConversation(conversation);
3051                        }
3052                    }
3053                    getAvatarService().clear(conversation);
3054                    updateMucRosterUi();
3055                    updateConversationUi();
3056                }
3057            }
3058        };
3059        for (String affiliation : affiliations) {
3060            sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
3061        }
3062        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
3063    }
3064
3065    public void providePasswordForMuc(Conversation conversation, String password) {
3066        if (conversation.getMode() == Conversation.MODE_MULTI) {
3067            conversation.getMucOptions().setPassword(password);
3068            if (conversation.getBookmark() != null) {
3069                final Bookmark bookmark = conversation.getBookmark();
3070                if (synchronizeWithBookmarks()) {
3071                    bookmark.setAutojoin(true);
3072                }
3073                createBookmark(conversation.getAccount(), bookmark);
3074            }
3075            updateConversation(conversation);
3076            joinMuc(conversation);
3077        }
3078    }
3079
3080    private boolean hasEnabledAccounts() {
3081        if (this.accounts == null) {
3082            return false;
3083        }
3084        for (Account account : this.accounts) {
3085            if (account.isEnabled()) {
3086                return true;
3087            }
3088        }
3089        return false;
3090    }
3091
3092
3093    public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
3094        getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
3095    }
3096
3097    public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3098        getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
3099    }
3100
3101
3102    public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3103        new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
3104    }
3105
3106    public void persistSelfNick(MucOptions.User self) {
3107        final Conversation conversation = self.getConversation();
3108        final boolean tookProposedNickFromBookmark = conversation.getMucOptions().isTookProposedNickFromBookmark();
3109        Jid full = self.getFullJid();
3110        if (!full.equals(conversation.getJid())) {
3111            Log.d(Config.LOGTAG, "nick changed. updating");
3112            conversation.setContactJid(full);
3113            databaseBackend.updateConversation(conversation);
3114        }
3115
3116        final Bookmark bookmark = conversation.getBookmark();
3117        final String bookmarkedNick = bookmark == null ? null : bookmark.getNick();
3118        if (bookmark != null && (tookProposedNickFromBookmark || TextUtils.isEmpty(bookmarkedNick)) && !full.getResource().equals(bookmarkedNick)) {
3119            final Account account = conversation.getAccount();
3120            final String defaultNick = MucOptions.defaultNick(account);
3121            if (TextUtils.isEmpty(bookmarkedNick) && full.getResource().equals(defaultNick)) {
3122                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not overwrite empty bookmark nick with default nick for " + conversation.getJid().asBareJid());
3123                return;
3124            }
3125            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persist nick '" + full.getResource() + "' into bookmark for " + conversation.getJid().asBareJid());
3126            bookmark.setNick(full.getResource());
3127            createBookmark(bookmark.getAccount(), bookmark);
3128        }
3129    }
3130
3131    public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
3132        final MucOptions options = conversation.getMucOptions();
3133        final Jid joinJid = options.createJoinJid(nick);
3134        if (joinJid == null) {
3135            return false;
3136        }
3137        if (options.online()) {
3138            Account account = conversation.getAccount();
3139            options.setOnRenameListener(new OnRenameListener() {
3140
3141                @Override
3142                public void onSuccess() {
3143                    callback.success(conversation);
3144                }
3145
3146                @Override
3147                public void onFailure() {
3148                    callback.error(R.string.nick_in_use, conversation);
3149                }
3150            });
3151
3152            final PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous());
3153            packet.setTo(joinJid);
3154            sendPresencePacket(account, packet);
3155        } else {
3156            conversation.setContactJid(joinJid);
3157            databaseBackend.updateConversation(conversation);
3158            if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
3159                Bookmark bookmark = conversation.getBookmark();
3160                if (bookmark != null) {
3161                    bookmark.setNick(nick);
3162                    createBookmark(bookmark.getAccount(), bookmark);
3163                }
3164                joinMuc(conversation);
3165            }
3166        }
3167        return true;
3168    }
3169
3170    public void leaveMuc(Conversation conversation) {
3171        leaveMuc(conversation, false);
3172    }
3173
3174    private void leaveMuc(Conversation conversation, boolean now) {
3175        final Account account = conversation.getAccount();
3176        synchronized (account.pendingConferenceJoins) {
3177            account.pendingConferenceJoins.remove(conversation);
3178        }
3179        synchronized (account.pendingConferenceLeaves) {
3180            account.pendingConferenceLeaves.remove(conversation);
3181        }
3182        if (account.getStatus() == Account.State.ONLINE || now) {
3183            sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
3184            conversation.getMucOptions().setOffline();
3185            Bookmark bookmark = conversation.getBookmark();
3186            if (bookmark != null) {
3187                bookmark.setConversation(null);
3188            }
3189            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
3190        } else {
3191            synchronized (account.pendingConferenceLeaves) {
3192                account.pendingConferenceLeaves.add(conversation);
3193            }
3194        }
3195    }
3196
3197    public String findConferenceServer(final Account account) {
3198        String server;
3199        if (account.getXmppConnection() != null) {
3200            server = account.getXmppConnection().getMucServer();
3201            if (server != null) {
3202                return server;
3203            }
3204        }
3205        for (Account other : getAccounts()) {
3206            if (other != account && other.getXmppConnection() != null) {
3207                server = other.getXmppConnection().getMucServer();
3208                if (server != null) {
3209                    return server;
3210                }
3211            }
3212        }
3213        return null;
3214    }
3215
3216
3217    public void createPublicChannel(final Account account, final String name, final Jid address, final UiCallback<Conversation> callback) {
3218        joinMuc(findOrCreateConversation(account, address, true, false, true), conversation -> {
3219            final Bundle configuration = IqGenerator.defaultChannelConfiguration();
3220            if (!TextUtils.isEmpty(name)) {
3221                configuration.putString("muc#roomconfig_roomname", name);
3222            }
3223            pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3224                @Override
3225                public void onPushSucceeded() {
3226                    saveConversationAsBookmark(conversation, name);
3227                    callback.success(conversation);
3228                }
3229
3230                @Override
3231                public void onPushFailed() {
3232                    if (conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
3233                        callback.error(R.string.unable_to_set_channel_configuration, conversation);
3234                    } else {
3235                        callback.error(R.string.joined_an_existing_channel, conversation);
3236                    }
3237                }
3238            });
3239        });
3240    }
3241
3242    public boolean createAdhocConference(final Account account,
3243                                         final String name,
3244                                         final Iterable<Jid> jids,
3245                                         final UiCallback<Conversation> callback) {
3246        Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
3247        if (account.getStatus() == Account.State.ONLINE) {
3248            try {
3249                String server = findConferenceServer(account);
3250                if (server == null) {
3251                    if (callback != null) {
3252                        callback.error(R.string.no_conference_server_found, null);
3253                    }
3254                    return false;
3255                }
3256                final Jid jid = Jid.of(CryptoHelper.pronounceable(getRNG()), server, null);
3257                final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
3258                joinMuc(conversation, new OnConferenceJoined() {
3259                    @Override
3260                    public void onConferenceJoined(final Conversation conversation) {
3261                        final Bundle configuration = IqGenerator.defaultGroupChatConfiguration();
3262                        if (!TextUtils.isEmpty(name)) {
3263                            configuration.putString("muc#roomconfig_roomname", name);
3264                        }
3265                        pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3266                            @Override
3267                            public void onPushSucceeded() {
3268                                for (Jid invite : jids) {
3269                                    invite(conversation, invite);
3270                                }
3271                                for (String resource : account.getSelfContact().getPresences().toResourceArray()) {
3272                                    Jid other = account.getJid().withResource(resource);
3273                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending direct invite to " + other);
3274                                    directInvite(conversation, other);
3275                                }
3276                                saveConversationAsBookmark(conversation, name);
3277                                if (callback != null) {
3278                                    callback.success(conversation);
3279                                }
3280                            }
3281
3282                            @Override
3283                            public void onPushFailed() {
3284                                archiveConversation(conversation);
3285                                if (callback != null) {
3286                                    callback.error(R.string.conference_creation_failed, conversation);
3287                                }
3288                            }
3289                        });
3290                    }
3291                });
3292                return true;
3293            } catch (IllegalArgumentException e) {
3294                if (callback != null) {
3295                    callback.error(R.string.conference_creation_failed, null);
3296                }
3297                return false;
3298            }
3299        } else {
3300            if (callback != null) {
3301                callback.error(R.string.not_connected_try_again, null);
3302            }
3303            return false;
3304        }
3305    }
3306
3307    public void fetchConferenceConfiguration(final Conversation conversation) {
3308        fetchConferenceConfiguration(conversation, null);
3309    }
3310
3311    public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
3312        IqPacket request = mIqGenerator.queryDiscoInfo(conversation.getJid().asBareJid());
3313        sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3314            @Override
3315            public void onIqPacketReceived(Account account, IqPacket packet) {
3316                if (packet.getType() == IqPacket.TYPE.RESULT) {
3317                    final MucOptions mucOptions = conversation.getMucOptions();
3318                    final Bookmark bookmark = conversation.getBookmark();
3319                    final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
3320
3321                    if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
3322                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
3323                        updateConversation(conversation);
3324                    }
3325
3326                    if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
3327                        if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
3328                            createBookmark(account, bookmark);
3329                        }
3330                    }
3331
3332
3333                    if (callback != null) {
3334                        callback.onConferenceConfigurationFetched(conversation);
3335                    }
3336
3337
3338                    updateConversationUi();
3339                } else if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
3340                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received timeout waiting for conference configuration fetch");
3341                } else {
3342                    if (callback != null) {
3343                        callback.onFetchFailed(conversation, packet.getErrorCondition());
3344                    }
3345                }
3346            }
3347        });
3348    }
3349
3350    public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
3351        pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
3352    }
3353
3354    public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
3355        Log.d(Config.LOGTAG, "pushing node configuration");
3356        sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
3357            @Override
3358            public void onIqPacketReceived(Account account, IqPacket packet) {
3359                if (packet.getType() == IqPacket.TYPE.RESULT) {
3360                    Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
3361                    Element configuration = pubsub == null ? null : pubsub.findChild("configure");
3362                    Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
3363                    if (x != null) {
3364                        Data data = Data.parse(x);
3365                        data.submit(options);
3366                        sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
3367                            @Override
3368                            public void onIqPacketReceived(Account account, IqPacket packet) {
3369                                if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
3370                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully changed node configuration for node " + node);
3371                                    callback.onPushSucceeded();
3372                                } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3373                                    callback.onPushFailed();
3374                                }
3375                            }
3376                        });
3377                    } else if (callback != null) {
3378                        callback.onPushFailed();
3379                    }
3380                } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3381                    callback.onPushFailed();
3382                }
3383            }
3384        });
3385    }
3386
3387    public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
3388        if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
3389            conversation.setAttribute("accept_non_anonymous", true);
3390            updateConversation(conversation);
3391        }
3392        if (options.containsKey("muc#roomconfig_moderatedroom")) {
3393            final boolean moderated = "1".equals(options.getString("muc#roomconfig_moderatedroom"));
3394            options.putString("members_by_default", moderated ? "0" : "1");
3395        }
3396        final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3397        request.setTo(conversation.getJid().asBareJid());
3398        request.query("http://jabber.org/protocol/muc#owner");
3399        sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3400            @Override
3401            public void onIqPacketReceived(Account account, IqPacket packet) {
3402                if (packet.getType() == IqPacket.TYPE.RESULT) {
3403                    final Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
3404                    data.submit(options);
3405                    final IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3406                    set.setTo(conversation.getJid().asBareJid());
3407                    set.query("http://jabber.org/protocol/muc#owner").addChild(data);
3408                    sendIqPacket(account, set, new OnIqPacketReceived() {
3409                        @Override
3410                        public void onIqPacketReceived(Account account, IqPacket packet) {
3411                            if (callback != null) {
3412                                if (packet.getType() == IqPacket.TYPE.RESULT) {
3413                                    callback.onPushSucceeded();
3414                                } else {
3415                                    callback.onPushFailed();
3416                                }
3417                            }
3418                        }
3419                    });
3420                } else {
3421                    if (callback != null) {
3422                        callback.onPushFailed();
3423                    }
3424                }
3425            }
3426        });
3427    }
3428
3429    public void pushSubjectToConference(final Conversation conference, final String subject) {
3430        MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
3431        this.sendMessagePacket(conference.getAccount(), packet);
3432    }
3433
3434    public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
3435        final Jid jid = user.asBareJid();
3436        final IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
3437        sendIqPacket(conference.getAccount(), request, (account, response) -> {
3438            if (response.getType() == IqPacket.TYPE.RESULT) {
3439                conference.getMucOptions().changeAffiliation(jid, affiliation);
3440                getAvatarService().clear(conference);
3441                if (callback != null) {
3442                    callback.onAffiliationChangedSuccessful(jid);
3443                } else {
3444                    Log.d(Config.LOGTAG, "changed affiliation of " + user + " to " + affiliation);
3445                }
3446            } else if (callback != null) {
3447                callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
3448            } else {
3449                Log.d(Config.LOGTAG, "unable to change affiliation");
3450            }
3451        });
3452    }
3453
3454    public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) {
3455        IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
3456        sendIqPacket(conference.getAccount(), request, (account, packet) -> {
3457            if (packet.getType() != IqPacket.TYPE.RESULT) {
3458                Log.d(Config.LOGTAG, account.getJid().asBareJid() + " unable to change role of " + nick);
3459            }
3460        });
3461    }
3462
3463    public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
3464        IqPacket request = new IqPacket(IqPacket.TYPE.SET);
3465        request.setTo(conversation.getJid().asBareJid());
3466        request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
3467        sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3468            @Override
3469            public void onIqPacketReceived(Account account, IqPacket packet) {
3470                if (packet.getType() == IqPacket.TYPE.RESULT) {
3471                    if (callback != null) {
3472                        callback.onRoomDestroySucceeded();
3473                    }
3474                } else if (packet.getType() == IqPacket.TYPE.ERROR) {
3475                    if (callback != null) {
3476                        callback.onRoomDestroyFailed();
3477                    }
3478                }
3479            }
3480        });
3481    }
3482
3483    private void disconnect(Account account, boolean force) {
3484        if ((account.getStatus() == Account.State.ONLINE)
3485                || (account.getStatus() == Account.State.DISABLED)) {
3486            final XmppConnection connection = account.getXmppConnection();
3487            if (!force) {
3488                List<Conversation> conversations = getConversations();
3489                for (Conversation conversation : conversations) {
3490                    if (conversation.getAccount() == account) {
3491                        if (conversation.getMode() == Conversation.MODE_MULTI) {
3492                            leaveMuc(conversation, true);
3493                        }
3494                    }
3495                }
3496                sendOfflinePresence(account);
3497            }
3498            connection.disconnect(force);
3499        }
3500    }
3501
3502    @Override
3503    public IBinder onBind(Intent intent) {
3504        return mBinder;
3505    }
3506
3507    public void updateMessage(Message message) {
3508        updateMessage(message, true);
3509    }
3510
3511    public void updateMessage(Message message, boolean includeBody) {
3512        databaseBackend.updateMessage(message, includeBody);
3513        updateConversationUi();
3514    }
3515
3516    public void createMessageAsync(final Message message) {
3517        mDatabaseWriterExecutor.execute(() -> databaseBackend.createMessage(message));
3518    }
3519
3520    public void updateMessage(Message message, String uuid) {
3521        if (!databaseBackend.updateMessage(message, uuid)) {
3522            Log.e(Config.LOGTAG, "error updated message in DB after edit");
3523        }
3524        updateConversationUi();
3525    }
3526
3527    protected void syncDirtyContacts(Account account) {
3528        for (Contact contact : account.getRoster().getContacts()) {
3529            if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
3530                pushContactToServer(contact);
3531            }
3532            if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
3533                deleteContactOnServer(contact);
3534            }
3535        }
3536    }
3537
3538    protected void unregisterPhoneAccounts(final Account account) {
3539        for (final Contact contact : account.getRoster().getContacts()) {
3540            if (!contact.showInRoster()) {
3541                contact.unregisterAsPhoneAccount(this);
3542            }
3543        }
3544    }
3545
3546    public void createContact(final Contact contact, final boolean autoGrant) {
3547        createContact(contact, autoGrant, null);
3548    }
3549
3550    public void createContact(final Contact contact, final boolean autoGrant, final String preAuth) {
3551        if (autoGrant) {
3552            contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
3553            contact.setOption(Contact.Options.ASKING);
3554        }
3555        pushContactToServer(contact, preAuth);
3556    }
3557
3558    public void pushContactToServer(final Contact contact) {
3559        pushContactToServer(contact, null);
3560    }
3561
3562    private void pushContactToServer(final Contact contact, final String preAuth) {
3563        contact.resetOption(Contact.Options.DIRTY_DELETE);
3564        contact.setOption(Contact.Options.DIRTY_PUSH);
3565        final Account account = contact.getAccount();
3566        if (account.getStatus() == Account.State.ONLINE) {
3567            final boolean ask = contact.getOption(Contact.Options.ASKING);
3568            final boolean sendUpdates = contact
3569                    .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
3570                    && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
3571            final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3572            iq.query(Namespace.ROSTER).addChild(contact.asElement());
3573            account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3574            if (sendUpdates) {
3575                sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
3576            }
3577            if (ask) {
3578                sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact, preAuth));
3579            }
3580        } else {
3581            syncRoster(contact.getAccount());
3582        }
3583    }
3584
3585    public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
3586        new Thread(() -> {
3587            final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3588            final int size = Config.AVATAR_SIZE;
3589            final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3590            if (avatar != null) {
3591                if (!getFileBackend().save(avatar)) {
3592                    callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3593                    return;
3594                }
3595                avatar.owner = conversation.getJid().asBareJid();
3596                publishMucAvatar(conversation, avatar, callback);
3597            } else {
3598                callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3599            }
3600        }).start();
3601    }
3602
3603    public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
3604        new Thread(() -> {
3605            final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3606            final int size = Config.AVATAR_SIZE;
3607            final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3608            if (avatar != null) {
3609                if (!getFileBackend().save(avatar)) {
3610                    Log.d(Config.LOGTAG, "unable to save vcard");
3611                    callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3612                    return;
3613                }
3614                publishAvatar(account, avatar, callback);
3615            } else {
3616                callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3617            }
3618        }).start();
3619
3620    }
3621
3622    private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
3623        final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
3624        sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
3625            boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
3626            if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
3627                Element vcard = response.findChild("vCard", "vcard-temp");
3628                if (vcard == null) {
3629                    vcard = new Element("vCard", "vcard-temp");
3630                }
3631                Element photo = vcard.findChild("PHOTO");
3632                if (photo == null) {
3633                    photo = vcard.addChild("PHOTO");
3634                }
3635                photo.clearChildren();
3636                photo.addChild("TYPE").setContent(avatar.type);
3637                photo.addChild("BINVAL").setContent(avatar.image);
3638                IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3639                publication.setTo(conversation.getJid().asBareJid());
3640                publication.addChild(vcard);
3641                sendIqPacket(account, publication, (a1, publicationResponse) -> {
3642                    if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3643                        callback.onAvatarPublicationSucceeded();
3644                    } else {
3645                        Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
3646                        callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3647                    }
3648                });
3649            } else {
3650                Log.d(Config.LOGTAG, "failed to request vcard " + response.toString());
3651                callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
3652            }
3653        });
3654    }
3655
3656    public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
3657        final Bundle options;
3658        if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
3659            options = PublishOptions.openAccess();
3660        } else {
3661            options = null;
3662        }
3663        publishAvatar(account, avatar, options, true, callback);
3664    }
3665
3666    public void publishAvatar(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3667        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": publishing avatar. options=" + options);
3668        IqPacket packet = this.mIqGenerator.publishAvatar(avatar, options);
3669        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3670
3671            @Override
3672            public void onIqPacketReceived(Account account, IqPacket result) {
3673                if (result.getType() == IqPacket.TYPE.RESULT) {
3674                    publishAvatarMetadata(account, avatar, options, true, callback);
3675                } else if (retry && PublishOptions.preconditionNotMet(result)) {
3676                    pushNodeConfiguration(account, "urn:xmpp:avatar:data", options, new OnConfigurationPushed() {
3677                        @Override
3678                        public void onPushSucceeded() {
3679                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar node");
3680                            publishAvatar(account, avatar, options, false, callback);
3681                        }
3682
3683                        @Override
3684                        public void onPushFailed() {
3685                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar node");
3686                            publishAvatar(account, avatar, null, false, callback);
3687                        }
3688                    });
3689                } else {
3690                    Element error = result.findChild("error");
3691                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
3692                    if (callback != null) {
3693                        callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3694                    }
3695                }
3696            }
3697        });
3698    }
3699
3700    public void publishAvatarMetadata(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3701        final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
3702        sendIqPacket(account, packet, new OnIqPacketReceived() {
3703            @Override
3704            public void onIqPacketReceived(Account account, IqPacket result) {
3705                if (result.getType() == IqPacket.TYPE.RESULT) {
3706                    if (account.setAvatar(avatar.getFilename())) {
3707                        getAvatarService().clear(account);
3708                        databaseBackend.updateAccount(account);
3709                        notifyAccountAvatarHasChanged(account);
3710                    }
3711                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
3712                    if (callback != null) {
3713                        callback.onAvatarPublicationSucceeded();
3714                    }
3715                } else if (retry && PublishOptions.preconditionNotMet(result)) {
3716                    pushNodeConfiguration(account, "urn:xmpp:avatar:metadata", options, new OnConfigurationPushed() {
3717                        @Override
3718                        public void onPushSucceeded() {
3719                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar meta data node");
3720                            publishAvatarMetadata(account, avatar, options, false, callback);
3721                        }
3722
3723                        @Override
3724                        public void onPushFailed() {
3725                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar meta data node");
3726                            publishAvatarMetadata(account, avatar, null, false, callback);
3727                        }
3728                    });
3729                } else {
3730                    if (callback != null) {
3731                        callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3732                    }
3733                }
3734            }
3735        });
3736    }
3737
3738    public void republishAvatarIfNeeded(Account account) {
3739        if (account.getAxolotlService().isPepBroken()) {
3740            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
3741            return;
3742        }
3743        IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3744        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3745
3746            private Avatar parseAvatar(IqPacket packet) {
3747                Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3748                if (pubsub != null) {
3749                    Element items = pubsub.findChild("items");
3750                    if (items != null) {
3751                        return Avatar.parseMetadata(items);
3752                    }
3753                }
3754                return null;
3755            }
3756
3757            private boolean errorIsItemNotFound(IqPacket packet) {
3758                Element error = packet.findChild("error");
3759                return packet.getType() == IqPacket.TYPE.ERROR
3760                        && error != null
3761                        && error.hasChild("item-not-found");
3762            }
3763
3764            @Override
3765            public void onIqPacketReceived(Account account, IqPacket packet) {
3766                if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
3767                    Avatar serverAvatar = parseAvatar(packet);
3768                    if (serverAvatar == null && account.getAvatar() != null) {
3769                        Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
3770                        if (avatar != null) {
3771                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
3772                            publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
3773                        } else {
3774                            Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
3775                        }
3776                    }
3777                }
3778            }
3779        });
3780    }
3781
3782    public void fetchAvatar(Account account, Avatar avatar) {
3783        fetchAvatar(account, avatar, null);
3784    }
3785
3786    public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3787        final String KEY = generateFetchKey(account, avatar);
3788        synchronized (this.mInProgressAvatarFetches) {
3789            if (mInProgressAvatarFetches.add(KEY)) {
3790                switch (avatar.origin) {
3791                    case PEP:
3792                        this.mInProgressAvatarFetches.add(KEY);
3793                        fetchAvatarPep(account, avatar, callback);
3794                        break;
3795                    case VCARD:
3796                        this.mInProgressAvatarFetches.add(KEY);
3797                        fetchAvatarVcard(account, avatar, callback);
3798                        break;
3799                }
3800            } else if (avatar.origin == Avatar.Origin.PEP) {
3801                mOmittedPepAvatarFetches.add(KEY);
3802            } else {
3803                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": already fetching " + avatar.origin + " avatar for " + avatar.owner);
3804            }
3805        }
3806    }
3807
3808    private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3809        IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
3810        sendIqPacket(account, packet, (a, result) -> {
3811            synchronized (mInProgressAvatarFetches) {
3812                mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
3813            }
3814            final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
3815            if (result.getType() == IqPacket.TYPE.RESULT) {
3816                avatar.image = mIqParser.avatarData(result);
3817                if (avatar.image != null) {
3818                    if (getFileBackend().save(avatar)) {
3819                        if (a.getJid().asBareJid().equals(avatar.owner)) {
3820                            if (a.setAvatar(avatar.getFilename())) {
3821                                databaseBackend.updateAccount(a);
3822                            }
3823                            getAvatarService().clear(a);
3824                            updateConversationUi();
3825                            updateAccountUi();
3826                        } else {
3827                            final Contact contact = a.getRoster().getContact(avatar.owner);
3828                            contact.setAvatar(avatar);
3829                            syncRoster(account);
3830                            getAvatarService().clear(contact);
3831                            updateConversationUi();
3832                            updateRosterUi();
3833                        }
3834                        if (callback != null) {
3835                            callback.success(avatar);
3836                        }
3837                        Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": successfully fetched pep avatar for " + avatar.owner);
3838                        return;
3839                    }
3840                } else {
3841
3842                    Log.d(Config.LOGTAG, ERROR + "(parsing error)");
3843                }
3844            } else {
3845                Element error = result.findChild("error");
3846                if (error == null) {
3847                    Log.d(Config.LOGTAG, ERROR + "(server error)");
3848                } else {
3849                    Log.d(Config.LOGTAG, ERROR + error.toString());
3850                }
3851            }
3852            if (callback != null) {
3853                callback.error(0, null);
3854            }
3855
3856        });
3857    }
3858
3859    private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3860        IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
3861        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3862            @Override
3863            public void onIqPacketReceived(Account account, IqPacket packet) {
3864                final boolean previouslyOmittedPepFetch;
3865                synchronized (mInProgressAvatarFetches) {
3866                    final String KEY = generateFetchKey(account, avatar);
3867                    mInProgressAvatarFetches.remove(KEY);
3868                    previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
3869                }
3870                if (packet.getType() == IqPacket.TYPE.RESULT) {
3871                    Element vCard = packet.findChild("vCard", "vcard-temp");
3872                    Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
3873                    String image = photo != null ? photo.findChildContent("BINVAL") : null;
3874                    if (image != null) {
3875                        avatar.image = image;
3876                        if (getFileBackend().save(avatar)) {
3877                            Log.d(Config.LOGTAG, account.getJid().asBareJid()
3878                                    + ": successfully fetched vCard avatar for " + avatar.owner + " omittedPep=" + previouslyOmittedPepFetch);
3879                            if (avatar.owner.isBareJid()) {
3880                                if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
3881                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
3882                                    account.setAvatar(avatar.getFilename());
3883                                    databaseBackend.updateAccount(account);
3884                                    getAvatarService().clear(account);
3885                                    updateAccountUi();
3886                                } else {
3887                                    final Contact contact = account.getRoster().getContact(avatar.owner);
3888                                    contact.setAvatar(avatar, previouslyOmittedPepFetch);
3889                                    syncRoster(account);
3890                                    getAvatarService().clear(contact);
3891                                    updateRosterUi();
3892                                }
3893                                updateConversationUi();
3894                            } else {
3895                                Conversation conversation = find(account, avatar.owner.asBareJid());
3896                                if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
3897                                    MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
3898                                    if (user != null) {
3899                                        if (user.setAvatar(avatar)) {
3900                                            getAvatarService().clear(user);
3901                                            updateConversationUi();
3902                                            updateMucRosterUi();
3903                                        }
3904                                        if (user.getRealJid() != null) {
3905                                            Contact contact = account.getRoster().getContact(user.getRealJid());
3906                                            contact.setAvatar(avatar);
3907                                            syncRoster(account);
3908                                            getAvatarService().clear(contact);
3909                                            updateRosterUi();
3910                                        }
3911                                    }
3912                                }
3913                            }
3914                        }
3915                    }
3916                }
3917            }
3918        });
3919    }
3920
3921    public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
3922        IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3923        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3924
3925            @Override
3926            public void onIqPacketReceived(Account account, IqPacket packet) {
3927                if (packet.getType() == IqPacket.TYPE.RESULT) {
3928                    Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3929                    if (pubsub != null) {
3930                        Element items = pubsub.findChild("items");
3931                        if (items != null) {
3932                            Avatar avatar = Avatar.parseMetadata(items);
3933                            if (avatar != null) {
3934                                avatar.owner = account.getJid().asBareJid();
3935                                if (fileBackend.isAvatarCached(avatar)) {
3936                                    if (account.setAvatar(avatar.getFilename())) {
3937                                        databaseBackend.updateAccount(account);
3938                                    }
3939                                    getAvatarService().clear(account);
3940                                    callback.success(avatar);
3941                                } else {
3942                                    fetchAvatarPep(account, avatar, callback);
3943                                }
3944                                return;
3945                            }
3946                        }
3947                    }
3948                }
3949                callback.error(0, null);
3950            }
3951        });
3952    }
3953
3954    public void notifyAccountAvatarHasChanged(final Account account) {
3955        final XmppConnection connection = account.getXmppConnection();
3956        if (connection != null && connection.getFeatures().bookmarksConversion()) {
3957            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar changed. resending presence to online group chats");
3958            for (Conversation conversation : conversations) {
3959                if (conversation.getAccount() == account && conversation.getMode() == Conversational.MODE_MULTI) {
3960                    final MucOptions mucOptions = conversation.getMucOptions();
3961                    if (mucOptions.online()) {
3962                        PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous());
3963                        packet.setTo(mucOptions.getSelf().getFullJid());
3964                        connection.sendPresencePacket(packet);
3965                    }
3966                }
3967            }
3968        }
3969    }
3970
3971    public void deleteContactOnServer(Contact contact) {
3972        contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
3973        contact.resetOption(Contact.Options.DIRTY_PUSH);
3974        contact.setOption(Contact.Options.DIRTY_DELETE);
3975        Account account = contact.getAccount();
3976        if (account.getStatus() == Account.State.ONLINE) {
3977            IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3978            Element item = iq.query(Namespace.ROSTER).addChild("item");
3979            item.setAttribute("jid", contact.getJid());
3980            item.setAttribute("subscription", "remove");
3981            account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3982        }
3983    }
3984
3985    public void updateConversation(final Conversation conversation) {
3986        mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
3987    }
3988
3989    private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
3990        synchronized (account) {
3991            XmppConnection connection = account.getXmppConnection();
3992            if (connection == null) {
3993                connection = createConnection(account);
3994                account.setXmppConnection(connection);
3995            }
3996            boolean hasInternet = hasInternetConnection();
3997            if (account.isEnabled() && hasInternet) {
3998                if (!force) {
3999                    disconnect(account, false);
4000                }
4001                Thread thread = new Thread(connection);
4002                connection.setInteractive(interactive);
4003                connection.prepareNewConnection();
4004                connection.interrupt();
4005                thread.start();
4006                scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
4007            } else {
4008                disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
4009                account.getRoster().clearPresences();
4010                connection.resetEverything();
4011                final AxolotlService axolotlService = account.getAxolotlService();
4012                if (axolotlService != null) {
4013                    axolotlService.resetBrokenness();
4014                }
4015                if (!hasInternet) {
4016                    account.setStatus(Account.State.NO_INTERNET);
4017                }
4018            }
4019        }
4020    }
4021
4022    public void reconnectAccountInBackground(final Account account) {
4023        new Thread(() -> reconnectAccount(account, false, true)).start();
4024    }
4025
4026    public void invite(final Conversation conversation, final Jid contact) {
4027        Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
4028        final MucOptions.User user = conversation.getMucOptions().findUserByRealJid(contact.asBareJid());
4029        if (user == null || user.getAffiliation() == MucOptions.Affiliation.OUTCAST) {
4030            changeAffiliationInConference(conversation, contact, MucOptions.Affiliation.NONE, null);
4031        }
4032        final MessagePacket packet = mMessageGenerator.invite(conversation, contact);
4033        sendMessagePacket(conversation.getAccount(), packet);
4034    }
4035
4036    public void directInvite(Conversation conversation, Jid jid) {
4037        MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
4038        sendMessagePacket(conversation.getAccount(), packet);
4039    }
4040
4041    public void resetSendingToWaiting(Account account) {
4042        for (Conversation conversation : getConversations()) {
4043            if (conversation.getAccount() == account) {
4044                conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
4045            }
4046        }
4047    }
4048
4049    public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
4050        return markMessage(account, recipient, uuid, status, null);
4051    }
4052
4053    public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
4054        if (uuid == null) {
4055            return null;
4056        }
4057        for (Conversation conversation : getConversations()) {
4058            if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
4059                final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
4060                if (message != null) {
4061                    markMessage(message, status, errorMessage);
4062                }
4063                return message;
4064            }
4065        }
4066        return null;
4067    }
4068
4069    public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId) {
4070        return markMessage(conversation, uuid, status, serverMessageId, null);
4071    }
4072
4073    public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId, final LocalizedContent body) {
4074        if (uuid == null) {
4075            return false;
4076        } else {
4077            final Message message = conversation.findSentMessageWithUuid(uuid);
4078            if (message != null) {
4079                if (message.getServerMsgId() == null) {
4080                    message.setServerMsgId(serverMessageId);
4081                }
4082                if (message.getEncryption() == Message.ENCRYPTION_NONE
4083                        && message.isTypeText()
4084                        && isBodyModified(message, body)) {
4085                    message.setBody(body.content);
4086                    if (body.count > 1) {
4087                        message.setBodyLanguage(body.language);
4088                    }
4089                    markMessage(message, status, null, true);
4090                } else {
4091                    markMessage(message, status);
4092                }
4093                return true;
4094            } else {
4095                return false;
4096            }
4097        }
4098    }
4099
4100    private static boolean isBodyModified(final Message message, final LocalizedContent body) {
4101        if (body == null || body.content == null) {
4102            return false;
4103        }
4104        return !body.content.equals(message.getBody());
4105    }
4106
4107    public void markMessage(Message message, int status) {
4108        markMessage(message, status, null);
4109    }
4110
4111
4112    public void markMessage(final Message message, final int status, final String errorMessage) {
4113        markMessage(message, status, errorMessage, false);
4114    }
4115
4116    public void markMessage(final Message message, final int status, final String errorMessage, final boolean includeBody) {
4117        final int oldStatus = message.getStatus();
4118        if (status == Message.STATUS_SEND_FAILED && (oldStatus == Message.STATUS_SEND_RECEIVED || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
4119            return;
4120        }
4121        if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
4122            return;
4123        }
4124        message.setErrorMessage(errorMessage);
4125        message.setStatus(status);
4126        databaseBackend.updateMessage(message, includeBody);
4127        updateConversationUi();
4128        if (oldStatus != status && status == Message.STATUS_SEND_FAILED) {
4129            mNotificationService.pushFailedDelivery(message);
4130        }
4131    }
4132
4133    private SharedPreferences getPreferences() {
4134        return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
4135    }
4136
4137    public long getAutomaticMessageDeletionDate() {
4138        final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
4139        return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
4140    }
4141
4142    public long getLongPreference(String name, @IntegerRes int res) {
4143        long defaultValue = getResources().getInteger(res);
4144        try {
4145            return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
4146        } catch (NumberFormatException e) {
4147            return defaultValue;
4148        }
4149    }
4150
4151    public boolean getBooleanPreference(String name, @BoolRes int res) {
4152        return getPreferences().getBoolean(name, getResources().getBoolean(res));
4153    }
4154
4155    public boolean confirmMessages() {
4156        return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
4157    }
4158
4159    public boolean allowMessageCorrection() {
4160        return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
4161    }
4162
4163    public boolean sendChatStates() {
4164        return getBooleanPreference("chat_states", R.bool.chat_states);
4165    }
4166
4167    private boolean synchronizeWithBookmarks() {
4168        return getBooleanPreference("autojoin", R.bool.autojoin);
4169    }
4170
4171    public boolean useTorToConnect() {
4172        return getBooleanPreference("use_tor", R.bool.use_tor);
4173    }
4174
4175    public boolean showExtendedConnectionOptions() {
4176        return getBooleanPreference("show_connection_options", R.bool.show_connection_options);
4177    }
4178
4179    public boolean broadcastLastActivity() {
4180        return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
4181    }
4182
4183    public int unreadCount() {
4184        int count = 0;
4185        for (Conversation conversation : getConversations()) {
4186            count += conversation.unreadCount();
4187        }
4188        return count;
4189    }
4190
4191
4192    private <T> List<T> threadSafeList(Set<T> set) {
4193        synchronized (LISTENER_LOCK) {
4194            return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
4195        }
4196    }
4197
4198    public void showErrorToastInUi(int resId) {
4199        for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
4200            listener.onShowErrorToast(resId);
4201        }
4202    }
4203
4204    public void updateConversationUi() {
4205        for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
4206            listener.onConversationUpdate();
4207        }
4208    }
4209
4210    public void notifyJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state) {
4211        for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4212            listener.onJingleRtpConnectionUpdate(account, with, sessionId, state);
4213        }
4214    }
4215
4216    public void notifyJingleRtpConnectionUpdate(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
4217        for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4218            listener.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
4219        }
4220    }
4221
4222    public void updateAccountUi() {
4223        for (final OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
4224            listener.onAccountUpdate();
4225        }
4226    }
4227
4228    public void updateRosterUi() {
4229        for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
4230            listener.onRosterUpdate();
4231        }
4232    }
4233
4234    public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
4235        if (mOnCaptchaRequested.size() > 0) {
4236            DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
4237            Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
4238                    (int) (captcha.getHeight() * metrics.scaledDensity), false);
4239            for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
4240                listener.onCaptchaRequested(account, id, data, scaled);
4241            }
4242            return true;
4243        }
4244        return false;
4245    }
4246
4247    public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
4248        for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
4249            listener.OnUpdateBlocklist(status);
4250        }
4251    }
4252
4253    public void updateMucRosterUi() {
4254        for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
4255            listener.onMucRosterUpdate();
4256        }
4257    }
4258
4259    public void keyStatusUpdated(AxolotlService.FetchStatus report) {
4260        for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
4261            listener.onKeyStatusUpdated(report);
4262        }
4263    }
4264
4265    public Account findAccountByJid(final Jid jid) {
4266        for (final Account account : this.accounts) {
4267            if (account.getJid().asBareJid().equals(jid.asBareJid())) {
4268                return account;
4269            }
4270        }
4271        return null;
4272    }
4273
4274    public Account findAccountByUuid(final String uuid) {
4275        for (Account account : this.accounts) {
4276            if (account.getUuid().equals(uuid)) {
4277                return account;
4278            }
4279        }
4280        return null;
4281    }
4282
4283    public Conversation findConversationByUuid(String uuid) {
4284        for (Conversation conversation : getConversations()) {
4285            if (conversation.getUuid().equals(uuid)) {
4286                return conversation;
4287            }
4288        }
4289        return null;
4290    }
4291
4292    public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
4293        List<Conversation> findings = new ArrayList<>();
4294        for (Conversation c : getConversations()) {
4295            if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
4296                findings.add(c);
4297            }
4298        }
4299        return findings.size() == 1 ? findings.get(0) : null;
4300    }
4301
4302    public boolean markRead(final Conversation conversation, boolean dismiss) {
4303        return markRead(conversation, null, dismiss).size() > 0;
4304    }
4305
4306    public void markRead(final Conversation conversation) {
4307        markRead(conversation, null, true);
4308    }
4309
4310    public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
4311        if (dismiss) {
4312            mNotificationService.clear(conversation);
4313        }
4314        final List<Message> readMessages = conversation.markRead(upToUuid);
4315        if (readMessages.size() > 0) {
4316            Runnable runnable = () -> {
4317                for (Message message : readMessages) {
4318                    databaseBackend.updateMessage(message, false);
4319                }
4320            };
4321            mDatabaseWriterExecutor.execute(runnable);
4322            updateConversationUi();
4323            updateUnreadCountBadge();
4324            return readMessages;
4325        } else {
4326            return readMessages;
4327        }
4328    }
4329
4330    public synchronized void updateUnreadCountBadge() {
4331        int count = unreadCount();
4332        if (unreadCount != count) {
4333            Log.d(Config.LOGTAG, "update unread count to " + count);
4334            if (count > 0) {
4335                ShortcutBadger.applyCount(getApplicationContext(), count);
4336            } else {
4337                ShortcutBadger.removeCount(getApplicationContext());
4338            }
4339            unreadCount = count;
4340        }
4341    }
4342
4343    public void sendReadMarker(final Conversation conversation, String upToUuid) {
4344        final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
4345        final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
4346        if (readMessages.size() > 0) {
4347            updateConversationUi();
4348        }
4349        final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
4350        if (confirmMessages()
4351                && markable != null
4352                && (markable.trusted() || isPrivateAndNonAnonymousMuc)
4353                && markable.getRemoteMsgId() != null) {
4354            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
4355            final Account account = conversation.getAccount();
4356            final MessagePacket packet = mMessageGenerator.confirm(markable);
4357            this.sendMessagePacket(account, packet);
4358        }
4359    }
4360
4361    public SecureRandom getRNG() {
4362        return this.mRandom;
4363    }
4364
4365    public MemorizingTrustManager getMemorizingTrustManager() {
4366        return this.mMemorizingTrustManager;
4367    }
4368
4369    public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
4370        this.mMemorizingTrustManager = trustManager;
4371    }
4372
4373    public void updateMemorizingTrustmanager() {
4374        final MemorizingTrustManager tm;
4375        final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
4376        if (dontTrustSystemCAs) {
4377            tm = new MemorizingTrustManager(getApplicationContext(), null);
4378        } else {
4379            tm = new MemorizingTrustManager(getApplicationContext());
4380        }
4381        setMemorizingTrustManager(tm);
4382    }
4383
4384    public LruCache<String, Bitmap> getBitmapCache() {
4385        return this.mBitmapCache;
4386    }
4387
4388    public LruCache<String, Drawable> getDrawableCache() {
4389        return this.mDrawableCache;
4390    }
4391
4392    public Collection<String> getKnownHosts() {
4393        final Set<String> hosts = new HashSet<>();
4394        for (final Account account : getAccounts()) {
4395            hosts.add(account.getServer());
4396            for (final Contact contact : account.getRoster().getContacts()) {
4397                if (contact.showInRoster()) {
4398                    final String server = contact.getServer();
4399                    if (server != null) {
4400                        hosts.add(server);
4401                    }
4402                }
4403            }
4404        }
4405        if (Config.QUICKSY_DOMAIN != null) {
4406            hosts.remove(Config.QUICKSY_DOMAIN.toEscapedString()); //we only want to show this when we type a e164 number
4407        }
4408        if (Config.DOMAIN_LOCK != null) {
4409            hosts.add(Config.DOMAIN_LOCK);
4410        }
4411        if (Config.MAGIC_CREATE_DOMAIN != null) {
4412            hosts.add(Config.MAGIC_CREATE_DOMAIN);
4413        }
4414        return hosts;
4415    }
4416
4417    public Collection<String> getKnownConferenceHosts() {
4418        final Set<String> mucServers = new HashSet<>();
4419        for (final Account account : accounts) {
4420            if (account.getXmppConnection() != null) {
4421                mucServers.addAll(account.getXmppConnection().getMucServers());
4422                for (Bookmark bookmark : account.getBookmarks()) {
4423                    final Jid jid = bookmark.getJid();
4424                    final String s = jid == null ? null : jid.getDomain().toEscapedString();
4425                    if (s != null) {
4426                        mucServers.add(s);
4427                    }
4428                }
4429            }
4430        }
4431        return mucServers;
4432    }
4433
4434    public void sendMessagePacket(Account account, MessagePacket packet) {
4435        final XmppConnection connection = account.getXmppConnection();
4436        if (connection != null) {
4437            connection.sendMessagePacket(packet);
4438        }
4439    }
4440
4441    public void sendPresencePacket(Account account, PresencePacket packet) {
4442        XmppConnection connection = account.getXmppConnection();
4443        if (connection != null) {
4444            connection.sendPresencePacket(packet);
4445        }
4446    }
4447
4448    public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
4449        final XmppConnection connection = account.getXmppConnection();
4450        if (connection != null) {
4451            IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
4452            connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
4453        }
4454    }
4455
4456    public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
4457        final XmppConnection connection = account.getXmppConnection();
4458        if (connection != null) {
4459            connection.sendIqPacket(packet, callback);
4460        } else if (callback != null) {
4461            callback.onIqPacketReceived(account, new IqPacket(IqPacket.TYPE.TIMEOUT));
4462        }
4463    }
4464
4465    public void sendPresence(final Account account) {
4466        sendPresence(account, checkListeners() && broadcastLastActivity());
4467    }
4468
4469    private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
4470        final Presence.Status status;
4471        if (manuallyChangePresence()) {
4472            status = account.getPresenceStatus();
4473        } else {
4474            status = getTargetPresence();
4475        }
4476        final PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
4477        if (mLastActivity > 0 && includeIdleTimestamp) {
4478            long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
4479            packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
4480        }
4481        sendPresencePacket(account, packet);
4482    }
4483
4484    private void deactivateGracePeriod() {
4485        for (Account account : getAccounts()) {
4486            account.deactivateGracePeriod();
4487        }
4488    }
4489
4490    public void refreshAllPresences() {
4491        boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
4492        for (Account account : getAccounts()) {
4493            if (account.isEnabled()) {
4494                sendPresence(account, includeIdleTimestamp);
4495            }
4496        }
4497    }
4498
4499    private void refreshAllFcmTokens() {
4500        for (Account account : getAccounts()) {
4501            if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
4502                mPushManagementService.registerPushTokenOnServer(account);
4503                //TODO renew mucs
4504            }
4505        }
4506    }
4507
4508    private void sendOfflinePresence(final Account account) {
4509        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
4510        sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
4511    }
4512
4513    public MessageGenerator getMessageGenerator() {
4514        return this.mMessageGenerator;
4515    }
4516
4517    public PresenceGenerator getPresenceGenerator() {
4518        return this.mPresenceGenerator;
4519    }
4520
4521    public IqGenerator getIqGenerator() {
4522        return this.mIqGenerator;
4523    }
4524
4525    public IqParser getIqParser() {
4526        return this.mIqParser;
4527    }
4528
4529    public JingleConnectionManager getJingleConnectionManager() {
4530        return this.mJingleConnectionManager;
4531    }
4532
4533    public MessageArchiveService getMessageArchiveService() {
4534        return this.mMessageArchiveService;
4535    }
4536
4537    public QuickConversationsService getQuickConversationsService() {
4538        return this.mQuickConversationsService;
4539    }
4540
4541    public List<Contact> findContacts(Jid jid, String accountJid) {
4542        ArrayList<Contact> contacts = new ArrayList<>();
4543        for (Account account : getAccounts()) {
4544            if ((account.isEnabled() || accountJid != null)
4545                    && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
4546                Contact contact = account.getRoster().getContactFromContactList(jid);
4547                if (contact != null) {
4548                    contacts.add(contact);
4549                }
4550            }
4551        }
4552        return contacts;
4553    }
4554
4555    public Conversation findFirstMuc(Jid jid) {
4556        for (Conversation conversation : getConversations()) {
4557            if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
4558                return conversation;
4559            }
4560        }
4561        return null;
4562    }
4563
4564    public NotificationService getNotificationService() {
4565        return this.mNotificationService;
4566    }
4567
4568    public HttpConnectionManager getHttpConnectionManager() {
4569        return this.mHttpConnectionManager;
4570    }
4571
4572    public void resendFailedMessages(final Message message) {
4573        final Collection<Message> messages = new ArrayList<>();
4574        Message current = message;
4575        while (current.getStatus() == Message.STATUS_SEND_FAILED) {
4576            messages.add(current);
4577            if (current.mergeable(current.next())) {
4578                current = current.next();
4579            } else {
4580                break;
4581            }
4582        }
4583        for (final Message msg : messages) {
4584            msg.setTime(System.currentTimeMillis());
4585            markMessage(msg, Message.STATUS_WAITING);
4586            this.resendMessage(msg, false);
4587        }
4588        if (message.getConversation() instanceof Conversation) {
4589            ((Conversation) message.getConversation()).sort();
4590        }
4591        updateConversationUi();
4592    }
4593
4594    public void clearConversationHistory(final Conversation conversation) {
4595        final long clearDate;
4596        final String reference;
4597        if (conversation.countMessages() > 0) {
4598            Message latestMessage = conversation.getLatestMessage();
4599            clearDate = latestMessage.getTimeSent() + 1000;
4600            reference = latestMessage.getServerMsgId();
4601        } else {
4602            clearDate = System.currentTimeMillis();
4603            reference = null;
4604        }
4605        conversation.clearMessages();
4606        conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
4607        conversation.setLastClearHistory(clearDate, reference);
4608        Runnable runnable = () -> {
4609            databaseBackend.deleteMessagesInConversation(conversation);
4610            databaseBackend.updateConversation(conversation);
4611        };
4612        mDatabaseWriterExecutor.execute(runnable);
4613    }
4614
4615    public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
4616        if (blockable != null && blockable.getBlockedJid() != null) {
4617            final Jid jid = blockable.getBlockedJid();
4618            this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), (a, response) -> {
4619                if (response.getType() == IqPacket.TYPE.RESULT) {
4620                    a.getBlocklist().add(jid);
4621                    updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
4622                }
4623            });
4624            if (blockable.getBlockedJid().isFullJid()) {
4625                return false;
4626            } else if (removeBlockedConversations(blockable.getAccount(), jid)) {
4627                updateConversationUi();
4628                return true;
4629            } else {
4630                return false;
4631            }
4632        } else {
4633            return false;
4634        }
4635    }
4636
4637    public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
4638        boolean removed = false;
4639        synchronized (this.conversations) {
4640            boolean domainJid = blockedJid.getLocal() == null;
4641            for (Conversation conversation : this.conversations) {
4642                boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
4643                        || blockedJid.equals(conversation.getJid().asBareJid());
4644                if (conversation.getAccount() == account
4645                        && conversation.getMode() == Conversation.MODE_SINGLE
4646                        && jidMatches) {
4647                    this.conversations.remove(conversation);
4648                    markRead(conversation);
4649                    conversation.setStatus(Conversation.STATUS_ARCHIVED);
4650                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
4651                    updateConversation(conversation);
4652                    removed = true;
4653                }
4654            }
4655        }
4656        return removed;
4657    }
4658
4659    public void sendUnblockRequest(final Blockable blockable) {
4660        if (blockable != null && blockable.getJid() != null) {
4661            final Jid jid = blockable.getBlockedJid();
4662            this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
4663                @Override
4664                public void onIqPacketReceived(final Account account, final IqPacket packet) {
4665                    if (packet.getType() == IqPacket.TYPE.RESULT) {
4666                        account.getBlocklist().remove(jid);
4667                        updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
4668                    }
4669                }
4670            });
4671        }
4672    }
4673
4674    public void publishDisplayName(Account account) {
4675        String displayName = account.getDisplayName();
4676        final IqPacket request;
4677        if (TextUtils.isEmpty(displayName)) {
4678            request = mIqGenerator.deleteNode(Namespace.NICK);
4679        } else {
4680            request = mIqGenerator.publishNick(displayName);
4681        }
4682        mAvatarService.clear(account);
4683        sendIqPacket(account, request, (account1, packet) -> {
4684            if (packet.getType() == IqPacket.TYPE.ERROR) {
4685                Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": unable to modify nick name " + packet.toString());
4686            }
4687        });
4688    }
4689
4690    public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
4691        ServiceDiscoveryResult result = discoCache.get(key);
4692        if (result != null) {
4693            return result;
4694        } else {
4695            if (key.first == null || key.second == null) return null;
4696            result = databaseBackend.findDiscoveryResult(key.first, key.second);
4697            if (result != null) {
4698                discoCache.put(key, result);
4699            }
4700            return result;
4701        }
4702    }
4703
4704    public void fetchFromGateway(Account account, final Jid jid, final String input, final OnGatewayResult callback) {
4705        IqPacket request = new IqPacket(input == null ? IqPacket.TYPE.GET : IqPacket.TYPE.SET);
4706        request.setTo(jid);
4707        Element query = request.query("jabber:iq:gateway");
4708        if (input != null) {
4709            Element prompt = query.addChild("prompt");
4710            prompt.setContent(input);
4711        }
4712        sendIqPacket(account, request, (Account acct, IqPacket packet) -> {
4713            if (packet.getType() == IqPacket.TYPE.RESULT) {
4714                callback.onGatewayResult(packet.query().findChildContent(input == null ? "prompt" : "jid"), null);
4715            } else {
4716                Element error = packet.findChild("error");
4717                callback.onGatewayResult(null, error == null ? null : error.findChildContent("text"));
4718            }
4719        });
4720    }
4721
4722    public void fetchCaps(Account account, final Jid jid, final Presence presence) {
4723        fetchCaps(account, jid, presence, null);
4724    }
4725
4726    public void fetchCaps(Account account, final Jid jid, final Presence presence, Runnable cb) {
4727        final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
4728        final ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
4729
4730        if (disco != null) {
4731            presence.setServiceDiscoveryResult(disco);
4732            final Contact contact = account.getRoster().getContact(jid);
4733            if (contact.refreshRtpCapability()) {
4734                syncRoster(account);
4735            }
4736            if (disco.hasIdentity("gateway", "pstn")) {
4737                contact.registerAsPhoneAccount(this);
4738                mQuickConversationsService.considerSyncBackground(false);
4739            }
4740        } else {
4741            final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4742            request.setTo(jid);
4743            final String node = presence.getNode();
4744            final String ver = presence.getVer();
4745            final Element query = request.query(Namespace.DISCO_INFO);
4746            if (node != null && ver != null) {
4747                query.setAttribute("node", node + "#" + ver);
4748            }
4749            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
4750            sendIqPacket(account, request, (a, response) -> {
4751                if (response.getType() == IqPacket.TYPE.RESULT) {
4752                    final ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
4753                    if (presence.getVer() == null || presence.getVer().equals(discoveryResult.getVer())) {
4754                        databaseBackend.insertDiscoveryResult(discoveryResult);
4755                        injectServiceDiscoveryResult(a.getRoster(), presence.getHash(), presence.getVer(), jid.getResource(), discoveryResult);
4756                        if (discoveryResult.hasIdentity("gateway", "pstn")) {
4757                            final Contact contact = account.getRoster().getContact(jid);
4758                            contact.registerAsPhoneAccount(this);
4759                            mQuickConversationsService.considerSyncBackground(false);
4760                        }
4761                        if (cb != null) cb.run();
4762                    } else {
4763                        Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
4764                    }
4765                } else {
4766                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to fetch caps from " + jid);
4767                }
4768            });
4769        }
4770    }
4771
4772    public void fetchCommands(Account account, final Jid jid, OnIqPacketReceived callback) {
4773        final IqPacket request = mIqGenerator.queryDiscoItems(jid, "http://jabber.org/protocol/commands");
4774        sendIqPacket(account, request, callback);
4775    }
4776
4777    private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, String resource, ServiceDiscoveryResult disco) {
4778        boolean rosterNeedsSync = false;
4779        for (final Contact contact : roster.getContacts()) {
4780            boolean serviceDiscoverySet = false;
4781            Presence onePresence = contact.getPresences().get(resource == null ? "" : resource);
4782            if (onePresence != null) {
4783                onePresence.setServiceDiscoveryResult(disco);
4784                serviceDiscoverySet = true;
4785            }
4786            if (hash != null && ver != null) {
4787                for (final Presence presence : contact.getPresences().getPresences()) {
4788                    if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
4789                        presence.setServiceDiscoveryResult(disco);
4790                        serviceDiscoverySet = true;
4791                    }
4792                }
4793            }
4794            if (serviceDiscoverySet) {
4795                rosterNeedsSync |= contact.refreshRtpCapability();
4796            }
4797        }
4798        if (rosterNeedsSync) {
4799            syncRoster(roster.getAccount());
4800        }
4801    }
4802
4803    public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
4804        final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
4805        IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4806        request.addChild("prefs", version.namespace);
4807        sendIqPacket(account, request, (account1, packet) -> {
4808            Element prefs = packet.findChild("prefs", version.namespace);
4809            if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
4810                callback.onPreferencesFetched(prefs);
4811            } else {
4812                callback.onPreferencesFetchFailed();
4813            }
4814        });
4815    }
4816
4817    public PushManagementService getPushManagementService() {
4818        return mPushManagementService;
4819    }
4820
4821    public void changeStatus(Account account, PresenceTemplate template, String signature) {
4822        if (!template.getStatusMessage().isEmpty()) {
4823            databaseBackend.insertPresenceTemplate(template);
4824        }
4825        account.setPgpSignature(signature);
4826        account.setPresenceStatus(template.getStatus());
4827        account.setPresenceStatusMessage(template.getStatusMessage());
4828        databaseBackend.updateAccount(account);
4829        sendPresence(account);
4830    }
4831
4832    public List<PresenceTemplate> getPresenceTemplates(Account account) {
4833        List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
4834        for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
4835            if (!templates.contains(template)) {
4836                templates.add(0, template);
4837            }
4838        }
4839        return templates;
4840    }
4841
4842    public void saveConversationAsBookmark(Conversation conversation, String name) {
4843        final Account account = conversation.getAccount();
4844        final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
4845        final String nick = conversation.getJid().getResource();
4846        if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
4847            bookmark.setNick(nick);
4848        }
4849        if (!TextUtils.isEmpty(name)) {
4850            bookmark.setBookmarkName(name);
4851        }
4852        bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
4853        createBookmark(account, bookmark);
4854        bookmark.setConversation(conversation);
4855    }
4856
4857    public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
4858        boolean performedVerification = false;
4859        final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
4860        for (XmppUri.Fingerprint fp : fingerprints) {
4861            if (fp.type == XmppUri.FingerprintType.OMEMO) {
4862                String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4863                FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4864                if (fingerprintStatus != null) {
4865                    if (!fingerprintStatus.isVerified()) {
4866                        performedVerification = true;
4867                        axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4868                    }
4869                } else {
4870                    axolotlService.preVerifyFingerprint(contact, fingerprint);
4871                }
4872            }
4873        }
4874        return performedVerification;
4875    }
4876
4877    public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
4878        final AxolotlService axolotlService = account.getAxolotlService();
4879        boolean verifiedSomething = false;
4880        for (XmppUri.Fingerprint fp : fingerprints) {
4881            if (fp.type == XmppUri.FingerprintType.OMEMO) {
4882                String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4883                Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
4884                FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4885                if (fingerprintStatus != null) {
4886                    if (!fingerprintStatus.isVerified()) {
4887                        axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4888                        verifiedSomething = true;
4889                    }
4890                } else {
4891                    axolotlService.preVerifyFingerprint(account, fingerprint);
4892                    verifiedSomething = true;
4893                }
4894            }
4895        }
4896        return verifiedSomething;
4897    }
4898
4899    public boolean blindTrustBeforeVerification() {
4900        return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
4901    }
4902
4903    public ShortcutService getShortcutService() {
4904        return mShortcutService;
4905    }
4906
4907    public void pushMamPreferences(Account account, Element prefs) {
4908        IqPacket set = new IqPacket(IqPacket.TYPE.SET);
4909        set.addChild(prefs);
4910        sendIqPacket(account, set, null);
4911    }
4912
4913    public void evictPreview(String uuid) {
4914        if (mBitmapCache.remove(uuid) != null) {
4915            Log.d(Config.LOGTAG, "deleted cached preview");
4916        }
4917    }
4918
4919    public interface OnMamPreferencesFetched {
4920        void onPreferencesFetched(Element prefs);
4921
4922        void onPreferencesFetchFailed();
4923    }
4924
4925    public interface OnAccountCreated {
4926        void onAccountCreated(Account account);
4927
4928        void informUser(int r);
4929    }
4930
4931    public interface OnMoreMessagesLoaded {
4932        void onMoreMessagesLoaded(int count, Conversation conversation);
4933
4934        void informUser(int r);
4935    }
4936
4937    public interface OnAccountPasswordChanged {
4938        void onPasswordChangeSucceeded();
4939
4940        void onPasswordChangeFailed();
4941    }
4942
4943    public interface OnRoomDestroy {
4944        void onRoomDestroySucceeded();
4945
4946        void onRoomDestroyFailed();
4947    }
4948
4949    public interface OnAffiliationChanged {
4950        void onAffiliationChangedSuccessful(Jid jid);
4951
4952        void onAffiliationChangeFailed(Jid jid, int resId);
4953    }
4954
4955    public interface OnConversationUpdate {
4956        void onConversationUpdate();
4957    }
4958
4959    public interface OnJingleRtpConnectionUpdate {
4960        void onJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state);
4961
4962        void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices);
4963    }
4964
4965    public interface OnAccountUpdate {
4966        void onAccountUpdate();
4967    }
4968
4969    public interface OnCaptchaRequested {
4970        void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
4971    }
4972
4973    public interface OnRosterUpdate {
4974        void onRosterUpdate();
4975    }
4976
4977    public interface OnMucRosterUpdate {
4978        void onMucRosterUpdate();
4979    }
4980
4981    public interface OnConferenceConfigurationFetched {
4982        void onConferenceConfigurationFetched(Conversation conversation);
4983
4984        void onFetchFailed(Conversation conversation, String errorCondition);
4985    }
4986
4987    public interface OnConferenceJoined {
4988        void onConferenceJoined(Conversation conversation);
4989    }
4990
4991    public interface OnConfigurationPushed {
4992        void onPushSucceeded();
4993
4994        void onPushFailed();
4995    }
4996
4997    public interface OnShowErrorToast {
4998        void onShowErrorToast(int resId);
4999    }
5000
5001    public class XmppConnectionBinder extends Binder {
5002        public XmppConnectionService getService() {
5003            return XmppConnectionService.this;
5004        }
5005    }
5006
5007    private class InternalEventReceiver extends BroadcastReceiver {
5008
5009        @Override
5010        public void onReceive(Context context, Intent intent) {
5011            onStartCommand(intent, 0, 0);
5012        }
5013    }
5014
5015    public static class OngoingCall {
5016        public final AbstractJingleConnection.Id id;
5017        public final Set<Media> media;
5018        public final boolean reconnecting;
5019
5020        public OngoingCall(AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
5021            this.id = id;
5022            this.media = media;
5023            this.reconnecting = reconnecting;
5024        }
5025
5026        @Override
5027        public boolean equals(Object o) {
5028            if (this == o) return true;
5029            if (o == null || getClass() != o.getClass()) return false;
5030            OngoingCall that = (OngoingCall) o;
5031            return reconnecting == that.reconnecting && Objects.equal(id, that.id) && Objects.equal(media, that.media);
5032        }
5033
5034        @Override
5035        public int hashCode() {
5036            return Objects.hashCode(id, media, reconnecting);
5037        }
5038    }
5039}