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