XmppConnectionService.java

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