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