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