XmppConnectionService.java

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