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