XmppConnectionService.java

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