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