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