XmppConnectionService.java

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