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