XmppConnectionService.java

   1package eu.siacs.conversations.services;
   2
   3import static eu.siacs.conversations.utils.Compatibility.s;
   4import static eu.siacs.conversations.utils.Random.SECURE_RANDOM;
   5
   6import android.Manifest;
   7import android.annotation.SuppressLint;
   8import android.annotation.TargetApi;
   9import android.app.AlarmManager;
  10import android.app.KeyguardManager;
  11import android.app.Notification;
  12import android.app.NotificationManager;
  13import android.app.PendingIntent;
  14import android.app.Service;
  15import android.content.BroadcastReceiver;
  16import android.content.ComponentName;
  17import android.content.Context;
  18import android.content.Intent;
  19import android.content.IntentFilter;
  20import android.content.SharedPreferences;
  21import android.content.pm.PackageManager;
  22import android.database.ContentObserver;
  23import android.graphics.Bitmap;
  24import android.graphics.drawable.BitmapDrawable;
  25import android.graphics.drawable.Drawable;
  26import android.media.AudioManager;
  27import android.net.ConnectivityManager;
  28import android.net.Network;
  29import android.net.NetworkCapabilities;
  30import android.net.NetworkInfo;
  31import android.net.Uri;
  32import android.os.Binder;
  33import android.os.Build;
  34import android.os.Bundle;
  35import android.os.Environment;
  36import android.os.IBinder;
  37import android.os.PowerManager;
  38import android.os.PowerManager.WakeLock;
  39import android.os.SystemClock;
  40import android.preference.PreferenceManager;
  41import android.provider.ContactsContract;
  42import android.security.KeyChain;
  43import android.telephony.PhoneStateListener;
  44import android.telephony.TelephonyManager;
  45import android.text.TextUtils;
  46import android.util.DisplayMetrics;
  47import android.util.Log;
  48import android.util.LruCache;
  49import android.util.Pair;
  50
  51import androidx.annotation.BoolRes;
  52import androidx.annotation.IntegerRes;
  53import androidx.annotation.NonNull;
  54import androidx.core.app.RemoteInput;
  55import androidx.core.content.ContextCompat;
  56
  57import com.google.common.base.Objects;
  58import com.google.common.base.Strings;
  59
  60import org.conscrypt.Conscrypt;
  61import org.openintents.openpgp.IOpenPgpService2;
  62import org.openintents.openpgp.util.OpenPgpApi;
  63import org.openintents.openpgp.util.OpenPgpServiceConnection;
  64
  65import java.io.File;
  66import java.security.SecureRandom;
  67import java.security.Security;
  68import java.security.cert.CertificateException;
  69import java.security.cert.X509Certificate;
  70import java.util.ArrayList;
  71import java.util.Arrays;
  72import java.util.Collection;
  73import java.util.Collections;
  74import java.util.HashSet;
  75import java.util.Hashtable;
  76import java.util.Iterator;
  77import java.util.List;
  78import java.util.ListIterator;
  79import java.util.Map;
  80import java.util.Set;
  81import java.util.WeakHashMap;
  82import java.util.concurrent.CopyOnWriteArrayList;
  83import java.util.concurrent.CountDownLatch;
  84import java.util.concurrent.Executor;
  85import java.util.concurrent.Executors;
  86import java.util.concurrent.atomic.AtomicBoolean;
  87import java.util.concurrent.atomic.AtomicLong;
  88import java.util.concurrent.atomic.AtomicReference;
  89
  90import io.ipfs.cid.Cid;
  91
  92import eu.siacs.conversations.Config;
  93import eu.siacs.conversations.R;
  94import eu.siacs.conversations.android.JabberIdContact;
  95import eu.siacs.conversations.crypto.OmemoSetting;
  96import eu.siacs.conversations.crypto.PgpDecryptionService;
  97import eu.siacs.conversations.crypto.PgpEngine;
  98import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  99import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
 100import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
 101import eu.siacs.conversations.entities.Account;
 102import eu.siacs.conversations.entities.Blockable;
 103import eu.siacs.conversations.entities.Bookmark;
 104import eu.siacs.conversations.entities.Contact;
 105import eu.siacs.conversations.entities.Conversation;
 106import eu.siacs.conversations.entities.Conversational;
 107import eu.siacs.conversations.entities.DownloadableFile;
 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.ui.ChooseAccountForProfilePictureActivity;
 127import eu.siacs.conversations.ui.RtpSessionActivity;
 128import eu.siacs.conversations.ui.SettingsActivity;
 129import eu.siacs.conversations.ui.UiCallback;
 130import eu.siacs.conversations.ui.interfaces.OnAvatarPublication;
 131import eu.siacs.conversations.ui.interfaces.OnMediaLoaded;
 132import eu.siacs.conversations.ui.interfaces.OnSearchResultsAvailable;
 133import eu.siacs.conversations.utils.Compatibility;
 134import eu.siacs.conversations.utils.ConversationsFileObserver;
 135import eu.siacs.conversations.utils.CryptoHelper;
 136import eu.siacs.conversations.utils.EasyOnboardingInvite;
 137import eu.siacs.conversations.utils.ExceptionHelper;
 138import eu.siacs.conversations.utils.MimeUtils;
 139import eu.siacs.conversations.utils.PhoneHelper;
 140import eu.siacs.conversations.utils.QuickLoader;
 141import eu.siacs.conversations.utils.ReplacingSerialSingleThreadExecutor;
 142import eu.siacs.conversations.utils.ReplacingTaskManager;
 143import eu.siacs.conversations.utils.Resolver;
 144import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
 145import eu.siacs.conversations.utils.StringUtils;
 146import eu.siacs.conversations.utils.TorServiceUtils;
 147import eu.siacs.conversations.utils.ThemeHelper;
 148import eu.siacs.conversations.utils.WakeLockHelper;
 149import eu.siacs.conversations.utils.XmppUri;
 150import eu.siacs.conversations.xml.Element;
 151import eu.siacs.conversations.xml.LocalizedContent;
 152import eu.siacs.conversations.xml.Namespace;
 153import eu.siacs.conversations.xmpp.Jid;
 154import eu.siacs.conversations.xmpp.OnBindListener;
 155import eu.siacs.conversations.xmpp.OnContactStatusChanged;
 156import eu.siacs.conversations.xmpp.OnGatewayResult;
 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.Patches;
 165import eu.siacs.conversations.xmpp.XmppConnection;
 166import eu.siacs.conversations.xmpp.chatstate.ChatState;
 167import eu.siacs.conversations.xmpp.forms.Data;
 168import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
 169import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
 170import eu.siacs.conversations.xmpp.jingle.JingleRtpConnection;
 171import eu.siacs.conversations.xmpp.jingle.Media;
 172import eu.siacs.conversations.xmpp.jingle.RtpEndUserState;
 173import eu.siacs.conversations.xmpp.mam.MamReference;
 174import eu.siacs.conversations.xmpp.pep.Avatar;
 175import eu.siacs.conversations.xmpp.pep.PublishOptions;
 176import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 177import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 178import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
 179import me.leolin.shortcutbadger.ShortcutBadger;
 180
 181public class XmppConnectionService extends Service {
 182
 183    public static final String ACTION_REPLY_TO_CONVERSATION = "reply_to_conversations";
 184    public static final String ACTION_MARK_AS_READ = "mark_as_read";
 185    public static final String ACTION_SNOOZE = "snooze";
 186    public static final String ACTION_CLEAR_MESSAGE_NOTIFICATION = "clear_message_notification";
 187    public static final String ACTION_CLEAR_MISSED_CALL_NOTIFICATION = "clear_missed_call_notification";
 188    public static final String ACTION_DISMISS_ERROR_NOTIFICATIONS = "dismiss_error";
 189    public static final String ACTION_TRY_AGAIN = "try_again";
 190    public static final String ACTION_IDLE_PING = "idle_ping";
 191    public static final String ACTION_FCM_TOKEN_REFRESH = "fcm_token_refresh";
 192    public static final String ACTION_FCM_MESSAGE_RECEIVED = "fcm_message_received";
 193    public static final String ACTION_DISMISS_CALL = "dismiss_call";
 194    public static final String ACTION_END_CALL = "end_call";
 195    public static final String ACTION_PROVISION_ACCOUNT = "provision_account";
 196    private static final String ACTION_POST_CONNECTIVITY_CHANGE = "eu.siacs.conversations.POST_CONNECTIVITY_CHANGE";
 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 ChannelDiscoveryService mChannelDiscoveryService = new ChannelDiscoveryService(this);
 230    private final ShortcutService mShortcutService = new ShortcutService(this);
 231    private final AtomicBoolean mInitialAddressbookSyncCompleted = new AtomicBoolean(false);
 232    private final AtomicBoolean mForceForegroundService = new AtomicBoolean(false);
 233    private final AtomicBoolean mForceDuringOnCreate = new AtomicBoolean(false);
 234    private final AtomicReference<OngoingCall> ongoingCall = new AtomicReference<>();
 235    private final OnMessagePacketReceived mMessageParser = new MessageParser(this);
 236    private final OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
 237    private final IqParser mIqParser = new IqParser(this);
 238    private final MessageGenerator mMessageGenerator = new MessageGenerator(this);
 239    public OnContactStatusChanged onContactStatusChanged = (contact, online) -> {
 240        Conversation conversation = find(getConversations(), contact);
 241        if (conversation != null) {
 242            if (online) {
 243                if (contact.getPresences().size() == 1) {
 244                    sendUnsentMessages(conversation);
 245                }
 246            }
 247        }
 248    };
 249    private final PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
 250    private List<Account> accounts;
 251    private final JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(this);
 252    private final HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(this);
 253    private final AvatarService mAvatarService = new AvatarService(this);
 254    private final MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
 255    private final PushManagementService mPushManagementService = new PushManagementService(this);
 256    private final QuickConversationsService mQuickConversationsService = new QuickConversationsService(this);
 257    private final ConversationsFileObserver fileObserver = new ConversationsFileObserver(
 258            Environment.getExternalStorageDirectory().getAbsolutePath()
 259    ) {
 260        @Override
 261        public void onEvent(final int event, final File file) {
 262            markFileDeleted(file);
 263        }
 264    };
 265    private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
 266
 267        @Override
 268        public boolean onMessageAcknowledged(final Account account, final Jid to, final String id) {
 269            if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
 270                final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
 271                mJingleConnectionManager.updateProposedSessionDiscovered(
 272                        account,
 273                        to,
 274                        sessionId,
 275                        JingleConnectionManager.DeviceDiscoveryState.SEARCHING_ACKNOWLEDGED
 276                );
 277            }
 278
 279
 280            final Jid bare = to.asBareJid();
 281
 282            for (final Conversation conversation : getConversations()) {
 283                if (conversation.getAccount() == account && conversation.getJid().asBareJid().equals(bare)) {
 284                    final Message message = conversation.findUnsentMessageWithUuid(id);
 285                    if (message != null) {
 286                        message.setStatus(Message.STATUS_SEND);
 287                        message.setErrorMessage(null);
 288                        databaseBackend.updateMessage(message, false);
 289                        return true;
 290                    }
 291                }
 292            }
 293            return false;
 294        }
 295    };
 296    private final AtomicBoolean isPhoneInCall = new AtomicBoolean(false);
 297    private final AtomicBoolean diallerIntegrationActive = new AtomicBoolean(false);
 298    private final PhoneStateListener phoneStateListener = new PhoneStateListener() {
 299        @Override
 300        public void onCallStateChanged(final int state, final String phoneNumber) {
 301            if (diallerIntegrationActive.get()) return;
 302            isPhoneInCall.set(state != TelephonyManager.CALL_STATE_IDLE);
 303            if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
 304                mJingleConnectionManager.notifyPhoneCallStarted();
 305            }
 306        }
 307    };
 308
 309    public void setDiallerIntegrationActive(boolean active) {
 310      diallerIntegrationActive.set(active);
 311    }
 312
 313    private boolean destroyed = false;
 314
 315    private int unreadCount = -1;
 316
 317    //Ui callback listeners
 318    private final Set<OnConversationUpdate> mOnConversationUpdates = Collections.newSetFromMap(new WeakHashMap<OnConversationUpdate, Boolean>());
 319    private final Set<OnShowErrorToast> mOnShowErrorToasts = Collections.newSetFromMap(new WeakHashMap<OnShowErrorToast, Boolean>());
 320    private final Set<OnAccountUpdate> mOnAccountUpdates = Collections.newSetFromMap(new WeakHashMap<OnAccountUpdate, Boolean>());
 321    private final Set<OnCaptchaRequested> mOnCaptchaRequested = Collections.newSetFromMap(new WeakHashMap<OnCaptchaRequested, Boolean>());
 322    private final Set<OnRosterUpdate> mOnRosterUpdates = Collections.newSetFromMap(new WeakHashMap<OnRosterUpdate, Boolean>());
 323    private final Set<OnUpdateBlocklist> mOnUpdateBlocklist = Collections.newSetFromMap(new WeakHashMap<OnUpdateBlocklist, Boolean>());
 324    private final Set<OnMucRosterUpdate> mOnMucRosterUpdate = Collections.newSetFromMap(new WeakHashMap<OnMucRosterUpdate, Boolean>());
 325    private final Set<OnKeyStatusUpdated> mOnKeyStatusUpdated = Collections.newSetFromMap(new WeakHashMap<OnKeyStatusUpdated, Boolean>());
 326    private final Set<OnJingleRtpConnectionUpdate> onJingleRtpConnectionUpdate = Collections.newSetFromMap(new WeakHashMap<OnJingleRtpConnectionUpdate, Boolean>());
 327
 328    private final Object LISTENER_LOCK = new Object();
 329
 330
 331    public final Set<String> FILENAMES_TO_IGNORE_DELETION = new HashSet<>();
 332
 333
 334    private final OnBindListener mOnBindListener = new OnBindListener() {
 335
 336        @Override
 337        public void onBind(final Account account) {
 338            synchronized (mInProgressAvatarFetches) {
 339                for (Iterator<String> iterator = mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
 340                    final String KEY = iterator.next();
 341                    if (KEY.startsWith(account.getJid().asBareJid() + "_")) {
 342                        iterator.remove();
 343                    }
 344                }
 345            }
 346            boolean loggedInSuccessfully = account.setOption(Account.OPTION_LOGGED_IN_SUCCESSFULLY, true);
 347            boolean gainedFeature = account.setOption(Account.OPTION_HTTP_UPLOAD_AVAILABLE, account.getXmppConnection().getFeatures().httpUpload(0));
 348            if (loggedInSuccessfully || gainedFeature) {
 349                databaseBackend.updateAccount(account);
 350            }
 351
 352            if (loggedInSuccessfully) {
 353                if (!TextUtils.isEmpty(account.getDisplayName())) {
 354                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": display name wasn't empty on first log in. publishing");
 355                    publishDisplayName(account);
 356                }
 357            }
 358
 359            account.getRoster().clearPresences();
 360            synchronized (account.inProgressConferenceJoins) {
 361                account.inProgressConferenceJoins.clear();
 362            }
 363            synchronized (account.inProgressConferencePings) {
 364                account.inProgressConferencePings.clear();
 365            }
 366            mJingleConnectionManager.notifyRebound(account);
 367            mQuickConversationsService.considerSyncBackground(false);
 368            fetchRosterFromServer(account);
 369
 370            final XmppConnection connection = account.getXmppConnection();
 371
 372            if (connection.getFeatures().bookmarks2()) {
 373                fetchBookmarks2(account);
 374            } else if (!account.getXmppConnection().getFeatures().bookmarksConversion()) {
 375                fetchBookmarks(account);
 376            }
 377            final boolean flexible = account.getXmppConnection().getFeatures().flexibleOfflineMessageRetrieval();
 378            final boolean catchup = getMessageArchiveService().inCatchup(account);
 379            if (flexible && catchup && account.getXmppConnection().isMamPreferenceAlways()) {
 380                sendIqPacket(account, mIqGenerator.purgeOfflineMessages(), (acc, packet) -> {
 381                    if (packet.getType() == IqPacket.TYPE.RESULT) {
 382                        Log.d(Config.LOGTAG, acc.getJid().asBareJid() + ": successfully purged offline messages");
 383                    }
 384                });
 385            }
 386            sendPresence(account);
 387            if (mPushManagementService.available(account)) {
 388                mPushManagementService.registerPushTokenOnServer(account);
 389            }
 390            connectMultiModeConversations(account);
 391            syncDirtyContacts(account);
 392
 393        }
 394    };
 395    private final AtomicLong mLastExpiryRun = new AtomicLong(0);
 396    private final LruCache<Pair<String, String>, ServiceDiscoveryResult> discoCache = new LruCache<>(20);
 397    private final OnStatusChanged statusListener = new OnStatusChanged() {
 398
 399        @Override
 400        public void onStatusChanged(final Account account) {
 401            XmppConnection connection = account.getXmppConnection();
 402            updateAccountUi();
 403
 404            if (account.getStatus() == Account.State.ONLINE || account.getStatus().isError()) {
 405                mQuickConversationsService.signalAccountStateChange();
 406            }
 407
 408            if (account.getStatus() == Account.State.ONLINE) {
 409                synchronized (mLowPingTimeoutMode) {
 410                    if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
 411                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": leaving low ping timeout mode");
 412                    }
 413                }
 414                if (account.setShowErrorNotification(true)) {
 415                    databaseBackend.updateAccount(account);
 416                }
 417                mMessageArchiveService.executePendingQueries(account);
 418                if (connection != null && connection.getFeatures().csi()) {
 419                    if (checkListeners()) {
 420                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + " sending csi//inactive");
 421                        connection.sendInactive();
 422                    } else {
 423                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + " sending csi//active");
 424                        connection.sendActive();
 425                    }
 426                }
 427                List<Conversation> conversations = getConversations();
 428                for (Conversation conversation : conversations) {
 429                    final boolean inProgressJoin;
 430                    synchronized (account.inProgressConferenceJoins) {
 431                        inProgressJoin = account.inProgressConferenceJoins.contains(conversation);
 432                    }
 433                    final boolean pendingJoin;
 434                    synchronized (account.pendingConferenceJoins) {
 435                        pendingJoin = account.pendingConferenceJoins.contains(conversation);
 436                    }
 437                    if (conversation.getAccount() == account
 438                            && !pendingJoin
 439                            && !inProgressJoin) {
 440                        sendUnsentMessages(conversation);
 441                    }
 442                }
 443                final List<Conversation> pendingLeaves;
 444                synchronized (account.pendingConferenceLeaves) {
 445                    pendingLeaves = new ArrayList<>(account.pendingConferenceLeaves);
 446                    account.pendingConferenceLeaves.clear();
 447
 448                }
 449                for (Conversation conversation : pendingLeaves) {
 450                    leaveMuc(conversation);
 451                }
 452                final List<Conversation> pendingJoins;
 453                synchronized (account.pendingConferenceJoins) {
 454                    pendingJoins = new ArrayList<>(account.pendingConferenceJoins);
 455                    account.pendingConferenceJoins.clear();
 456                }
 457                for (Conversation conversation : pendingJoins) {
 458                    joinMuc(conversation);
 459                }
 460                scheduleWakeUpCall(Config.PING_MAX_INTERVAL, account.getUuid().hashCode());
 461            } else if (account.getStatus() == Account.State.OFFLINE || account.getStatus() == Account.State.DISABLED) {
 462                resetSendingToWaiting(account);
 463                if (account.isEnabled() && isInLowPingTimeoutMode(account)) {
 464                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": went into offline state during low ping mode. reconnecting now");
 465                    reconnectAccount(account, true, false);
 466                } else {
 467                    final int timeToReconnect = SECURE_RANDOM.nextInt(10) + 2;
 468                    scheduleWakeUpCall(timeToReconnect, account.getUuid().hashCode());
 469                }
 470            } else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
 471                databaseBackend.updateAccount(account);
 472                reconnectAccount(account, true, false);
 473            } else if (account.getStatus() != Account.State.CONNECTING && account.getStatus() != Account.State.NO_INTERNET) {
 474                resetSendingToWaiting(account);
 475                if (connection != null && account.getStatus().isAttemptReconnect()) {
 476                    final int next = connection.getTimeToNextAttempt();
 477                    final boolean lowPingTimeoutMode = isInLowPingTimeoutMode(account);
 478                    if (next <= 0) {
 479                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error connecting account. reconnecting now. lowPingTimeout=" + lowPingTimeoutMode);
 480                        reconnectAccount(account, true, false);
 481                    } else {
 482                        final int attempt = connection.getAttempt() + 1;
 483                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error connecting account. try again in " + next + "s for the " + attempt + " time. lowPingTimeout=" + lowPingTimeoutMode);
 484                        scheduleWakeUpCall(next, account.getUuid().hashCode());
 485                    }
 486                }
 487            }
 488            getNotificationService().updateErrorNotification();
 489        }
 490    };
 491    private OpenPgpServiceConnection pgpServiceConnection;
 492    private PgpEngine mPgpEngine = null;
 493    private WakeLock wakeLock;
 494    private LruCache<String, Bitmap> mBitmapCache;
 495    private LruCache<String, Drawable> mDrawableCache;
 496    private final BroadcastReceiver mInternalEventReceiver = new InternalEventReceiver();
 497    private final BroadcastReceiver mInternalScreenEventReceiver = new InternalEventReceiver();
 498
 499    private static String generateFetchKey(Account account, final Avatar avatar) {
 500        return account.getJid().asBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum;
 501    }
 502
 503    private boolean isInLowPingTimeoutMode(Account account) {
 504        synchronized (mLowPingTimeoutMode) {
 505            return mLowPingTimeoutMode.contains(account.getJid().asBareJid());
 506        }
 507    }
 508
 509    public void startForcingForegroundNotification() {
 510        mForceForegroundService.set(true);
 511        toggleForegroundService();
 512    }
 513
 514    public void stopForcingForegroundNotification() {
 515        mForceForegroundService.set(false);
 516        toggleForegroundService();
 517    }
 518
 519    public boolean areMessagesInitialized() {
 520        return this.restoredFromDatabaseLatch.getCount() == 0;
 521    }
 522
 523    public PgpEngine getPgpEngine() {
 524        if (!Config.supportOpenPgp()) {
 525            return null;
 526        } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
 527            if (this.mPgpEngine == null) {
 528                this.mPgpEngine = new PgpEngine(new OpenPgpApi(
 529                        getApplicationContext(),
 530                        pgpServiceConnection.getService()), this);
 531            }
 532            return mPgpEngine;
 533        } else {
 534            return null;
 535        }
 536
 537    }
 538
 539    public OpenPgpApi getOpenPgpApi() {
 540        if (!Config.supportOpenPgp()) {
 541            return null;
 542        } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
 543            return new OpenPgpApi(this, pgpServiceConnection.getService());
 544        } else {
 545            return null;
 546        }
 547    }
 548
 549    public FileBackend getFileBackend() {
 550        return this.fileBackend;
 551    }
 552
 553    public DownloadableFile getFileForCid(Cid cid) {
 554        return this.databaseBackend.getFileForCid(cid);
 555    }
 556
 557    public void saveCid(Cid cid, File file) {
 558        this.databaseBackend.saveCid(cid, file);
 559    }
 560
 561    public AvatarService getAvatarService() {
 562        return this.mAvatarService;
 563    }
 564
 565    public void attachLocationToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
 566        int encryption = conversation.getNextEncryption();
 567        if (encryption == Message.ENCRYPTION_PGP) {
 568            encryption = Message.ENCRYPTION_DECRYPTED;
 569        }
 570        Message message = new Message(conversation, uri.toString(), encryption);
 571        message.setThread(conversation.getThread());
 572        Message.configurePrivateMessage(message);
 573        if (encryption == Message.ENCRYPTION_DECRYPTED) {
 574            getPgpEngine().encrypt(message, callback);
 575        } else {
 576            sendMessage(message);
 577            callback.success(message);
 578        }
 579    }
 580
 581    public void attachFileToConversation(final Conversation conversation, final Uri uri, final String type, final UiCallback<Message> callback) {
 582        final Message message;
 583        if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 584            message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
 585        } else {
 586            message = new Message(conversation, "", conversation.getNextEncryption());
 587        }
 588        message.setThread(conversation.getThread());
 589        if (!Message.configurePrivateFileMessage(message)) {
 590            message.setCounterpart(conversation.getNextCounterpart());
 591            message.setType(Message.TYPE_FILE);
 592        }
 593        Log.d(Config.LOGTAG, "attachFile: type=" + message.getType());
 594        Log.d(Config.LOGTAG, "counterpart=" + message.getCounterpart());
 595        final AttachFileToConversationRunnable runnable = new AttachFileToConversationRunnable(this, uri, type, message, callback);
 596        if (runnable.isVideoMessage()) {
 597            VIDEO_COMPRESSION_EXECUTOR.execute(runnable);
 598        } else {
 599            FILE_ATTACHMENT_EXECUTOR.execute(runnable);
 600        }
 601    }
 602
 603    public void attachImageToConversation(final Conversation conversation, final Uri uri,  final String type, final UiCallback<Message> callback) {
 604        final String mimeType = MimeUtils.guessMimeTypeFromUriAndMime(this, uri, type);
 605        final String compressPictures = getCompressPicturesPreference();
 606
 607        if ("never".equals(compressPictures)
 608                || ("auto".equals(compressPictures) && getFileBackend().useImageAsIs(uri))
 609                || (mimeType != null && mimeType.endsWith("/gif"))
 610                || getFileBackend().unusualBounds(uri)) {
 611            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": not compressing picture. sending as file");
 612            attachFileToConversation(conversation, uri, mimeType, callback);
 613            return;
 614        }
 615        final Message message;
 616        if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 617            message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
 618        } else {
 619            message = new Message(conversation, "", conversation.getNextEncryption());
 620        }
 621        message.setThread(conversation.getThread());
 622        if (!Message.configurePrivateFileMessage(message)) {
 623            message.setCounterpart(conversation.getNextCounterpart());
 624            message.setType(Message.TYPE_IMAGE);
 625        }
 626        Log.d(Config.LOGTAG, "attachImage: type=" + message.getType());
 627        FILE_ATTACHMENT_EXECUTOR.execute(() -> {
 628            try {
 629                getFileBackend().copyImageToPrivateStorage(message, uri);
 630            } catch (FileBackend.ImageCompressionException e) {
 631                Log.d(Config.LOGTAG, "unable to compress image. fall back to file transfer", e);
 632                attachFileToConversation(conversation, uri, mimeType, callback);
 633                return;
 634            } catch (final FileBackend.FileCopyException e) {
 635                callback.error(e.getResId(), message);
 636                return;
 637            }
 638            if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 639                final PgpEngine pgpEngine = getPgpEngine();
 640                if (pgpEngine != null) {
 641                    pgpEngine.encrypt(message, callback);
 642                } else if (callback != null) {
 643                    callback.error(R.string.unable_to_connect_to_keychain, null);
 644                }
 645            } else {
 646                sendMessage(message);
 647                callback.success(message);
 648            }
 649        });
 650    }
 651
 652    public Conversation find(Bookmark bookmark) {
 653        return find(bookmark.getAccount(), bookmark.getJid());
 654    }
 655
 656    public Conversation find(final Account account, final Jid jid) {
 657        return find(getConversations(), account, jid);
 658    }
 659
 660    public boolean isMuc(final Account account, final Jid jid) {
 661        final Conversation c = find(account, jid);
 662        return c != null && c.getMode() == Conversational.MODE_MULTI;
 663    }
 664
 665    public void search(final List<String> term, final String uuid, final OnSearchResultsAvailable onSearchResultsAvailable) {
 666        MessageSearchTask.search(this, term, uuid, onSearchResultsAvailable);
 667    }
 668
 669    @Override
 670    public int onStartCommand(Intent intent, int flags, int startId) {
 671        final String action = intent == null ? null : intent.getAction();
 672        final boolean needsForegroundService = intent != null && intent.getBooleanExtra(EventReceiver.EXTRA_NEEDS_FOREGROUND_SERVICE, false);
 673        if (needsForegroundService) {
 674            Log.d(Config.LOGTAG, "toggle forced foreground service after receiving event (action=" + action + ")");
 675            toggleForegroundService(true);
 676        }
 677        String pushedAccountHash = null;
 678        boolean interactive = false;
 679        if (action != null) {
 680            final String uuid = intent.getStringExtra("uuid");
 681            switch (action) {
 682                case QuickConversationsService.SMS_RETRIEVED_ACTION:
 683                    mQuickConversationsService.handleSmsReceived(intent);
 684                    break;
 685                case ConnectivityManager.CONNECTIVITY_ACTION:
 686                    if (hasInternetConnection()) {
 687                        if (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL > 0) {
 688                            schedulePostConnectivityChange();
 689                        }
 690                        if (Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
 691                            resetAllAttemptCounts(true, false);
 692                        }
 693                        Resolver.clearCache();
 694                    }
 695                    break;
 696                case Intent.ACTION_SHUTDOWN:
 697                    logoutAndSave(true);
 698                    return START_NOT_STICKY;
 699                case ACTION_CLEAR_MESSAGE_NOTIFICATION:
 700                    mNotificationExecutor.execute(() -> {
 701                        try {
 702                            final Conversation c = findConversationByUuid(uuid);
 703                            if (c != null) {
 704                                mNotificationService.clearMessages(c);
 705                            } else {
 706                                mNotificationService.clearMessages();
 707                            }
 708                            restoredFromDatabaseLatch.await();
 709
 710                        } catch (InterruptedException e) {
 711                            Log.d(Config.LOGTAG, "unable to process clear message notification");
 712                        }
 713                    });
 714                    break;
 715                case ACTION_CLEAR_MISSED_CALL_NOTIFICATION:
 716                    mNotificationExecutor.execute(() -> {
 717                        try {
 718                            final Conversation c = findConversationByUuid(uuid);
 719                            if (c != null) {
 720                                mNotificationService.clearMissedCalls(c);
 721                            } else {
 722                                mNotificationService.clearMissedCalls();
 723                            }
 724                            restoredFromDatabaseLatch.await();
 725
 726                        } catch (InterruptedException e) {
 727                            Log.d(Config.LOGTAG, "unable to process clear missed call notification");
 728                        }
 729                    });
 730                    break;
 731                case ACTION_DISMISS_CALL: {
 732                    final String sessionId = intent.getStringExtra(RtpSessionActivity.EXTRA_SESSION_ID);
 733                    Log.d(Config.LOGTAG, "received intent to dismiss call with session id " + sessionId);
 734                    mJingleConnectionManager.rejectRtpSession(sessionId);
 735                    break;
 736                }
 737                case TorServiceUtils.ACTION_STATUS:
 738                    final String status = intent.getStringExtra(TorServiceUtils.EXTRA_STATUS);
 739                    //TODO port and host are in 'extras' - but this may not be a reliable source?
 740                    if ("ON".equals(status)) {
 741                        handleOrbotStartedEvent();
 742                        return START_STICKY;
 743                    }
 744                    break;
 745                case ACTION_END_CALL: {
 746                    final String sessionId = intent.getStringExtra(RtpSessionActivity.EXTRA_SESSION_ID);
 747                    Log.d(Config.LOGTAG, "received intent to end call with session id " + sessionId);
 748                    mJingleConnectionManager.endRtpSession(sessionId);
 749                }
 750                break;
 751                case ACTION_PROVISION_ACCOUNT: {
 752                    final String address = intent.getStringExtra("address");
 753                    final String password = intent.getStringExtra("password");
 754                    if (QuickConversationsService.isQuicksy() || Strings.isNullOrEmpty(address) || Strings.isNullOrEmpty(password)) {
 755                        break;
 756                    }
 757                    provisionAccount(address, password);
 758                    break;
 759                }
 760                case ACTION_DISMISS_ERROR_NOTIFICATIONS:
 761                    dismissErrorNotifications();
 762                    break;
 763                case ACTION_TRY_AGAIN:
 764                    resetAllAttemptCounts(false, true);
 765                    interactive = true;
 766                    break;
 767                case ACTION_REPLY_TO_CONVERSATION:
 768                    Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
 769                    if (remoteInput == null) {
 770                        break;
 771                    }
 772                    final CharSequence body = remoteInput.getCharSequence("text_reply");
 773                    final boolean dismissNotification = intent.getBooleanExtra("dismiss_notification", false);
 774                    final String lastMessageUuid = intent.getStringExtra("last_message_uuid");
 775                    if (body == null || body.length() <= 0) {
 776                        break;
 777                    }
 778                    mNotificationExecutor.execute(() -> {
 779                        try {
 780                            restoredFromDatabaseLatch.await();
 781                            final Conversation c = findConversationByUuid(uuid);
 782                            if (c != null) {
 783                                directReply(c, body.toString(), lastMessageUuid, dismissNotification);
 784                            }
 785                        } catch (InterruptedException e) {
 786                            Log.d(Config.LOGTAG, "unable to process direct reply");
 787                        }
 788                    });
 789                    break;
 790                case ACTION_MARK_AS_READ:
 791                    mNotificationExecutor.execute(() -> {
 792                        final Conversation c = findConversationByUuid(uuid);
 793                        if (c == null) {
 794                            Log.d(Config.LOGTAG, "received mark read intent for unknown conversation (" + uuid + ")");
 795                            return;
 796                        }
 797                        try {
 798                            restoredFromDatabaseLatch.await();
 799                            sendReadMarker(c, null);
 800                        } catch (InterruptedException e) {
 801                            Log.d(Config.LOGTAG, "unable to process notification read marker for conversation " + c.getName());
 802                        }
 803
 804                    });
 805                    break;
 806                case ACTION_SNOOZE:
 807                    mNotificationExecutor.execute(() -> {
 808                        final Conversation c = findConversationByUuid(uuid);
 809                        if (c == null) {
 810                            Log.d(Config.LOGTAG, "received snooze intent for unknown conversation (" + uuid + ")");
 811                            return;
 812                        }
 813                        c.setMutedTill(System.currentTimeMillis() + 30 * 60 * 1000);
 814                        mNotificationService.clearMessages(c);
 815                        updateConversation(c);
 816                    });
 817                case AudioManager.RINGER_MODE_CHANGED_ACTION:
 818                case NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED:
 819                    if (dndOnSilentMode()) {
 820                        refreshAllPresences();
 821                    }
 822                    break;
 823                case Intent.ACTION_SCREEN_ON:
 824                    deactivateGracePeriod();
 825                case Intent.ACTION_USER_PRESENT:
 826                case Intent.ACTION_SCREEN_OFF:
 827                    if (awayWhenScreenLocked()) {
 828                        refreshAllPresences();
 829                    }
 830                    break;
 831                case ACTION_FCM_TOKEN_REFRESH:
 832                    refreshAllFcmTokens();
 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.toString());
 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 void reinitializeMuclumbusService() {
 964        mChannelDiscoveryService.initializeMuclumbusService();
 965    }
 966
 967    public void discoverChannels(String query, ChannelDiscoveryService.Method method, ChannelDiscoveryService.OnChannelSearchResultsFound onChannelSearchResultsFound) {
 968        mChannelDiscoveryService.discover(Strings.nullToEmpty(query).trim(), method, onChannelSearchResultsFound);
 969    }
 970
 971    public boolean isDataSaverDisabled() {
 972        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 973            final ConnectivityManager connectivityManager =
 974                    (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
 975            return !connectivityManager.isActiveNetworkMetered()
 976                    || Compatibility.getRestrictBackgroundStatus(connectivityManager)
 977                            == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
 978        } else {
 979            return true;
 980        }
 981    }
 982
 983    private void directReply(final Conversation conversation, final String body, final String lastMessageUuid, final boolean dismissAfterReply) {
 984        final Message inReplyTo = lastMessageUuid == null ? null : conversation.findMessageWithUuid(lastMessageUuid);
 985        final Message message = new Message(conversation, body, conversation.getNextEncryption());
 986        if (inReplyTo != null) message.setThread(inReplyTo.getThread());
 987        if (inReplyTo != null && inReplyTo.isPrivateMessage()) {
 988            Message.configurePrivateMessage(message, inReplyTo.getCounterpart());
 989        }
 990        message.markUnread();
 991        if (message.getEncryption() == Message.ENCRYPTION_PGP) {
 992            getPgpEngine().encrypt(message, new UiCallback<Message>() {
 993                @Override
 994                public void success(Message message) {
 995                    if (dismissAfterReply) {
 996                        markRead((Conversation) message.getConversation(), true);
 997                    } else {
 998                        mNotificationService.pushFromDirectReply(message);
 999                    }
1000                }
1001
1002                @Override
1003                public void error(int errorCode, Message object) {
1004
1005                }
1006
1007                @Override
1008                public void userInputRequired(PendingIntent pi, Message object) {
1009
1010                }
1011            });
1012        } else {
1013            sendMessage(message);
1014            if (dismissAfterReply) {
1015                markRead(conversation, true);
1016            } else {
1017                mNotificationService.pushFromDirectReply(message);
1018            }
1019        }
1020    }
1021
1022    private boolean dndOnSilentMode() {
1023        return getBooleanPreference(SettingsActivity.DND_ON_SILENT_MODE, R.bool.dnd_on_silent_mode);
1024    }
1025
1026    private boolean manuallyChangePresence() {
1027        return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
1028    }
1029
1030    private boolean treatVibrateAsSilent() {
1031        return getBooleanPreference(SettingsActivity.TREAT_VIBRATE_AS_SILENT, R.bool.treat_vibrate_as_silent);
1032    }
1033
1034    private boolean awayWhenScreenLocked() {
1035        return getBooleanPreference(SettingsActivity.AWAY_WHEN_SCREEN_IS_OFF, R.bool.away_when_screen_off);
1036    }
1037
1038    private String getCompressPicturesPreference() {
1039        return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression));
1040    }
1041
1042    private Presence.Status getTargetPresence() {
1043        if (dndOnSilentMode() && isPhoneSilenced()) {
1044            return Presence.Status.DND;
1045        } else if (awayWhenScreenLocked() && isScreenLocked()) {
1046            return Presence.Status.AWAY;
1047        } else {
1048            return Presence.Status.ONLINE;
1049        }
1050    }
1051
1052    public boolean isScreenLocked() {
1053        final KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
1054        final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
1055        final boolean locked = keyguardManager != null && keyguardManager.isKeyguardLocked();
1056        final boolean interactive = powerManager != null && powerManager.isInteractive();
1057        return locked || !interactive;
1058    }
1059
1060    private boolean isPhoneSilenced() {
1061        final boolean notificationDnd;
1062        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1063            final NotificationManager notificationManager = getSystemService(NotificationManager.class);
1064            final int filter = notificationManager == null ? NotificationManager.INTERRUPTION_FILTER_UNKNOWN : notificationManager.getCurrentInterruptionFilter();
1065            notificationDnd = filter >= NotificationManager.INTERRUPTION_FILTER_PRIORITY;
1066        } else {
1067            notificationDnd = false;
1068        }
1069        final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
1070        final int ringerMode = audioManager == null ? AudioManager.RINGER_MODE_NORMAL : audioManager.getRingerMode();
1071        try {
1072            if (treatVibrateAsSilent()) {
1073                return notificationDnd || ringerMode != AudioManager.RINGER_MODE_NORMAL;
1074            } else {
1075                return notificationDnd || ringerMode == AudioManager.RINGER_MODE_SILENT;
1076            }
1077        } catch (Throwable throwable) {
1078            Log.d(Config.LOGTAG, "platform bug in isPhoneSilenced (" + throwable.getMessage() + ")");
1079            return notificationDnd;
1080        }
1081    }
1082
1083    private void resetAllAttemptCounts(boolean reallyAll, boolean retryImmediately) {
1084        Log.d(Config.LOGTAG, "resetting all attempt counts");
1085        for (Account account : accounts) {
1086            if (account.hasErrorStatus() || reallyAll) {
1087                final XmppConnection connection = account.getXmppConnection();
1088                if (connection != null) {
1089                    connection.resetAttemptCount(retryImmediately);
1090                }
1091            }
1092            if (account.setShowErrorNotification(true)) {
1093                mDatabaseWriterExecutor.execute(() -> databaseBackend.updateAccount(account));
1094            }
1095        }
1096        mNotificationService.updateErrorNotification();
1097    }
1098
1099    private void dismissErrorNotifications() {
1100        for (final Account account : this.accounts) {
1101            if (account.hasErrorStatus()) {
1102                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": dismissing error notification");
1103                if (account.setShowErrorNotification(false)) {
1104                    mDatabaseWriterExecutor.execute(() -> databaseBackend.updateAccount(account));
1105                }
1106            }
1107        }
1108    }
1109
1110    private void expireOldMessages() {
1111        expireOldMessages(false);
1112    }
1113
1114    public void expireOldMessages(final boolean resetHasMessagesLeftOnServer) {
1115        mLastExpiryRun.set(SystemClock.elapsedRealtime());
1116        mDatabaseWriterExecutor.execute(() -> {
1117            long timestamp = getAutomaticMessageDeletionDate();
1118            if (timestamp > 0) {
1119                databaseBackend.expireOldMessages(timestamp);
1120                synchronized (XmppConnectionService.this.conversations) {
1121                    for (Conversation conversation : XmppConnectionService.this.conversations) {
1122                        conversation.expireOldMessages(timestamp);
1123                        if (resetHasMessagesLeftOnServer) {
1124                            conversation.messagesLoaded.set(true);
1125                            conversation.setHasMessagesLeftOnServer(true);
1126                        }
1127                    }
1128                }
1129                updateConversationUi();
1130            }
1131        });
1132    }
1133
1134    public boolean hasInternetConnection() {
1135        final ConnectivityManager cm = ContextCompat.getSystemService(this, ConnectivityManager.class);
1136        if (cm == null) {
1137            return true; //if internet connection can not be checked it is probably best to just try
1138        }
1139        try {
1140            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
1141                final Network activeNetwork = cm.getActiveNetwork();
1142                final NetworkCapabilities capabilities = activeNetwork == null ? null : cm.getNetworkCapabilities(activeNetwork);
1143                return capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1144            } else {
1145                final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
1146                return networkInfo != null && (networkInfo.isConnected() || networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET);
1147            }
1148        } catch (final RuntimeException e) {
1149            Log.d(Config.LOGTAG, "unable to check for internet connection", e);
1150            return true; //if internet connection can not be checked it is probably best to just try
1151        }
1152    }
1153
1154    @SuppressLint("TrulyRandom")
1155    @Override
1156    public void onCreate() {
1157        setTheme(ThemeHelper.find(this));
1158        if (Compatibility.runsTwentySix()) {
1159            mNotificationService.initializeChannels();
1160        }
1161        mChannelDiscoveryService.initializeMuclumbusService();
1162        mForceDuringOnCreate.set(Compatibility.runsAndTargetsTwentySix(this));
1163        toggleForegroundService();
1164        this.destroyed = false;
1165        OmemoSetting.load(this);
1166        ExceptionHelper.init(getApplicationContext());
1167        try {
1168            Security.insertProviderAt(Conscrypt.newProvider(), 1);
1169        } catch (Throwable throwable) {
1170            Log.e(Config.LOGTAG, "unable to initialize security provider", throwable);
1171        }
1172        Resolver.init(this);
1173        updateMemorizingTrustmanager();
1174        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
1175        final int cacheSize = maxMemory / 9;
1176        this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
1177            @Override
1178            protected int sizeOf(final String key, final Bitmap bitmap) {
1179                return bitmap.getByteCount() / 1024;
1180            }
1181        };
1182        this.mDrawableCache = new LruCache<String, Drawable>(cacheSize) {
1183            @Override
1184            protected int sizeOf(final String key, final Drawable drawable) {
1185                if (drawable instanceof BitmapDrawable) {
1186                    return ((BitmapDrawable) drawable).getBitmap().getByteCount() / 1024;
1187                } else {
1188                    return drawable.getIntrinsicWidth() * drawable.getIntrinsicHeight() * 40 / 1024;
1189                }
1190            }
1191        };
1192        if (mLastActivity == 0) {
1193            mLastActivity = getPreferences().getLong(SETTING_LAST_ACTIVITY_TS, System.currentTimeMillis());
1194        }
1195
1196        Log.d(Config.LOGTAG, "initializing database...");
1197        this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
1198        Log.d(Config.LOGTAG, "restoring accounts...");
1199        this.accounts = databaseBackend.getAccounts();
1200        final SharedPreferences.Editor editor = getPreferences().edit();
1201        if (this.accounts.size() == 0 && Arrays.asList("Sony", "Sony Ericsson").contains(Build.MANUFACTURER)) {
1202            editor.putBoolean(SettingsActivity.KEEP_FOREGROUND_SERVICE, true);
1203            Log.d(Config.LOGTAG, Build.MANUFACTURER + " is on blacklist. enabling foreground service");
1204        }
1205        final boolean hasEnabledAccounts = hasEnabledAccounts();
1206        editor.putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
1207        editor.apply();
1208        toggleSetProfilePictureActivity(hasEnabledAccounts);
1209
1210        restoreFromDatabase();
1211
1212        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
1213            startContactObserver();
1214        }
1215        FILE_OBSERVER_EXECUTOR.execute(fileBackend::deleteHistoricAvatarPath);
1216        if (Compatibility.hasStoragePermission(this)) {
1217            Log.d(Config.LOGTAG, "starting file observer");
1218            FILE_OBSERVER_EXECUTOR.execute(this.fileObserver::startWatching);
1219            FILE_OBSERVER_EXECUTOR.execute(this::checkForDeletedFiles);
1220        }
1221        if (Config.supportOpenPgp()) {
1222            this.pgpServiceConnection = new OpenPgpServiceConnection(this, "org.sufficientlysecure.keychain", new OpenPgpServiceConnection.OnBound() {
1223                @Override
1224                public void onBound(IOpenPgpService2 service) {
1225                    for (Account account : accounts) {
1226                        final PgpDecryptionService pgp = account.getPgpDecryptionService();
1227                        if (pgp != null) {
1228                            pgp.continueDecryption(true);
1229                        }
1230                    }
1231                }
1232
1233                @Override
1234                public void onError(Exception e) {
1235                }
1236            });
1237            this.pgpServiceConnection.bindToService();
1238        }
1239
1240        final PowerManager pm = ContextCompat.getSystemService(this, PowerManager.class);
1241        this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Conversations:Service");
1242
1243        toggleForegroundService();
1244        updateUnreadCountBadge();
1245        toggleScreenEventReceiver();
1246        final IntentFilter intentFilter = new IntentFilter();
1247        intentFilter.addAction(TorServiceUtils.ACTION_STATUS);
1248        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1249            scheduleNextIdlePing();
1250            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1251                intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1252            }
1253            intentFilter.addAction(NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED);
1254        }
1255        registerReceiver(this.mInternalEventReceiver, intentFilter);
1256        mForceDuringOnCreate.set(false);
1257        toggleForegroundService();
1258        setupPhoneStateListener();
1259    }
1260
1261
1262    private void setupPhoneStateListener() {
1263        final TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
1264        if (telephonyManager == null || Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
1265            return;
1266        }
1267        telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
1268    }
1269
1270    public boolean isPhoneInCall() {
1271        return isPhoneInCall.get();
1272    }
1273
1274    private void checkForDeletedFiles() {
1275        if (destroyed) {
1276            Log.d(Config.LOGTAG, "Do not check for deleted files because service has been destroyed");
1277            return;
1278        }
1279        final long start = SystemClock.elapsedRealtime();
1280        final List<DatabaseBackend.FilePathInfo> relativeFilePaths = databaseBackend.getFilePathInfo();
1281        final List<DatabaseBackend.FilePathInfo> changed = new ArrayList<>();
1282        for (final DatabaseBackend.FilePathInfo filePath : relativeFilePaths) {
1283            if (destroyed) {
1284                Log.d(Config.LOGTAG, "Stop checking for deleted files because service has been destroyed");
1285                return;
1286            }
1287            final File file = fileBackend.getFileForPath(filePath.path);
1288            if (filePath.setDeleted(!file.exists())) {
1289                changed.add(filePath);
1290            }
1291        }
1292        final long duration = SystemClock.elapsedRealtime() - start;
1293        Log.d(Config.LOGTAG, "found " + changed.size() + " changed files on start up. total=" + relativeFilePaths.size() + ". (" + duration + "ms)");
1294        if (changed.size() > 0) {
1295            databaseBackend.markFilesAsChanged(changed);
1296            markChangedFiles(changed);
1297        }
1298    }
1299
1300    public void startContactObserver() {
1301        getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, new ContentObserver(null) {
1302            @Override
1303            public void onChange(boolean selfChange) {
1304                super.onChange(selfChange);
1305                if (restoredFromDatabaseLatch.getCount() == 0) {
1306                    loadPhoneContacts();
1307                }
1308            }
1309        });
1310    }
1311
1312    @Override
1313    public void onTrimMemory(int level) {
1314        super.onTrimMemory(level);
1315        if (level >= TRIM_MEMORY_COMPLETE) {
1316            Log.d(Config.LOGTAG, "clear cache due to low memory");
1317            getBitmapCache().evictAll();
1318        }
1319    }
1320
1321    @Override
1322    public void onDestroy() {
1323        try {
1324            unregisterReceiver(this.mInternalEventReceiver);
1325            unregisterReceiver(this.mInternalScreenEventReceiver);
1326        } catch (final IllegalArgumentException e) {
1327            //ignored
1328        }
1329        destroyed = false;
1330        fileObserver.stopWatching();
1331        super.onDestroy();
1332    }
1333
1334    public void restartFileObserver() {
1335        Log.d(Config.LOGTAG, "restarting file observer");
1336        FILE_OBSERVER_EXECUTOR.execute(this.fileObserver::restartWatching);
1337        FILE_OBSERVER_EXECUTOR.execute(this::checkForDeletedFiles);
1338    }
1339
1340    public void toggleScreenEventReceiver() {
1341        if (awayWhenScreenLocked() && !manuallyChangePresence()) {
1342            final IntentFilter filter = new IntentFilter();
1343            filter.addAction(Intent.ACTION_SCREEN_ON);
1344            filter.addAction(Intent.ACTION_SCREEN_OFF);
1345            filter.addAction(Intent.ACTION_USER_PRESENT);
1346            registerReceiver(this.mInternalScreenEventReceiver, filter);
1347        } else {
1348            try {
1349                unregisterReceiver(this.mInternalScreenEventReceiver);
1350            } catch (IllegalArgumentException e) {
1351                //ignored
1352            }
1353        }
1354    }
1355
1356    public void toggleForegroundService() {
1357        toggleForegroundService(false);
1358    }
1359
1360    public void setOngoingCall(AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
1361        ongoingCall.set(new OngoingCall(id, media, reconnecting));
1362        toggleForegroundService(false);
1363    }
1364
1365    public void removeOngoingCall() {
1366        ongoingCall.set(null);
1367        toggleForegroundService(false);
1368    }
1369
1370    private void toggleForegroundService(boolean force) {
1371        final boolean status;
1372        final OngoingCall ongoing = ongoingCall.get();
1373        final boolean showOngoing = ongoing != null && !diallerIntegrationActive.get();
1374        if (force || mForceDuringOnCreate.get() || mForceForegroundService.get() || showOngoing || (Compatibility.keepForegroundService(this) && hasEnabledAccounts())) {
1375            final Notification notification;
1376            final int id;
1377            if (showOngoing) {
1378                notification = this.mNotificationService.getOngoingCallNotification(ongoing);
1379                id = NotificationService.ONGOING_CALL_NOTIFICATION_ID;
1380                startForeground(id, notification);
1381                mNotificationService.cancel(NotificationService.FOREGROUND_NOTIFICATION_ID);
1382            } else {
1383                notification = this.mNotificationService.createForegroundNotification();
1384                id = NotificationService.FOREGROUND_NOTIFICATION_ID;
1385                startForeground(id, notification);
1386            }
1387
1388            if (!mForceForegroundService.get()) {
1389                mNotificationService.notify(id, notification);
1390            }
1391            status = true;
1392        } else {
1393            stopForeground(true);
1394            status = false;
1395        }
1396        if (!mForceForegroundService.get()) {
1397            mNotificationService.cancel(NotificationService.FOREGROUND_NOTIFICATION_ID);
1398        }
1399        if (!showOngoing) {
1400            mNotificationService.cancel(NotificationService.ONGOING_CALL_NOTIFICATION_ID);
1401        }
1402        Log.d(Config.LOGTAG, "ForegroundService: " + (status ? "on" : "off"));
1403    }
1404
1405    public boolean foregroundNotificationNeedsUpdatingWhenErrorStateChanges() {
1406        return !mForceForegroundService.get() && ongoingCall.get() == null && Compatibility.keepForegroundService(this) && hasEnabledAccounts();
1407    }
1408
1409    @Override
1410    public void onTaskRemoved(final Intent rootIntent) {
1411        super.onTaskRemoved(rootIntent);
1412        if ((Compatibility.keepForegroundService(this) && hasEnabledAccounts()) || mForceForegroundService.get() || ongoingCall.get() != null) {
1413            Log.d(Config.LOGTAG, "ignoring onTaskRemoved because foreground service is activated");
1414        } else {
1415            this.logoutAndSave(false);
1416        }
1417    }
1418
1419    private void logoutAndSave(boolean stop) {
1420        int activeAccounts = 0;
1421        for (final Account account : accounts) {
1422            if (account.getStatus() != Account.State.DISABLED) {
1423                databaseBackend.writeRoster(account.getRoster());
1424                activeAccounts++;
1425            }
1426            if (account.getXmppConnection() != null) {
1427                new Thread(() -> disconnect(account, false)).start();
1428            }
1429        }
1430        if (stop || activeAccounts == 0) {
1431            Log.d(Config.LOGTAG, "good bye");
1432            stopSelf();
1433        }
1434    }
1435
1436    private void schedulePostConnectivityChange() {
1437        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1438        if (alarmManager == null) {
1439            return;
1440        }
1441        final long triggerAtMillis = SystemClock.elapsedRealtime() + (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL * 1000);
1442        final Intent intent = new Intent(this, EventReceiver.class);
1443        intent.setAction(ACTION_POST_CONNECTIVITY_CHANGE);
1444        try {
1445            final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, s()
1446                    ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1447                    : PendingIntent.FLAG_UPDATE_CURRENT);
1448            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1449                alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1450            } else {
1451                alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1452            }
1453        } catch (RuntimeException e) {
1454            Log.e(Config.LOGTAG, "unable to schedule alarm for post connectivity change", e);
1455        }
1456    }
1457
1458    public void scheduleWakeUpCall(int seconds, int requestCode) {
1459        final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000L;
1460        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1461        if (alarmManager == null) {
1462            return;
1463        }
1464        final Intent intent = new Intent(this, EventReceiver.class);
1465        intent.setAction("ping");
1466        try {
1467            final PendingIntent pendingIntent;
1468            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1469                pendingIntent =
1470                        PendingIntent.getBroadcast(
1471                                this, requestCode, intent, PendingIntent.FLAG_IMMUTABLE);
1472            } else {
1473                pendingIntent =
1474                        PendingIntent.getBroadcast(
1475                                this, requestCode, intent, 0);
1476            }
1477            alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1478        } catch (RuntimeException e) {
1479            Log.e(Config.LOGTAG, "unable to schedule alarm for ping", e);
1480        }
1481    }
1482
1483    @TargetApi(Build.VERSION_CODES.M)
1484    private void scheduleNextIdlePing() {
1485        final long timeToWake = SystemClock.elapsedRealtime() + (Config.IDLE_PING_INTERVAL * 1000);
1486        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1487        if (alarmManager == null) {
1488            return;
1489        }
1490        final Intent intent = new Intent(this, EventReceiver.class);
1491        intent.setAction(ACTION_IDLE_PING);
1492        try {
1493            final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, s()
1494                    ? PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
1495                    : PendingIntent.FLAG_UPDATE_CURRENT);
1496            alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1497        } catch (RuntimeException e) {
1498            Log.d(Config.LOGTAG, "unable to schedule alarm for idle ping", e);
1499        }
1500    }
1501
1502    public XmppConnection createConnection(final Account account) {
1503        final XmppConnection connection = new XmppConnection(account, this);
1504        connection.setOnMessagePacketReceivedListener(this.mMessageParser);
1505        connection.setOnStatusChangedListener(this.statusListener);
1506        connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
1507        connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
1508        connection.setOnJinglePacketReceivedListener((mJingleConnectionManager::deliverPacket));
1509        connection.setOnBindListener(this.mOnBindListener);
1510        connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
1511        connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
1512        connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
1513        AxolotlService axolotlService = account.getAxolotlService();
1514        if (axolotlService != null) {
1515            connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
1516        }
1517        return connection;
1518    }
1519
1520    public void sendChatState(Conversation conversation) {
1521        if (sendChatStates()) {
1522            MessagePacket packet = mMessageGenerator.generateChatState(conversation);
1523            sendMessagePacket(conversation.getAccount(), packet);
1524        }
1525    }
1526
1527    private void sendFileMessage(final Message message, final boolean delay) {
1528        Log.d(Config.LOGTAG, "send file message");
1529        final Account account = message.getConversation().getAccount();
1530        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1531                || message.getConversation().getMode() == Conversation.MODE_MULTI) {
1532            mHttpConnectionManager.createNewUploadConnection(message, delay);
1533        } else {
1534            mJingleConnectionManager.startJingleFileTransfer(message);
1535        }
1536    }
1537
1538    public void sendMessage(final Message message) {
1539        sendMessage(message, false, false);
1540    }
1541
1542    private void sendMessage(final Message message, final boolean resend, final boolean delay) {
1543        final Account account = message.getConversation().getAccount();
1544        if (account.setShowErrorNotification(true)) {
1545            databaseBackend.updateAccount(account);
1546            mNotificationService.updateErrorNotification();
1547        }
1548        final Conversation conversation = (Conversation) message.getConversation();
1549        account.deactivateGracePeriod();
1550
1551
1552        if (QuickConversationsService.isQuicksy() && conversation.getMode() == Conversation.MODE_SINGLE) {
1553            final Contact contact = conversation.getContact();
1554            if (!contact.showInRoster() && contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1555                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": adding " + contact.getJid() + " on sending message");
1556                createContact(contact, true);
1557            }
1558        }
1559
1560        MessagePacket packet = null;
1561        final boolean addToConversation = (conversation.getMode() != Conversation.MODE_MULTI
1562                || !Patches.BAD_MUC_REFLECTION.contains(account.getServerIdentity()))
1563                && !message.edited();
1564        boolean saveInDb = addToConversation;
1565        message.setStatus(Message.STATUS_WAITING);
1566
1567        if (message.getEncryption() != Message.ENCRYPTION_NONE && conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous()) {
1568            if (conversation.setAttribute(Conversation.ATTRIBUTE_FORMERLY_PRIVATE_NON_ANONYMOUS, true)) {
1569                databaseBackend.updateConversation(conversation);
1570            }
1571        }
1572
1573        final boolean inProgressJoin = isJoinInProgress(conversation);
1574
1575
1576        if (account.isOnlineAndConnected() && !inProgressJoin) {
1577            switch (message.getEncryption()) {
1578                case Message.ENCRYPTION_NONE:
1579                    if (message.needsUploading()) {
1580                        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1581                                || conversation.getMode() == Conversation.MODE_MULTI
1582                                || message.fixCounterpart()) {
1583                            this.sendFileMessage(message, delay);
1584                        } else {
1585                            break;
1586                        }
1587                    } else {
1588                        packet = mMessageGenerator.generateChat(message);
1589                    }
1590                    break;
1591                case Message.ENCRYPTION_PGP:
1592                case Message.ENCRYPTION_DECRYPTED:
1593                    if (message.needsUploading()) {
1594                        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1595                                || conversation.getMode() == Conversation.MODE_MULTI
1596                                || message.fixCounterpart()) {
1597                            this.sendFileMessage(message, delay);
1598                        } else {
1599                            break;
1600                        }
1601                    } else {
1602                        packet = mMessageGenerator.generatePgpChat(message);
1603                    }
1604                    break;
1605                case Message.ENCRYPTION_AXOLOTL:
1606                    message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1607                    if (message.needsUploading()) {
1608                        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1609                                || conversation.getMode() == Conversation.MODE_MULTI
1610                                || message.fixCounterpart()) {
1611                            this.sendFileMessage(message, delay);
1612                        } else {
1613                            break;
1614                        }
1615                    } else {
1616                        XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
1617                        if (axolotlMessage == null) {
1618                            account.getAxolotlService().preparePayloadMessage(message, delay);
1619                        } else {
1620                            packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
1621                        }
1622                    }
1623                    break;
1624
1625            }
1626            if (packet != null) {
1627                if (account.getXmppConnection().getFeatures().sm()
1628                        || (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1629                    message.setStatus(Message.STATUS_UNSEND);
1630                } else {
1631                    message.setStatus(Message.STATUS_SEND);
1632                }
1633            }
1634        } else {
1635            switch (message.getEncryption()) {
1636                case Message.ENCRYPTION_DECRYPTED:
1637                    if (!message.needsUploading()) {
1638                        String pgpBody = message.getEncryptedBody();
1639                        String decryptedBody = message.getBody();
1640                        message.setBody(pgpBody); //TODO might throw NPE
1641                        message.setEncryption(Message.ENCRYPTION_PGP);
1642                        if (message.edited()) {
1643                            message.setBody(decryptedBody);
1644                            message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1645                            if (!databaseBackend.updateMessage(message, message.getEditedId())) {
1646                                Log.e(Config.LOGTAG, "error updated message in DB after edit");
1647                            }
1648                            updateConversationUi();
1649                            return;
1650                        } else {
1651                            databaseBackend.createMessage(message);
1652                            saveInDb = false;
1653                            message.setBody(decryptedBody);
1654                            message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1655                        }
1656                    }
1657                    break;
1658                case Message.ENCRYPTION_AXOLOTL:
1659                    message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1660                    break;
1661            }
1662        }
1663
1664
1665        boolean mucMessage = conversation.getMode() == Conversation.MODE_MULTI && !message.isPrivateMessage();
1666        if (mucMessage) {
1667            message.setCounterpart(conversation.getMucOptions().getSelf().getFullJid());
1668        }
1669
1670        if (resend) {
1671            if (packet != null && addToConversation) {
1672                if (account.getXmppConnection().getFeatures().sm() || mucMessage) {
1673                    markMessage(message, Message.STATUS_UNSEND);
1674                } else {
1675                    markMessage(message, Message.STATUS_SEND);
1676                }
1677            }
1678        } else {
1679            if (addToConversation) {
1680                conversation.add(message);
1681            }
1682            if (saveInDb) {
1683                databaseBackend.createMessage(message);
1684            } else if (message.edited()) {
1685                if (!databaseBackend.updateMessage(message, message.getEditedId())) {
1686                    Log.e(Config.LOGTAG, "error updated message in DB after edit");
1687                }
1688            }
1689            updateConversationUi();
1690        }
1691        if (packet != null) {
1692            if (delay) {
1693                mMessageGenerator.addDelay(packet, message.getTimeSent());
1694            }
1695            if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
1696                if (this.sendChatStates()) {
1697                    packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
1698                }
1699            }
1700            sendMessagePacket(account, packet);
1701        }
1702    }
1703
1704    private boolean isJoinInProgress(final Conversation conversation) {
1705        final Account account = conversation.getAccount();
1706        synchronized (account.inProgressConferenceJoins) {
1707            if (conversation.getMode() == Conversational.MODE_MULTI) {
1708                final boolean inProgress = account.inProgressConferenceJoins.contains(conversation);
1709                final boolean pending = account.pendingConferenceJoins.contains(conversation);
1710                final boolean inProgressJoin = inProgress || pending;
1711                if (inProgressJoin) {
1712                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": holding back message to group. inProgress=" + inProgress + ", pending=" + pending);
1713                }
1714                return inProgressJoin;
1715            } else {
1716                return false;
1717            }
1718        }
1719    }
1720
1721    private void sendUnsentMessages(final Conversation conversation) {
1722        conversation.findWaitingMessages(message -> resendMessage(message, true));
1723    }
1724
1725    public void resendMessage(final Message message, final boolean delay) {
1726        sendMessage(message, true, delay);
1727    }
1728
1729    public void requestEasyOnboardingInvite(final Account account, final EasyOnboardingInvite.OnInviteRequested callback) {
1730        final XmppConnection connection = account.getXmppConnection();
1731        final Jid jid = connection == null ? null : connection.getJidForCommand(Namespace.EASY_ONBOARDING_INVITE);
1732        if (jid == null) {
1733            callback.inviteRequestFailed(getString(R.string.server_does_not_support_easy_onboarding_invites));
1734            return;
1735        }
1736        final IqPacket request = new IqPacket(IqPacket.TYPE.SET);
1737        request.setTo(jid);
1738        final Element command = request.addChild("command", Namespace.COMMANDS);
1739        command.setAttribute("node", Namespace.EASY_ONBOARDING_INVITE);
1740        command.setAttribute("action", "execute");
1741        sendIqPacket(account, request, (a, response) -> {
1742            if (response.getType() == IqPacket.TYPE.RESULT) {
1743                final Element resultCommand = response.findChild("command", Namespace.COMMANDS);
1744                final Element x = resultCommand == null ? null : resultCommand.findChild("x", Namespace.DATA);
1745                if (x != null) {
1746                    final Data data = Data.parse(x);
1747                    final String uri = data.getValue("uri");
1748                    final String landingUrl = data.getValue("landing-url");
1749                    if (uri != null) {
1750                        final EasyOnboardingInvite invite = new EasyOnboardingInvite(jid.getDomain().toEscapedString(), uri, landingUrl);
1751                        callback.inviteRequested(invite);
1752                        return;
1753                    }
1754                }
1755                callback.inviteRequestFailed(getString(R.string.unable_to_parse_invite));
1756                Log.d(Config.LOGTAG, response.toString());
1757            } else if (response.getType() == IqPacket.TYPE.ERROR) {
1758                callback.inviteRequestFailed(IqParser.errorMessage(response));
1759            } else {
1760                callback.inviteRequestFailed(getString(R.string.remote_server_timeout));
1761            }
1762        });
1763
1764    }
1765
1766    public void fetchRosterFromServer(final Account account) {
1767        final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1768        if (!"".equals(account.getRosterVersion())) {
1769            Log.d(Config.LOGTAG, account.getJid().asBareJid()
1770                    + ": fetching roster version " + account.getRosterVersion());
1771        } else {
1772            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching roster");
1773        }
1774        iqPacket.query(Namespace.ROSTER).setAttribute("ver", account.getRosterVersion());
1775        sendIqPacket(account, iqPacket, mIqParser);
1776    }
1777
1778    public void fetchBookmarks(final Account account) {
1779        final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1780        final Element query = iqPacket.query("jabber:iq:private");
1781        query.addChild("storage", Namespace.BOOKMARKS);
1782        final OnIqPacketReceived callback = (a, response) -> {
1783            if (response.getType() == IqPacket.TYPE.RESULT) {
1784                final Element query1 = response.query();
1785                final Element storage = query1.findChild("storage", "storage:bookmarks");
1786                Map<Jid, Bookmark> bookmarks = Bookmark.parseFromStorage(storage, account);
1787                processBookmarksInitial(a, bookmarks, false);
1788            } else {
1789                Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": could not fetch bookmarks");
1790            }
1791        };
1792        sendIqPacket(account, iqPacket, callback);
1793    }
1794
1795    public void fetchBookmarks2(final Account account) {
1796        final IqPacket retrieve = mIqGenerator.retrieveBookmarks();
1797        sendIqPacket(account, retrieve, new OnIqPacketReceived() {
1798            @Override
1799            public void onIqPacketReceived(final Account account, final IqPacket response) {
1800                if (response.getType() == IqPacket.TYPE.RESULT) {
1801                    final Element pubsub = response.findChild("pubsub", Namespace.PUBSUB);
1802                    final Map<Jid, Bookmark> bookmarks = Bookmark.parseFromPubsub(pubsub, account);
1803                    processBookmarksInitial(account, bookmarks, true);
1804                }
1805            }
1806        });
1807    }
1808
1809    public void processBookmarksInitial(Account account, Map<Jid, Bookmark> bookmarks, final boolean pep) {
1810        final Set<Jid> previousBookmarks = account.getBookmarkedJids();
1811        final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
1812        for (Bookmark bookmark : bookmarks.values()) {
1813            previousBookmarks.remove(bookmark.getJid().asBareJid());
1814            processModifiedBookmark(bookmark, pep, synchronizeWithBookmarks);
1815        }
1816        if (pep && synchronizeWithBookmarks) {
1817            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + previousBookmarks.size() + " bookmarks have been removed");
1818            for (Jid jid : previousBookmarks) {
1819                processDeletedBookmark(account, jid);
1820            }
1821        }
1822        account.setBookmarks(bookmarks);
1823    }
1824
1825    public void processDeletedBookmark(Account account, Jid jid) {
1826        final Conversation conversation = find(account, jid);
1827        if (conversation != null && conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
1828            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving destroyed conference (" + conversation.getJid() + ") after receiving pep");
1829            archiveConversation(conversation, false);
1830        }
1831    }
1832
1833    private void processModifiedBookmark(Bookmark bookmark, final boolean pep, final boolean synchronizeWithBookmarks) {
1834        final Account account = bookmark.getAccount();
1835        Conversation conversation = find(bookmark);
1836        if (conversation != null) {
1837            if (conversation.getMode() != Conversation.MODE_MULTI) {
1838                return;
1839            }
1840            bookmark.setConversation(conversation);
1841            if (pep && synchronizeWithBookmarks && !bookmark.autojoin()) {
1842                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conference (" + conversation.getJid() + ") after receiving pep");
1843                archiveConversation(conversation, false);
1844            } else {
1845                final MucOptions mucOptions = conversation.getMucOptions();
1846                if (mucOptions.getError() == MucOptions.Error.NICK_IN_USE) {
1847                    final String current = mucOptions.getActualNick();
1848                    final String proposed = mucOptions.getProposedNick();
1849                    if (current != null && !current.equals(proposed)) {
1850                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": proposed nick changed after bookmark push " + current + "->" + proposed);
1851                        joinMuc(conversation);
1852                    }
1853                }
1854            }
1855        } else if (synchronizeWithBookmarks && bookmark.autojoin()) {
1856            conversation = findOrCreateConversation(account, bookmark.getFullJid(), true, true, false);
1857            bookmark.setConversation(conversation);
1858        }
1859    }
1860
1861    public void processModifiedBookmark(Bookmark bookmark) {
1862        final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
1863        processModifiedBookmark(bookmark, true, synchronizeWithBookmarks);
1864    }
1865
1866    public void createBookmark(final Account account, final Bookmark bookmark) {
1867        account.putBookmark(bookmark);
1868        final XmppConnection connection = account.getXmppConnection();
1869        if (connection == null) {
1870            Log.d(Config.LOGTAG, account.getJid().asBareJid()+": no connection. ignoring bookmark creation");
1871        } else if (connection.getFeatures().bookmarks2()) {
1872            final Element item = mIqGenerator.publishBookmarkItem(bookmark);
1873            pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS2, item, bookmark.getJid().asBareJid().toEscapedString(), PublishOptions.persistentWhitelistAccessMaxItems());
1874        } else if (connection.getFeatures().bookmarksConversion()) {
1875            pushBookmarksPep(account);
1876        } else {
1877            pushBookmarksPrivateXml(account);
1878        }
1879    }
1880
1881    public void deleteBookmark(final Account account, final Bookmark bookmark) {
1882        if (bookmark.getJid().toString().equals("discuss@conference.soprani.ca")) {
1883            getPreferences().edit().putBoolean("cheogram_sopranica_bookmark_deleted", true).apply();
1884        }
1885        account.removeBookmark(bookmark);
1886        final XmppConnection connection = account.getXmppConnection();
1887        if (connection.getFeatures().bookmarks2()) {
1888            IqPacket request = mIqGenerator.deleteItem(Namespace.BOOKMARKS2, bookmark.getJid().asBareJid().toEscapedString());
1889            sendIqPacket(account, request, (a, response) -> {
1890                if (response.getType() == IqPacket.TYPE.ERROR) {
1891                    Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": unable to delete bookmark " + response.getErrorCondition());
1892                }
1893            });
1894        } else if (connection.getFeatures().bookmarksConversion()) {
1895            pushBookmarksPep(account);
1896        } else {
1897            pushBookmarksPrivateXml(account);
1898        }
1899    }
1900
1901    private void pushBookmarksPrivateXml(Account account) {
1902        if (!account.areBookmarksLoaded()) return;
1903
1904        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
1905        IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1906        Element query = iqPacket.query("jabber:iq:private");
1907        Element storage = query.addChild("storage", "storage:bookmarks");
1908        for (final Bookmark bookmark : account.getBookmarks()) {
1909            storage.addChild(bookmark);
1910        }
1911        sendIqPacket(account, iqPacket, mDefaultIqHandler);
1912    }
1913
1914    private void pushBookmarksPep(Account account) {
1915        if (!account.areBookmarksLoaded()) return;
1916
1917        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
1918        final Element storage = new Element("storage", "storage:bookmarks");
1919        for (final Bookmark bookmark : account.getBookmarks()) {
1920            storage.addChild(bookmark);
1921        }
1922        pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS, storage, "current", PublishOptions.persistentWhitelistAccess());
1923
1924    }
1925
1926    private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options) {
1927        pushNodeAndEnforcePublishOptions(account, node, element, id, options, true);
1928
1929    }
1930
1931    private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options, final boolean retry) {
1932        final IqPacket packet = mIqGenerator.publishElement(node, element, id, options);
1933        sendIqPacket(account, packet, (a, response) -> {
1934            if (response.getType() == IqPacket.TYPE.RESULT) {
1935                return;
1936            }
1937            if (retry && PublishOptions.preconditionNotMet(response)) {
1938                pushNodeConfiguration(account, node, options, new OnConfigurationPushed() {
1939                    @Override
1940                    public void onPushSucceeded() {
1941                        pushNodeAndEnforcePublishOptions(account, node, element, id, options, false);
1942                    }
1943
1944                    @Override
1945                    public void onPushFailed() {
1946                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to push node configuration (" + node + ")");
1947                    }
1948                });
1949            } else {
1950                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error publishing bookmarks (retry=" + retry + ") " + response);
1951            }
1952        });
1953    }
1954
1955    private void restoreFromDatabase() {
1956        synchronized (this.conversations) {
1957            final Map<String, Account> accountLookupTable = new Hashtable<>();
1958            for (Account account : this.accounts) {
1959                accountLookupTable.put(account.getUuid(), account);
1960            }
1961            Log.d(Config.LOGTAG, "restoring conversations...");
1962            final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
1963            this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1964            for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
1965                Conversation conversation = iterator.next();
1966                Account account = accountLookupTable.get(conversation.getAccountUuid());
1967                if (account != null) {
1968                    conversation.setAccount(account);
1969                } else {
1970                    Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
1971                    iterator.remove();
1972                }
1973            }
1974            long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
1975            Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
1976            Runnable runnable = () -> {
1977                if (DatabaseBackend.requiresMessageIndexRebuild()) {
1978                    DatabaseBackend.getInstance(this).rebuildMessagesIndex();
1979                }
1980                final long deletionDate = getAutomaticMessageDeletionDate();
1981                mLastExpiryRun.set(SystemClock.elapsedRealtime());
1982                if (deletionDate > 0) {
1983                    Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
1984                    databaseBackend.expireOldMessages(deletionDate);
1985                }
1986                Log.d(Config.LOGTAG, "restoring roster...");
1987                for (final Account account : accounts) {
1988                    databaseBackend.readRoster(account.getRoster());
1989                    account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1990                }
1991                getBitmapCache().evictAll();
1992                loadPhoneContacts();
1993                Log.d(Config.LOGTAG, "restoring messages...");
1994                final long startMessageRestore = SystemClock.elapsedRealtime();
1995                final Conversation quickLoad = QuickLoader.get(this.conversations);
1996                if (quickLoad != null) {
1997                    restoreMessages(quickLoad);
1998                    updateConversationUi();
1999                    final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
2000                    Log.d(Config.LOGTAG, "quickly restored " + quickLoad.getName() + " after " + diffMessageRestore + "ms");
2001                }
2002                for (Conversation conversation : this.conversations) {
2003                    if (quickLoad != conversation) {
2004                        restoreMessages(conversation);
2005                    }
2006                }
2007                mNotificationService.finishBacklog();
2008                restoredFromDatabaseLatch.countDown();
2009                final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
2010                Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
2011                updateConversationUi();
2012            };
2013            mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
2014        }
2015    }
2016
2017    private void restoreMessages(Conversation conversation) {
2018        conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
2019        conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
2020        conversation.findUnreadMessagesAndCalls(mNotificationService::pushFromBacklog);
2021    }
2022
2023    public void loadPhoneContacts() {
2024        mContactMergerExecutor.execute(() -> {
2025            final Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
2026            Log.d(Config.LOGTAG, "start merging phone contacts with roster");
2027            for (final Account account : accounts) {
2028                final List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts(JabberIdContact.class);
2029                for (final JabberIdContact jidContact : contacts.values()) {
2030                    final Contact contact = account.getRoster().getContact(jidContact.getJid());
2031                    boolean needsCacheClean = contact.setPhoneContact(jidContact);
2032                    if (needsCacheClean) {
2033                        getAvatarService().clear(contact);
2034                    }
2035                    withSystemAccounts.remove(contact);
2036                }
2037                for (final Contact contact : withSystemAccounts) {
2038                    boolean needsCacheClean = contact.unsetPhoneContact(JabberIdContact.class);
2039                    if (needsCacheClean) {
2040                        getAvatarService().clear(contact);
2041                    }
2042                }
2043            }
2044            Log.d(Config.LOGTAG, "finished merging phone contacts");
2045            mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
2046            updateRosterUi();
2047            mQuickConversationsService.considerSync();
2048        });
2049    }
2050
2051
2052    public void syncRoster(final Account account) {
2053        mRosterSyncTaskManager.execute(account, () -> {
2054            unregisterPhoneAccounts(account);
2055            databaseBackend.writeRoster(account.getRoster());
2056            try { Thread.sleep(500); } catch (InterruptedException e) { }
2057        });
2058    }
2059
2060    public List<Conversation> getConversations() {
2061        return this.conversations;
2062    }
2063
2064    private void markFileDeleted(final File file) {
2065        synchronized (FILENAMES_TO_IGNORE_DELETION) {
2066            if (FILENAMES_TO_IGNORE_DELETION.remove(file.getAbsolutePath())) {
2067                Log.d(Config.LOGTAG, "ignored deletion of " + file.getAbsolutePath());
2068                return;
2069            }
2070        }
2071        final boolean isInternalFile = fileBackend.isInternalFile(file);
2072        final List<String> uuids = databaseBackend.markFileAsDeleted(file, isInternalFile);
2073        Log.d(Config.LOGTAG, "deleted file " + file.getAbsolutePath() + " internal=" + isInternalFile + ", database hits=" + uuids.size());
2074        markUuidsAsDeletedFiles(uuids);
2075    }
2076
2077    private void markUuidsAsDeletedFiles(List<String> uuids) {
2078        boolean deleted = false;
2079        for (Conversation conversation : getConversations()) {
2080            deleted |= conversation.markAsDeleted(uuids);
2081        }
2082        for (final String uuid : uuids) {
2083            evictPreview(uuid);
2084        }
2085        if (deleted) {
2086            updateConversationUi();
2087        }
2088    }
2089
2090    private void markChangedFiles(List<DatabaseBackend.FilePathInfo> infos) {
2091        boolean changed = false;
2092        for (Conversation conversation : getConversations()) {
2093            changed |= conversation.markAsChanged(infos);
2094        }
2095        if (changed) {
2096            updateConversationUi();
2097        }
2098    }
2099
2100    public void populateWithOrderedConversations(final List<Conversation> list) {
2101        populateWithOrderedConversations(list, true, true);
2102    }
2103
2104    public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload) {
2105        populateWithOrderedConversations(list, includeNoFileUpload, true);
2106    }
2107
2108    public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload, final boolean sort) {
2109        final List<String> orderedUuids;
2110        if (sort) {
2111            orderedUuids = null;
2112        } else {
2113            orderedUuids = new ArrayList<>();
2114            for (Conversation conversation : list) {
2115                orderedUuids.add(conversation.getUuid());
2116            }
2117        }
2118        list.clear();
2119        if (includeNoFileUpload) {
2120            list.addAll(getConversations());
2121        } else {
2122            for (Conversation conversation : getConversations()) {
2123                if (conversation.getMode() == Conversation.MODE_SINGLE
2124                        || (conversation.getAccount().httpUploadAvailable() && conversation.getMucOptions().participating())) {
2125                    list.add(conversation);
2126                }
2127            }
2128        }
2129        try {
2130            if (orderedUuids != null) {
2131                Collections.sort(list, (a, b) -> {
2132                    final int indexA = orderedUuids.indexOf(a.getUuid());
2133                    final int indexB = orderedUuids.indexOf(b.getUuid());
2134                    if (indexA == -1 || indexB == -1 || indexA == indexB) {
2135                        return a.compareTo(b);
2136                    }
2137                    return indexA - indexB;
2138                });
2139            } else {
2140                Collections.sort(list);
2141            }
2142        } catch (IllegalArgumentException e) {
2143            //ignore
2144        }
2145    }
2146
2147    public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
2148        if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
2149            return;
2150        } else if (timestamp == 0) {
2151            return;
2152        }
2153        Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
2154        final Runnable runnable = () -> {
2155            final Account account = conversation.getAccount();
2156            List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
2157            if (messages.size() > 0) {
2158                conversation.addAll(0, messages);
2159                callback.onMoreMessagesLoaded(messages.size(), conversation);
2160            } else if (conversation.hasMessagesLeftOnServer()
2161                    && account.isOnlineAndConnected()
2162                    && conversation.getLastClearHistory().getTimestamp() == 0) {
2163                final boolean mamAvailable;
2164                if (conversation.getMode() == Conversation.MODE_SINGLE) {
2165                    mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
2166                } else {
2167                    mamAvailable = conversation.getMucOptions().mamSupport();
2168                }
2169                if (mamAvailable) {
2170                    MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
2171                    if (query != null) {
2172                        query.setCallback(callback);
2173                        callback.informUser(R.string.fetching_history_from_server);
2174                    } else {
2175                        callback.informUser(R.string.not_fetching_history_retention_period);
2176                    }
2177
2178                }
2179            }
2180        };
2181        mDatabaseReaderExecutor.execute(runnable);
2182    }
2183
2184    public List<Account> getAccounts() {
2185        return this.accounts;
2186    }
2187
2188
2189    /**
2190     * 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)
2191     */
2192    public List<Conversation> findAllConferencesWith(Contact contact) {
2193        final ArrayList<Conversation> results = new ArrayList<>();
2194        for (final Conversation c : conversations) {
2195            if (c.getMode() != Conversation.MODE_MULTI) {
2196                continue;
2197            }
2198            final MucOptions mucOptions = c.getMucOptions();
2199            if (c.getJid().asBareJid().equals(contact.getJid().asBareJid()) || (mucOptions != null && mucOptions.isContactInRoom(contact))) {
2200                results.add(c);
2201            }
2202        }
2203        return results;
2204    }
2205
2206    public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
2207        for (final Conversation conversation : haystack) {
2208            if (conversation.getContact() == contact) {
2209                return conversation;
2210            }
2211        }
2212        return null;
2213    }
2214
2215    public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
2216        if (jid == null) {
2217            return null;
2218        }
2219        for (final Conversation conversation : haystack) {
2220            if ((account == null || conversation.getAccount() == account)
2221                    && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
2222                return conversation;
2223            }
2224        }
2225        return null;
2226    }
2227
2228    public boolean isConversationsListEmpty(final Conversation ignore) {
2229        synchronized (this.conversations) {
2230            final int size = this.conversations.size();
2231            return size == 0 || size == 1 && this.conversations.get(0) == ignore;
2232        }
2233    }
2234
2235    public boolean isConversationStillOpen(final Conversation conversation) {
2236        synchronized (this.conversations) {
2237            for (Conversation current : this.conversations) {
2238                if (current == conversation) {
2239                    return true;
2240                }
2241            }
2242        }
2243        return false;
2244    }
2245
2246    public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
2247        return this.findOrCreateConversation(account, jid, muc, false, async);
2248    }
2249
2250    public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
2251        return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
2252    }
2253
2254    public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
2255        synchronized (this.conversations) {
2256            Conversation conversation = find(account, jid);
2257            if (conversation != null) {
2258                return conversation;
2259            }
2260            conversation = databaseBackend.findConversation(account, jid);
2261            final boolean loadMessagesFromDb;
2262            if (conversation != null) {
2263                conversation.setStatus(Conversation.STATUS_AVAILABLE);
2264                conversation.setAccount(account);
2265                if (muc) {
2266                    conversation.setMode(Conversation.MODE_MULTI);
2267                    conversation.setContactJid(jid);
2268                } else {
2269                    conversation.setMode(Conversation.MODE_SINGLE);
2270                    conversation.setContactJid(jid.asBareJid());
2271                }
2272                databaseBackend.updateConversation(conversation);
2273                loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
2274            } else {
2275                String conversationName;
2276                Contact contact = account.getRoster().getContact(jid);
2277                if (contact != null) {
2278                    conversationName = contact.getDisplayName();
2279                } else {
2280                    conversationName = jid.getLocal();
2281                }
2282                if (muc) {
2283                    conversation = new Conversation(conversationName, account, jid,
2284                            Conversation.MODE_MULTI);
2285                } else {
2286                    conversation = new Conversation(conversationName, account, jid.asBareJid(),
2287                            Conversation.MODE_SINGLE);
2288                }
2289                this.databaseBackend.createConversation(conversation);
2290                loadMessagesFromDb = false;
2291            }
2292            final Conversation c = conversation;
2293            final Runnable runnable = () -> {
2294                if (loadMessagesFromDb) {
2295                    c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
2296                    updateConversationUi();
2297                    c.messagesLoaded.set(true);
2298                }
2299                if (account.getXmppConnection() != null
2300                        && !c.getContact().isBlocked()
2301                        && account.getXmppConnection().getFeatures().mam()
2302                        && !muc) {
2303                    if (query == null) {
2304                        mMessageArchiveService.query(c);
2305                    } else {
2306                        if (query.getConversation() == null) {
2307                            mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
2308                        }
2309                    }
2310                }
2311                if (joinAfterCreate) {
2312                    joinMuc(c);
2313                }
2314            };
2315            if (async) {
2316                mDatabaseReaderExecutor.execute(runnable);
2317            } else {
2318                runnable.run();
2319            }
2320            this.conversations.add(conversation);
2321            updateConversationUi();
2322            return conversation;
2323        }
2324    }
2325
2326    public void archiveConversation(Conversation conversation) {
2327        archiveConversation(conversation, true);
2328    }
2329
2330    private void archiveConversation(Conversation conversation, final boolean maySynchronizeWithBookmarks) {
2331        getNotificationService().clear(conversation);
2332        conversation.setStatus(Conversation.STATUS_ARCHIVED);
2333        conversation.setNextMessage(null);
2334        synchronized (this.conversations) {
2335            getMessageArchiveService().kill(conversation);
2336            if (conversation.getMode() == Conversation.MODE_MULTI) {
2337                if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2338                    final Bookmark bookmark = conversation.getBookmark();
2339                    if (maySynchronizeWithBookmarks && bookmark != null && synchronizeWithBookmarks()) {
2340                        if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2341                            Account account = bookmark.getAccount();
2342                            bookmark.setConversation(null);
2343                            deleteBookmark(account, bookmark);
2344                        } else if (bookmark.autojoin()) {
2345                            bookmark.setAutojoin(false);
2346                            createBookmark(bookmark.getAccount(), bookmark);
2347                        }
2348                    }
2349                }
2350                leaveMuc(conversation);
2351            } else {
2352                if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2353                    stopPresenceUpdatesTo(conversation.getContact());
2354                }
2355            }
2356            updateConversation(conversation);
2357            this.conversations.remove(conversation);
2358            updateConversationUi();
2359        }
2360    }
2361
2362    public void stopPresenceUpdatesTo(Contact contact) {
2363        Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
2364        sendPresencePacket(contact.getAccount(), mPresenceGenerator.stopPresenceUpdatesTo(contact));
2365        contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2366    }
2367
2368    public void createAccount(final Account account) {
2369        account.initAccountServices(this);
2370        databaseBackend.createAccount(account);
2371        this.accounts.add(account);
2372        this.reconnectAccountInBackground(account);
2373        updateAccountUi();
2374        syncEnabledAccountSetting();
2375        toggleForegroundService();
2376    }
2377
2378    private void syncEnabledAccountSetting() {
2379        final boolean hasEnabledAccounts = hasEnabledAccounts();
2380        getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
2381        toggleSetProfilePictureActivity(hasEnabledAccounts);
2382    }
2383
2384    private void toggleSetProfilePictureActivity(final boolean enabled) {
2385        try {
2386            final ComponentName name = new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
2387            final int targetState = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
2388            getPackageManager().setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
2389        } catch (IllegalStateException e) {
2390            Log.d(Config.LOGTAG, "unable to toggle profile picture actvitiy");
2391        }
2392    }
2393
2394    private void provisionAccount(final String address, final String password) {
2395        final Jid jid = Jid.ofEscaped(address);
2396        final Account account = new Account(jid, password);
2397        account.setOption(Account.OPTION_DISABLED, true);
2398        Log.d(Config.LOGTAG, jid.asBareJid().toEscapedString() + ": provisioning account");
2399        createAccount(account);
2400    }
2401
2402    public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
2403        new Thread(() -> {
2404            try {
2405                final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
2406                final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
2407                if (cert == null) {
2408                    callback.informUser(R.string.unable_to_parse_certificate);
2409                    return;
2410                }
2411                Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
2412                if (info == null) {
2413                    callback.informUser(R.string.certificate_does_not_contain_jid);
2414                    return;
2415                }
2416                if (findAccountByJid(info.first) == null) {
2417                    final Account account = new Account(info.first, "");
2418                    account.setPrivateKeyAlias(alias);
2419                    account.setOption(Account.OPTION_DISABLED, true);
2420                    account.setOption(Account.OPTION_FIXED_USERNAME, true);
2421                    account.setDisplayName(info.second);
2422                    createAccount(account);
2423                    callback.onAccountCreated(account);
2424                    if (Config.X509_VERIFICATION) {
2425                        try {
2426                            getMemorizingTrustManager().getNonInteractive(account.getServer()).checkClientTrusted(chain, "RSA");
2427                        } catch (CertificateException e) {
2428                            callback.informUser(R.string.certificate_chain_is_not_trusted);
2429                        }
2430                    }
2431                } else {
2432                    callback.informUser(R.string.account_already_exists);
2433                }
2434            } catch (Exception e) {
2435                callback.informUser(R.string.unable_to_parse_certificate);
2436            }
2437        }).start();
2438
2439    }
2440
2441    public void updateKeyInAccount(final Account account, final String alias) {
2442        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
2443        try {
2444            X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
2445            Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
2446            Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
2447            if (info == null) {
2448                showErrorToastInUi(R.string.certificate_does_not_contain_jid);
2449                return;
2450            }
2451            if (account.getJid().asBareJid().equals(info.first)) {
2452                account.setPrivateKeyAlias(alias);
2453                account.setDisplayName(info.second);
2454                databaseBackend.updateAccount(account);
2455                if (Config.X509_VERIFICATION) {
2456                    try {
2457                        getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
2458                    } catch (CertificateException e) {
2459                        showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
2460                    }
2461                    account.getAxolotlService().regenerateKeys(true);
2462                }
2463            } else {
2464                showErrorToastInUi(R.string.jid_does_not_match_certificate);
2465            }
2466        } catch (Exception e) {
2467            e.printStackTrace();
2468        }
2469    }
2470
2471    public boolean updateAccount(final Account account) {
2472        if (databaseBackend.updateAccount(account)) {
2473            account.setShowErrorNotification(true);
2474            this.statusListener.onStatusChanged(account);
2475            databaseBackend.updateAccount(account);
2476            reconnectAccountInBackground(account);
2477            updateAccountUi();
2478            getNotificationService().updateErrorNotification();
2479            toggleForegroundService();
2480            syncEnabledAccountSetting();
2481            mChannelDiscoveryService.cleanCache();
2482            return true;
2483        } else {
2484            return false;
2485        }
2486    }
2487
2488    public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
2489        final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
2490        sendIqPacket(account, iq, (a, packet) -> {
2491            if (packet.getType() == IqPacket.TYPE.RESULT) {
2492                a.setPassword(newPassword);
2493                a.setOption(Account.OPTION_MAGIC_CREATE, false);
2494                databaseBackend.updateAccount(a);
2495                callback.onPasswordChangeSucceeded();
2496            } else {
2497                callback.onPasswordChangeFailed();
2498            }
2499        });
2500    }
2501
2502    public void deleteAccount(final Account account) {
2503        final boolean connected = account.getStatus() == Account.State.ONLINE;
2504        synchronized (this.conversations) {
2505            if (connected) {
2506                account.getAxolotlService().deleteOmemoIdentity();
2507            }
2508            for (final Conversation conversation : conversations) {
2509                if (conversation.getAccount() == account) {
2510                    if (conversation.getMode() == Conversation.MODE_MULTI) {
2511                        if (connected) {
2512                            leaveMuc(conversation);
2513                        }
2514                    }
2515                    conversations.remove(conversation);
2516                    mNotificationService.clear(conversation);
2517                }
2518            }
2519            new Thread(() -> {
2520                for (final Contact contact : account.getRoster().getContacts()) {
2521                    contact.unregisterAsPhoneAccount(this);
2522                }
2523            }).start();
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    protected void unregisterPhoneAccounts(final Account account) {
3608        for (final Contact contact : account.getRoster().getContacts()) {
3609            if (!contact.showInRoster()) {
3610                contact.unregisterAsPhoneAccount(this);
3611            }
3612        }
3613    }
3614
3615    public void createContact(final Contact contact, final boolean autoGrant) {
3616        createContact(contact, autoGrant, null);
3617    }
3618
3619    public void createContact(final Contact contact, final boolean autoGrant, final String preAuth) {
3620        if (autoGrant) {
3621            contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
3622            contact.setOption(Contact.Options.ASKING);
3623        }
3624        pushContactToServer(contact, preAuth);
3625    }
3626
3627    public void pushContactToServer(final Contact contact) {
3628        pushContactToServer(contact, null);
3629    }
3630
3631    private void pushContactToServer(final Contact contact, final String preAuth) {
3632        contact.resetOption(Contact.Options.DIRTY_DELETE);
3633        contact.setOption(Contact.Options.DIRTY_PUSH);
3634        final Account account = contact.getAccount();
3635        if (account.getStatus() == Account.State.ONLINE) {
3636            final boolean ask = contact.getOption(Contact.Options.ASKING);
3637            final boolean sendUpdates = contact
3638                    .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
3639                    && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
3640            final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3641            iq.query(Namespace.ROSTER).addChild(contact.asElement());
3642            account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3643            if (sendUpdates) {
3644                sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
3645            }
3646            if (ask) {
3647                sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact, preAuth));
3648            }
3649        } else {
3650            syncRoster(contact.getAccount());
3651        }
3652    }
3653
3654    public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
3655        new Thread(() -> {
3656            final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3657            final int size = Config.AVATAR_SIZE;
3658            final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3659            if (avatar != null) {
3660                if (!getFileBackend().save(avatar)) {
3661                    callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3662                    return;
3663                }
3664                avatar.owner = conversation.getJid().asBareJid();
3665                publishMucAvatar(conversation, avatar, callback);
3666            } else {
3667                callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3668            }
3669        }).start();
3670    }
3671
3672    public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
3673        new Thread(() -> {
3674            final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3675            final int size = Config.AVATAR_SIZE;
3676            final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3677            if (avatar != null) {
3678                if (!getFileBackend().save(avatar)) {
3679                    Log.d(Config.LOGTAG, "unable to save vcard");
3680                    callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3681                    return;
3682                }
3683                publishAvatar(account, avatar, callback);
3684            } else {
3685                callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3686            }
3687        }).start();
3688
3689    }
3690
3691    private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
3692        final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
3693        sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
3694            boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
3695            if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
3696                Element vcard = response.findChild("vCard", "vcard-temp");
3697                if (vcard == null) {
3698                    vcard = new Element("vCard", "vcard-temp");
3699                }
3700                Element photo = vcard.findChild("PHOTO");
3701                if (photo == null) {
3702                    photo = vcard.addChild("PHOTO");
3703                }
3704                photo.clearChildren();
3705                photo.addChild("TYPE").setContent(avatar.type);
3706                photo.addChild("BINVAL").setContent(avatar.image);
3707                IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3708                publication.setTo(conversation.getJid().asBareJid());
3709                publication.addChild(vcard);
3710                sendIqPacket(account, publication, (a1, publicationResponse) -> {
3711                    if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3712                        callback.onAvatarPublicationSucceeded();
3713                    } else {
3714                        Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
3715                        callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3716                    }
3717                });
3718            } else {
3719                Log.d(Config.LOGTAG, "failed to request vcard " + response.toString());
3720                callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
3721            }
3722        });
3723    }
3724
3725    public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
3726        final Bundle options;
3727        if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
3728            options = PublishOptions.openAccess();
3729        } else {
3730            options = null;
3731        }
3732        publishAvatar(account, avatar, options, true, callback);
3733    }
3734
3735    public void publishAvatar(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3736        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": publishing avatar. options=" + options);
3737        IqPacket packet = this.mIqGenerator.publishAvatar(avatar, options);
3738        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3739
3740            @Override
3741            public void onIqPacketReceived(Account account, IqPacket result) {
3742                if (result.getType() == IqPacket.TYPE.RESULT) {
3743                    publishAvatarMetadata(account, avatar, options, true, callback);
3744                } else if (retry && PublishOptions.preconditionNotMet(result)) {
3745                    pushNodeConfiguration(account, Namespace.AVATAR_DATA, options, new OnConfigurationPushed() {
3746                        @Override
3747                        public void onPushSucceeded() {
3748                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar node");
3749                            publishAvatar(account, avatar, options, false, callback);
3750                        }
3751
3752                        @Override
3753                        public void onPushFailed() {
3754                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar node");
3755                            publishAvatar(account, avatar, null, false, callback);
3756                        }
3757                    });
3758                } else {
3759                    Element error = result.findChild("error");
3760                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
3761                    if (callback != null) {
3762                        callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3763                    }
3764                }
3765            }
3766        });
3767    }
3768
3769    public void publishAvatarMetadata(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3770        final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
3771        sendIqPacket(account, packet, new OnIqPacketReceived() {
3772            @Override
3773            public void onIqPacketReceived(Account account, IqPacket result) {
3774                if (result.getType() == IqPacket.TYPE.RESULT) {
3775                    if (account.setAvatar(avatar.getFilename())) {
3776                        getAvatarService().clear(account);
3777                        databaseBackend.updateAccount(account);
3778                        notifyAccountAvatarHasChanged(account);
3779                    }
3780                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
3781                    if (callback != null) {
3782                        callback.onAvatarPublicationSucceeded();
3783                    }
3784                } else if (retry && PublishOptions.preconditionNotMet(result)) {
3785                    pushNodeConfiguration(account, Namespace.AVATAR_METADATA, options, new OnConfigurationPushed() {
3786                        @Override
3787                        public void onPushSucceeded() {
3788                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar meta data node");
3789                            publishAvatarMetadata(account, avatar, options, false, callback);
3790                        }
3791
3792                        @Override
3793                        public void onPushFailed() {
3794                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar meta data node");
3795                            publishAvatarMetadata(account, avatar, null, false, callback);
3796                        }
3797                    });
3798                } else {
3799                    if (callback != null) {
3800                        callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3801                    }
3802                }
3803            }
3804        });
3805    }
3806
3807    public void republishAvatarIfNeeded(Account account) {
3808        if (account.getAxolotlService().isPepBroken()) {
3809            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
3810            return;
3811        }
3812        IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3813        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3814
3815            private Avatar parseAvatar(IqPacket packet) {
3816                Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3817                if (pubsub != null) {
3818                    Element items = pubsub.findChild("items");
3819                    if (items != null) {
3820                        return Avatar.parseMetadata(items);
3821                    }
3822                }
3823                return null;
3824            }
3825
3826            private boolean errorIsItemNotFound(IqPacket packet) {
3827                Element error = packet.findChild("error");
3828                return packet.getType() == IqPacket.TYPE.ERROR
3829                        && error != null
3830                        && error.hasChild("item-not-found");
3831            }
3832
3833            @Override
3834            public void onIqPacketReceived(Account account, IqPacket packet) {
3835                if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
3836                    Avatar serverAvatar = parseAvatar(packet);
3837                    if (serverAvatar == null && account.getAvatar() != null) {
3838                        Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
3839                        if (avatar != null) {
3840                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
3841                            publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
3842                        } else {
3843                            Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
3844                        }
3845                    }
3846                }
3847            }
3848        });
3849    }
3850
3851    public void fetchAvatar(Account account, Avatar avatar) {
3852        fetchAvatar(account, avatar, null);
3853    }
3854
3855    public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3856        final String KEY = generateFetchKey(account, avatar);
3857        synchronized (this.mInProgressAvatarFetches) {
3858            if (mInProgressAvatarFetches.add(KEY)) {
3859                switch (avatar.origin) {
3860                    case PEP:
3861                        this.mInProgressAvatarFetches.add(KEY);
3862                        fetchAvatarPep(account, avatar, callback);
3863                        break;
3864                    case VCARD:
3865                        this.mInProgressAvatarFetches.add(KEY);
3866                        fetchAvatarVcard(account, avatar, callback);
3867                        break;
3868                }
3869            } else if (avatar.origin == Avatar.Origin.PEP) {
3870                mOmittedPepAvatarFetches.add(KEY);
3871            } else {
3872                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": already fetching " + avatar.origin + " avatar for " + avatar.owner);
3873            }
3874        }
3875    }
3876
3877    private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3878        IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
3879        sendIqPacket(account, packet, (a, result) -> {
3880            synchronized (mInProgressAvatarFetches) {
3881                mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
3882            }
3883            final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
3884            if (result.getType() == IqPacket.TYPE.RESULT) {
3885                avatar.image = mIqParser.avatarData(result);
3886                if (avatar.image != null) {
3887                    if (getFileBackend().save(avatar)) {
3888                        if (a.getJid().asBareJid().equals(avatar.owner)) {
3889                            if (a.setAvatar(avatar.getFilename())) {
3890                                databaseBackend.updateAccount(a);
3891                            }
3892                            getAvatarService().clear(a);
3893                            updateConversationUi();
3894                            updateAccountUi();
3895                        } else {
3896                            final Contact contact = a.getRoster().getContact(avatar.owner);
3897                            contact.setAvatar(avatar);
3898                            syncRoster(account);
3899                            getAvatarService().clear(contact);
3900                            updateConversationUi();
3901                            updateRosterUi();
3902                        }
3903                        if (callback != null) {
3904                            callback.success(avatar);
3905                        }
3906                        Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": successfully fetched pep avatar for " + avatar.owner);
3907                        return;
3908                    }
3909                } else {
3910
3911                    Log.d(Config.LOGTAG, ERROR + "(parsing error)");
3912                }
3913            } else {
3914                Element error = result.findChild("error");
3915                if (error == null) {
3916                    Log.d(Config.LOGTAG, ERROR + "(server error)");
3917                } else {
3918                    Log.d(Config.LOGTAG, ERROR + error.toString());
3919                }
3920            }
3921            if (callback != null) {
3922                callback.error(0, null);
3923            }
3924
3925        });
3926    }
3927
3928    private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3929        IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
3930        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3931            @Override
3932            public void onIqPacketReceived(Account account, IqPacket packet) {
3933                final boolean previouslyOmittedPepFetch;
3934                synchronized (mInProgressAvatarFetches) {
3935                    final String KEY = generateFetchKey(account, avatar);
3936                    mInProgressAvatarFetches.remove(KEY);
3937                    previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
3938                }
3939                if (packet.getType() == IqPacket.TYPE.RESULT) {
3940                    Element vCard = packet.findChild("vCard", "vcard-temp");
3941                    Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
3942                    String image = photo != null ? photo.findChildContent("BINVAL") : null;
3943                    if (image != null) {
3944                        avatar.image = image;
3945                        if (getFileBackend().save(avatar)) {
3946                            Log.d(Config.LOGTAG, account.getJid().asBareJid()
3947                                    + ": successfully fetched vCard avatar for " + avatar.owner + " omittedPep=" + previouslyOmittedPepFetch);
3948                            if (avatar.owner.isBareJid()) {
3949                                if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
3950                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
3951                                    account.setAvatar(avatar.getFilename());
3952                                    databaseBackend.updateAccount(account);
3953                                    getAvatarService().clear(account);
3954                                    updateAccountUi();
3955                                } else {
3956                                    final Contact contact = account.getRoster().getContact(avatar.owner);
3957                                    contact.setAvatar(avatar, previouslyOmittedPepFetch);
3958                                    syncRoster(account);
3959                                    getAvatarService().clear(contact);
3960                                    updateRosterUi();
3961                                }
3962                                updateConversationUi();
3963                            } else {
3964                                Conversation conversation = find(account, avatar.owner.asBareJid());
3965                                if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
3966                                    MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
3967                                    if (user != null) {
3968                                        if (user.setAvatar(avatar)) {
3969                                            getAvatarService().clear(user);
3970                                            updateConversationUi();
3971                                            updateMucRosterUi();
3972                                        }
3973                                        if (user.getRealJid() != null) {
3974                                            Contact contact = account.getRoster().getContact(user.getRealJid());
3975                                            contact.setAvatar(avatar);
3976                                            syncRoster(account);
3977                                            getAvatarService().clear(contact);
3978                                            updateRosterUi();
3979                                        }
3980                                    }
3981                                }
3982                            }
3983                        }
3984                    }
3985                }
3986            }
3987        });
3988    }
3989
3990    public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
3991        IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3992        this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3993
3994            @Override
3995            public void onIqPacketReceived(Account account, IqPacket packet) {
3996                if (packet.getType() == IqPacket.TYPE.RESULT) {
3997                    Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3998                    if (pubsub != null) {
3999                        Element items = pubsub.findChild("items");
4000                        if (items != null) {
4001                            Avatar avatar = Avatar.parseMetadata(items);
4002                            if (avatar != null) {
4003                                avatar.owner = account.getJid().asBareJid();
4004                                if (fileBackend.isAvatarCached(avatar)) {
4005                                    if (account.setAvatar(avatar.getFilename())) {
4006                                        databaseBackend.updateAccount(account);
4007                                    }
4008                                    getAvatarService().clear(account);
4009                                    callback.success(avatar);
4010                                } else {
4011                                    fetchAvatarPep(account, avatar, callback);
4012                                }
4013                                return;
4014                            }
4015                        }
4016                    }
4017                }
4018                callback.error(0, null);
4019            }
4020        });
4021    }
4022
4023    public void notifyAccountAvatarHasChanged(final Account account) {
4024        final XmppConnection connection = account.getXmppConnection();
4025        if (connection != null && connection.getFeatures().bookmarksConversion()) {
4026            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar changed. resending presence to online group chats");
4027            for (Conversation conversation : conversations) {
4028                if (conversation.getAccount() == account && conversation.getMode() == Conversational.MODE_MULTI) {
4029                    final MucOptions mucOptions = conversation.getMucOptions();
4030                    if (mucOptions.online()) {
4031                        PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous());
4032                        packet.setTo(mucOptions.getSelf().getFullJid());
4033                        connection.sendPresencePacket(packet);
4034                    }
4035                }
4036            }
4037        }
4038    }
4039
4040    public void deleteContactOnServer(Contact contact) {
4041        contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
4042        contact.resetOption(Contact.Options.DIRTY_PUSH);
4043        contact.setOption(Contact.Options.DIRTY_DELETE);
4044        Account account = contact.getAccount();
4045        if (account.getStatus() == Account.State.ONLINE) {
4046            IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
4047            Element item = iq.query(Namespace.ROSTER).addChild("item");
4048            item.setAttribute("jid", contact.getJid());
4049            item.setAttribute("subscription", "remove");
4050            account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
4051        }
4052    }
4053
4054    public void updateConversation(final Conversation conversation) {
4055        mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
4056    }
4057
4058    private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
4059        synchronized (account) {
4060            XmppConnection connection = account.getXmppConnection();
4061            if (connection == null) {
4062                connection = createConnection(account);
4063                account.setXmppConnection(connection);
4064            }
4065            boolean hasInternet = hasInternetConnection();
4066            if (account.isEnabled() && hasInternet) {
4067                if (!force) {
4068                    disconnect(account, false);
4069                }
4070                Thread thread = new Thread(connection);
4071                connection.setInteractive(interactive);
4072                connection.prepareNewConnection();
4073                connection.interrupt();
4074                thread.start();
4075                scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
4076            } else {
4077                disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
4078                account.getRoster().clearPresences();
4079                connection.resetEverything();
4080                final AxolotlService axolotlService = account.getAxolotlService();
4081                if (axolotlService != null) {
4082                    axolotlService.resetBrokenness();
4083                }
4084                if (!hasInternet) {
4085                    account.setStatus(Account.State.NO_INTERNET);
4086                }
4087            }
4088        }
4089    }
4090
4091    public void reconnectAccountInBackground(final Account account) {
4092        new Thread(() -> reconnectAccount(account, false, true)).start();
4093    }
4094
4095    public void invite(final Conversation conversation, final Jid contact) {
4096        Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
4097        final MucOptions.User user = conversation.getMucOptions().findUserByRealJid(contact.asBareJid());
4098        if (user == null || user.getAffiliation() == MucOptions.Affiliation.OUTCAST) {
4099            changeAffiliationInConference(conversation, contact, MucOptions.Affiliation.NONE, null);
4100        }
4101        final MessagePacket packet = mMessageGenerator.invite(conversation, contact);
4102        sendMessagePacket(conversation.getAccount(), packet);
4103    }
4104
4105    public void directInvite(Conversation conversation, Jid jid) {
4106        MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
4107        sendMessagePacket(conversation.getAccount(), packet);
4108    }
4109
4110    public void resetSendingToWaiting(Account account) {
4111        for (Conversation conversation : getConversations()) {
4112            if (conversation.getAccount() == account) {
4113                conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
4114            }
4115        }
4116    }
4117
4118    public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
4119        return markMessage(account, recipient, uuid, status, null);
4120    }
4121
4122    public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
4123        if (uuid == null) {
4124            return null;
4125        }
4126        for (Conversation conversation : getConversations()) {
4127            if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
4128                final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
4129                if (message != null) {
4130                    markMessage(message, status, errorMessage);
4131                }
4132                return message;
4133            }
4134        }
4135        return null;
4136    }
4137
4138    public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId) {
4139        return markMessage(conversation, uuid, status, serverMessageId, null);
4140    }
4141
4142    public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId, final LocalizedContent body) {
4143        if (uuid == null) {
4144            return false;
4145        } else {
4146            final Message message = conversation.findSentMessageWithUuid(uuid);
4147            if (message != null) {
4148                if (message.getServerMsgId() == null) {
4149                    message.setServerMsgId(serverMessageId);
4150                }
4151                if (message.getEncryption() == Message.ENCRYPTION_NONE
4152                        && message.isTypeText()
4153                        && isBodyModified(message, body)) {
4154                    message.setBody(body.content);
4155                    if (body.count > 1) {
4156                        message.setBodyLanguage(body.language);
4157                    }
4158                    markMessage(message, status, null, true);
4159                } else {
4160                    markMessage(message, status);
4161                }
4162                return true;
4163            } else {
4164                return false;
4165            }
4166        }
4167    }
4168
4169    private static boolean isBodyModified(final Message message, final LocalizedContent body) {
4170        if (body == null || body.content == null) {
4171            return false;
4172        }
4173        return !body.content.equals(message.getBody());
4174    }
4175
4176    public void markMessage(Message message, int status) {
4177        markMessage(message, status, null);
4178    }
4179
4180
4181    public void markMessage(final Message message, final int status, final String errorMessage) {
4182        markMessage(message, status, errorMessage, false);
4183    }
4184
4185    public void markMessage(final Message message, final int status, final String errorMessage, final boolean includeBody) {
4186        final int oldStatus = message.getStatus();
4187        if (status == Message.STATUS_SEND_FAILED && (oldStatus == Message.STATUS_SEND_RECEIVED || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
4188            return;
4189        }
4190        if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
4191            return;
4192        }
4193        message.setErrorMessage(errorMessage);
4194        message.setStatus(status);
4195        databaseBackend.updateMessage(message, includeBody);
4196        updateConversationUi();
4197        if (oldStatus != status && status == Message.STATUS_SEND_FAILED) {
4198            mNotificationService.pushFailedDelivery(message);
4199        }
4200    }
4201
4202    public SharedPreferences getPreferences() {
4203        return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
4204    }
4205
4206    public long getAutomaticMessageDeletionDate() {
4207        final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
4208        return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
4209    }
4210
4211    public long getLongPreference(String name, @IntegerRes int res) {
4212        long defaultValue = getResources().getInteger(res);
4213        try {
4214            return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
4215        } catch (NumberFormatException e) {
4216            return defaultValue;
4217        }
4218    }
4219
4220    public boolean getBooleanPreference(String name, @BoolRes int res) {
4221        return getPreferences().getBoolean(name, getResources().getBoolean(res));
4222    }
4223
4224    public boolean confirmMessages() {
4225        return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
4226    }
4227
4228    public boolean allowMessageCorrection() {
4229        return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
4230    }
4231
4232    public boolean sendChatStates() {
4233        return getBooleanPreference("chat_states", R.bool.chat_states);
4234    }
4235
4236    private boolean synchronizeWithBookmarks() {
4237        return getBooleanPreference("autojoin", R.bool.autojoin);
4238    }
4239
4240    public boolean useTorToConnect() {
4241        return getBooleanPreference("use_tor", R.bool.use_tor);
4242    }
4243
4244    public boolean showExtendedConnectionOptions() {
4245        return getBooleanPreference("show_connection_options", R.bool.show_connection_options);
4246    }
4247
4248    public boolean broadcastLastActivity() {
4249        return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
4250    }
4251
4252    public int unreadCount() {
4253        int count = 0;
4254        for (Conversation conversation : getConversations()) {
4255            count += conversation.unreadCount();
4256        }
4257        return count;
4258    }
4259
4260
4261    private <T> List<T> threadSafeList(Set<T> set) {
4262        synchronized (LISTENER_LOCK) {
4263            return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
4264        }
4265    }
4266
4267    public void showErrorToastInUi(int resId) {
4268        for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
4269            listener.onShowErrorToast(resId);
4270        }
4271    }
4272
4273    public void updateConversationUi() {
4274        for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
4275            listener.onConversationUpdate();
4276        }
4277    }
4278
4279    public void notifyJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state) {
4280        for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4281            listener.onJingleRtpConnectionUpdate(account, with, sessionId, state);
4282        }
4283    }
4284
4285    public void notifyJingleRtpConnectionUpdate(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
4286        for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4287            listener.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
4288        }
4289    }
4290
4291    public void updateAccountUi() {
4292        for (final OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
4293            listener.onAccountUpdate();
4294        }
4295    }
4296
4297    public void updateRosterUi() {
4298        for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
4299            listener.onRosterUpdate();
4300        }
4301    }
4302
4303    public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
4304        if (mOnCaptchaRequested.size() > 0) {
4305            DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
4306            Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
4307                    (int) (captcha.getHeight() * metrics.scaledDensity), false);
4308            for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
4309                listener.onCaptchaRequested(account, id, data, scaled);
4310            }
4311            return true;
4312        }
4313        return false;
4314    }
4315
4316    public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
4317        for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
4318            listener.OnUpdateBlocklist(status);
4319        }
4320    }
4321
4322    public void updateMucRosterUi() {
4323        for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
4324            listener.onMucRosterUpdate();
4325        }
4326    }
4327
4328    public void keyStatusUpdated(AxolotlService.FetchStatus report) {
4329        for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
4330            listener.onKeyStatusUpdated(report);
4331        }
4332    }
4333
4334    public Account findAccountByJid(final Jid jid) {
4335        for (final Account account : this.accounts) {
4336            if (account.getJid().asBareJid().equals(jid.asBareJid())) {
4337                return account;
4338            }
4339        }
4340        return null;
4341    }
4342
4343    public Account findAccountByUuid(final String uuid) {
4344        for (Account account : this.accounts) {
4345            if (account.getUuid().equals(uuid)) {
4346                return account;
4347            }
4348        }
4349        return null;
4350    }
4351
4352    public Conversation findConversationByUuid(String uuid) {
4353        for (Conversation conversation : getConversations()) {
4354            if (conversation.getUuid().equals(uuid)) {
4355                return conversation;
4356            }
4357        }
4358        return null;
4359    }
4360
4361    public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
4362        List<Conversation> findings = new ArrayList<>();
4363        for (Conversation c : getConversations()) {
4364            if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
4365                findings.add(c);
4366            }
4367        }
4368        return findings.size() == 1 ? findings.get(0) : null;
4369    }
4370
4371    public boolean markRead(final Conversation conversation, boolean dismiss) {
4372        return markRead(conversation, null, dismiss).size() > 0;
4373    }
4374
4375    public void markRead(final Conversation conversation) {
4376        markRead(conversation, null, true);
4377    }
4378
4379    public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
4380        if (dismiss) {
4381            mNotificationService.clear(conversation);
4382        }
4383        final List<Message> readMessages = conversation.markRead(upToUuid);
4384        if (readMessages.size() > 0) {
4385            Runnable runnable = () -> {
4386                for (Message message : readMessages) {
4387                    databaseBackend.updateMessage(message, false);
4388                }
4389            };
4390            mDatabaseWriterExecutor.execute(runnable);
4391            updateConversationUi();
4392            updateUnreadCountBadge();
4393            return readMessages;
4394        } else {
4395            return readMessages;
4396        }
4397    }
4398
4399    public synchronized void updateUnreadCountBadge() {
4400        int count = unreadCount();
4401        if (unreadCount != count) {
4402            Log.d(Config.LOGTAG, "update unread count to " + count);
4403            if (count > 0) {
4404                ShortcutBadger.applyCount(getApplicationContext(), count);
4405            } else {
4406                ShortcutBadger.removeCount(getApplicationContext());
4407            }
4408            unreadCount = count;
4409        }
4410    }
4411
4412    public void sendReadMarker(final Conversation conversation, String upToUuid) {
4413        final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
4414        final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
4415        if (readMessages.size() > 0) {
4416            updateConversationUi();
4417        }
4418        final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
4419        if (confirmMessages()
4420                && markable != null
4421                && (markable.trusted() || isPrivateAndNonAnonymousMuc)
4422                && markable.getRemoteMsgId() != null) {
4423            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
4424            final Account account = conversation.getAccount();
4425            final MessagePacket packet = mMessageGenerator.confirm(markable);
4426            this.sendMessagePacket(account, packet);
4427        }
4428    }
4429
4430    public MemorizingTrustManager getMemorizingTrustManager() {
4431        return this.mMemorizingTrustManager;
4432    }
4433
4434    public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
4435        this.mMemorizingTrustManager = trustManager;
4436    }
4437
4438    public void updateMemorizingTrustmanager() {
4439        final MemorizingTrustManager tm;
4440        final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
4441        if (dontTrustSystemCAs) {
4442            tm = new MemorizingTrustManager(getApplicationContext(), null);
4443        } else {
4444            tm = new MemorizingTrustManager(getApplicationContext());
4445        }
4446        setMemorizingTrustManager(tm);
4447    }
4448
4449    public LruCache<String, Bitmap> getBitmapCache() {
4450        return this.mBitmapCache;
4451    }
4452
4453    public LruCache<String, Drawable> getDrawableCache() {
4454        return this.mDrawableCache;
4455    }
4456
4457    public Collection<String> getKnownHosts() {
4458        final Set<String> hosts = new HashSet<>();
4459        for (final Account account : getAccounts()) {
4460            hosts.add(account.getServer());
4461            for (final Contact contact : account.getRoster().getContacts()) {
4462                if (contact.showInRoster()) {
4463                    final String server = contact.getServer();
4464                    if (server != null) {
4465                        hosts.add(server);
4466                    }
4467                }
4468            }
4469        }
4470        if (Config.QUICKSY_DOMAIN != null) {
4471            hosts.remove(Config.QUICKSY_DOMAIN.toEscapedString()); //we only want to show this when we type a e164 number
4472        }
4473        if (Config.DOMAIN_LOCK != null) {
4474            hosts.add(Config.DOMAIN_LOCK);
4475        }
4476        if (Config.MAGIC_CREATE_DOMAIN != null) {
4477            hosts.add(Config.MAGIC_CREATE_DOMAIN);
4478        }
4479        return hosts;
4480    }
4481
4482    public Collection<String> getKnownConferenceHosts() {
4483        final Set<String> mucServers = new HashSet<>();
4484        for (final Account account : accounts) {
4485            if (account.getXmppConnection() != null) {
4486                mucServers.addAll(account.getXmppConnection().getMucServers());
4487                for (final Bookmark bookmark : account.getBookmarks()) {
4488                    final Jid jid = bookmark.getJid();
4489                    final String s = jid == null ? null : jid.getDomain().toEscapedString();
4490                    if (s != null) {
4491                        mucServers.add(s);
4492                    }
4493                }
4494            }
4495        }
4496        return mucServers;
4497    }
4498
4499    public void sendMessagePacket(Account account, MessagePacket packet) {
4500        final XmppConnection connection = account.getXmppConnection();
4501        if (connection != null) {
4502            connection.sendMessagePacket(packet);
4503        }
4504    }
4505
4506    public void sendPresencePacket(Account account, PresencePacket packet) {
4507        XmppConnection connection = account.getXmppConnection();
4508        if (connection != null) {
4509            connection.sendPresencePacket(packet);
4510        }
4511    }
4512
4513    public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
4514        final XmppConnection connection = account.getXmppConnection();
4515        if (connection != null) {
4516            IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
4517            connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
4518        }
4519    }
4520
4521    public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
4522        final XmppConnection connection = account.getXmppConnection();
4523        if (connection != null) {
4524            connection.sendIqPacket(packet, callback);
4525        } else if (callback != null) {
4526            callback.onIqPacketReceived(account, new IqPacket(IqPacket.TYPE.TIMEOUT));
4527        }
4528    }
4529
4530    public void sendPresence(final Account account) {
4531        sendPresence(account, checkListeners() && broadcastLastActivity());
4532    }
4533
4534    private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
4535        final Presence.Status status;
4536        if (manuallyChangePresence()) {
4537            status = account.getPresenceStatus();
4538        } else {
4539            status = getTargetPresence();
4540        }
4541        final PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
4542        if (mLastActivity > 0 && includeIdleTimestamp) {
4543            long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
4544            packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
4545        }
4546        sendPresencePacket(account, packet);
4547    }
4548
4549    private void deactivateGracePeriod() {
4550        for (Account account : getAccounts()) {
4551            account.deactivateGracePeriod();
4552        }
4553    }
4554
4555    public void refreshAllPresences() {
4556        boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
4557        for (Account account : getAccounts()) {
4558            if (account.isEnabled()) {
4559                sendPresence(account, includeIdleTimestamp);
4560            }
4561        }
4562    }
4563
4564    private void refreshAllFcmTokens() {
4565        for (Account account : getAccounts()) {
4566            if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
4567                mPushManagementService.registerPushTokenOnServer(account);
4568            }
4569        }
4570    }
4571
4572    private void sendOfflinePresence(final Account account) {
4573        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
4574        sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
4575    }
4576
4577    public MessageGenerator getMessageGenerator() {
4578        return this.mMessageGenerator;
4579    }
4580
4581    public PresenceGenerator getPresenceGenerator() {
4582        return this.mPresenceGenerator;
4583    }
4584
4585    public IqGenerator getIqGenerator() {
4586        return this.mIqGenerator;
4587    }
4588
4589    public IqParser getIqParser() {
4590        return this.mIqParser;
4591    }
4592
4593    public JingleConnectionManager getJingleConnectionManager() {
4594        return this.mJingleConnectionManager;
4595    }
4596
4597    public MessageArchiveService getMessageArchiveService() {
4598        return this.mMessageArchiveService;
4599    }
4600
4601    public QuickConversationsService getQuickConversationsService() {
4602        return this.mQuickConversationsService;
4603    }
4604
4605    public List<Contact> findContacts(Jid jid, String accountJid) {
4606        ArrayList<Contact> contacts = new ArrayList<>();
4607        for (Account account : getAccounts()) {
4608            if ((account.isEnabled() || accountJid != null)
4609                    && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
4610                Contact contact = account.getRoster().getContactFromContactList(jid);
4611                if (contact != null) {
4612                    contacts.add(contact);
4613                }
4614            }
4615        }
4616        return contacts;
4617    }
4618
4619    public Conversation findFirstMuc(Jid jid) {
4620        for (Conversation conversation : getConversations()) {
4621            if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
4622                return conversation;
4623            }
4624        }
4625        return null;
4626    }
4627
4628    public NotificationService getNotificationService() {
4629        return this.mNotificationService;
4630    }
4631
4632    public HttpConnectionManager getHttpConnectionManager() {
4633        return this.mHttpConnectionManager;
4634    }
4635
4636    public void resendFailedMessages(final Message message) {
4637        final Collection<Message> messages = new ArrayList<>();
4638        Message current = message;
4639        while (current.getStatus() == Message.STATUS_SEND_FAILED) {
4640            messages.add(current);
4641            if (current.mergeable(current.next())) {
4642                current = current.next();
4643            } else {
4644                break;
4645            }
4646        }
4647        for (final Message msg : messages) {
4648            msg.setTime(System.currentTimeMillis());
4649            markMessage(msg, Message.STATUS_WAITING);
4650            this.resendMessage(msg, false);
4651        }
4652        if (message.getConversation() instanceof Conversation) {
4653            ((Conversation) message.getConversation()).sort();
4654        }
4655        updateConversationUi();
4656    }
4657
4658    public void clearConversationHistory(final Conversation conversation) {
4659        final long clearDate;
4660        final String reference;
4661        if (conversation.countMessages() > 0) {
4662            Message latestMessage = conversation.getLatestMessage();
4663            clearDate = latestMessage.getTimeSent() + 1000;
4664            reference = latestMessage.getServerMsgId();
4665        } else {
4666            clearDate = System.currentTimeMillis();
4667            reference = null;
4668        }
4669        conversation.clearMessages();
4670        conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
4671        conversation.setLastClearHistory(clearDate, reference);
4672        Runnable runnable = () -> {
4673            databaseBackend.deleteMessagesInConversation(conversation);
4674            databaseBackend.updateConversation(conversation);
4675        };
4676        mDatabaseWriterExecutor.execute(runnable);
4677    }
4678
4679    public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
4680        if (blockable != null && blockable.getBlockedJid() != null) {
4681            final Jid jid = blockable.getBlockedJid();
4682            this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), (a, response) -> {
4683                if (response.getType() == IqPacket.TYPE.RESULT) {
4684                    a.getBlocklist().add(jid);
4685                    updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
4686                }
4687            });
4688            if (blockable.getBlockedJid().isFullJid()) {
4689                return false;
4690            } else if (removeBlockedConversations(blockable.getAccount(), jid)) {
4691                updateConversationUi();
4692                return true;
4693            } else {
4694                return false;
4695            }
4696        } else {
4697            return false;
4698        }
4699    }
4700
4701    public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
4702        boolean removed = false;
4703        synchronized (this.conversations) {
4704            boolean domainJid = blockedJid.getLocal() == null;
4705            for (Conversation conversation : this.conversations) {
4706                boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
4707                        || blockedJid.equals(conversation.getJid().asBareJid());
4708                if (conversation.getAccount() == account
4709                        && conversation.getMode() == Conversation.MODE_SINGLE
4710                        && jidMatches) {
4711                    this.conversations.remove(conversation);
4712                    markRead(conversation);
4713                    conversation.setStatus(Conversation.STATUS_ARCHIVED);
4714                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
4715                    updateConversation(conversation);
4716                    removed = true;
4717                }
4718            }
4719        }
4720        return removed;
4721    }
4722
4723    public void sendUnblockRequest(final Blockable blockable) {
4724        if (blockable != null && blockable.getJid() != null) {
4725            final Jid jid = blockable.getBlockedJid();
4726            this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
4727                @Override
4728                public void onIqPacketReceived(final Account account, final IqPacket packet) {
4729                    if (packet.getType() == IqPacket.TYPE.RESULT) {
4730                        account.getBlocklist().remove(jid);
4731                        updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
4732                    }
4733                }
4734            });
4735        }
4736    }
4737
4738    public void publishDisplayName(Account account) {
4739        String displayName = account.getDisplayName();
4740        final IqPacket request;
4741        if (TextUtils.isEmpty(displayName)) {
4742            request = mIqGenerator.deleteNode(Namespace.NICK);
4743        } else {
4744            request = mIqGenerator.publishNick(displayName);
4745        }
4746        mAvatarService.clear(account);
4747        sendIqPacket(account, request, (account1, packet) -> {
4748            if (packet.getType() == IqPacket.TYPE.ERROR) {
4749                Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": unable to modify nick name " + packet.toString());
4750            }
4751        });
4752    }
4753
4754    public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
4755        ServiceDiscoveryResult result = discoCache.get(key);
4756        if (result != null) {
4757            return result;
4758        } else {
4759            if (key.first == null || key.second == null) return null;
4760            result = databaseBackend.findDiscoveryResult(key.first, key.second);
4761            if (result != null) {
4762                discoCache.put(key, result);
4763            }
4764            return result;
4765        }
4766    }
4767
4768    public void fetchFromGateway(Account account, final Jid jid, final String input, final OnGatewayResult callback) {
4769        IqPacket request = new IqPacket(input == null ? IqPacket.TYPE.GET : IqPacket.TYPE.SET);
4770        request.setTo(jid);
4771        Element query = request.query("jabber:iq:gateway");
4772        if (input != null) {
4773            Element prompt = query.addChild("prompt");
4774            prompt.setContent(input);
4775        }
4776        sendIqPacket(account, request, (Account acct, IqPacket packet) -> {
4777            if (packet.getType() == IqPacket.TYPE.RESULT) {
4778                callback.onGatewayResult(packet.query().findChildContent(input == null ? "prompt" : "jid"), null);
4779            } else {
4780                Element error = packet.findChild("error");
4781                callback.onGatewayResult(null, error == null ? null : error.findChildContent("text"));
4782            }
4783        });
4784    }
4785
4786    public void fetchCaps(Account account, final Jid jid, final Presence presence) {
4787        fetchCaps(account, jid, presence, null);
4788    }
4789
4790    public void fetchCaps(Account account, final Jid jid, final Presence presence, Runnable cb) {
4791        final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
4792        final ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
4793
4794        if (disco != null) {
4795            presence.setServiceDiscoveryResult(disco);
4796            final Contact contact = account.getRoster().getContact(jid);
4797            if (contact.refreshRtpCapability()) {
4798                syncRoster(account);
4799            }
4800            if (disco.hasIdentity("gateway", "pstn")) {
4801                contact.registerAsPhoneAccount(this);
4802                mQuickConversationsService.considerSyncBackground(false);
4803            }
4804        } else {
4805            final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4806            request.setTo(jid);
4807            final String node = presence.getNode();
4808            final String ver = presence.getVer();
4809            final Element query = request.query(Namespace.DISCO_INFO);
4810            if (node != null && ver != null) {
4811                query.setAttribute("node", node + "#" + ver);
4812            }
4813            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
4814            sendIqPacket(account, request, (a, response) -> {
4815                if (response.getType() == IqPacket.TYPE.RESULT) {
4816                    final ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
4817                    if (presence.getVer() == null || presence.getVer().equals(discoveryResult.getVer())) {
4818                        databaseBackend.insertDiscoveryResult(discoveryResult);
4819                        injectServiceDiscoveryResult(a.getRoster(), presence.getHash(), presence.getVer(), jid.getResource(), discoveryResult);
4820                        if (discoveryResult.hasIdentity("gateway", "pstn")) {
4821                            final Contact contact = account.getRoster().getContact(jid);
4822                            contact.registerAsPhoneAccount(this);
4823                            mQuickConversationsService.considerSyncBackground(false);
4824                        }
4825                        if (cb != null) cb.run();
4826                    } else {
4827                        Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
4828                    }
4829                } else {
4830                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to fetch caps from " + jid);
4831                }
4832            });
4833        }
4834    }
4835
4836    public void fetchCommands(Account account, final Jid jid, OnIqPacketReceived callback) {
4837        final IqPacket request = mIqGenerator.queryDiscoItems(jid, "http://jabber.org/protocol/commands");
4838        sendIqPacket(account, request, callback);
4839    }
4840
4841    private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, String resource, ServiceDiscoveryResult disco) {
4842        boolean rosterNeedsSync = false;
4843        for (final Contact contact : roster.getContacts()) {
4844            boolean serviceDiscoverySet = false;
4845            Presence onePresence = contact.getPresences().get(resource == null ? "" : resource);
4846            if (onePresence != null) {
4847                onePresence.setServiceDiscoveryResult(disco);
4848                serviceDiscoverySet = true;
4849            }
4850            if (hash != null && ver != null) {
4851                for (final Presence presence : contact.getPresences().getPresences()) {
4852                    if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
4853                        presence.setServiceDiscoveryResult(disco);
4854                        serviceDiscoverySet = true;
4855                    }
4856                }
4857            }
4858            if (serviceDiscoverySet) {
4859                rosterNeedsSync |= contact.refreshRtpCapability();
4860            }
4861        }
4862        if (rosterNeedsSync) {
4863            syncRoster(roster.getAccount());
4864        }
4865    }
4866
4867    public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
4868        final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
4869        IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4870        request.addChild("prefs", version.namespace);
4871        sendIqPacket(account, request, (account1, packet) -> {
4872            Element prefs = packet.findChild("prefs", version.namespace);
4873            if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
4874                callback.onPreferencesFetched(prefs);
4875            } else {
4876                callback.onPreferencesFetchFailed();
4877            }
4878        });
4879    }
4880
4881    public PushManagementService getPushManagementService() {
4882        return mPushManagementService;
4883    }
4884
4885    public void changeStatus(Account account, PresenceTemplate template, String signature) {
4886        if (!template.getStatusMessage().isEmpty()) {
4887            databaseBackend.insertPresenceTemplate(template);
4888        }
4889        account.setPgpSignature(signature);
4890        account.setPresenceStatus(template.getStatus());
4891        account.setPresenceStatusMessage(template.getStatusMessage());
4892        databaseBackend.updateAccount(account);
4893        sendPresence(account);
4894    }
4895
4896    public List<PresenceTemplate> getPresenceTemplates(Account account) {
4897        List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
4898        for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
4899            if (!templates.contains(template)) {
4900                templates.add(0, template);
4901            }
4902        }
4903        return templates;
4904    }
4905
4906    public void saveConversationAsBookmark(Conversation conversation, String name) {
4907        final Account account = conversation.getAccount();
4908        final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
4909        final String nick = conversation.getJid().getResource();
4910        if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
4911            bookmark.setNick(nick);
4912        }
4913        if (!TextUtils.isEmpty(name)) {
4914            bookmark.setBookmarkName(name);
4915        }
4916        bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
4917        createBookmark(account, bookmark);
4918        bookmark.setConversation(conversation);
4919    }
4920
4921    public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
4922        boolean performedVerification = false;
4923        final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
4924        for (XmppUri.Fingerprint fp : fingerprints) {
4925            if (fp.type == XmppUri.FingerprintType.OMEMO) {
4926                String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4927                FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4928                if (fingerprintStatus != null) {
4929                    if (!fingerprintStatus.isVerified()) {
4930                        performedVerification = true;
4931                        axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4932                    }
4933                } else {
4934                    axolotlService.preVerifyFingerprint(contact, fingerprint);
4935                }
4936            }
4937        }
4938        return performedVerification;
4939    }
4940
4941    public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
4942        final AxolotlService axolotlService = account.getAxolotlService();
4943        boolean verifiedSomething = false;
4944        for (XmppUri.Fingerprint fp : fingerprints) {
4945            if (fp.type == XmppUri.FingerprintType.OMEMO) {
4946                String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4947                Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
4948                FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4949                if (fingerprintStatus != null) {
4950                    if (!fingerprintStatus.isVerified()) {
4951                        axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4952                        verifiedSomething = true;
4953                    }
4954                } else {
4955                    axolotlService.preVerifyFingerprint(account, fingerprint);
4956                    verifiedSomething = true;
4957                }
4958            }
4959        }
4960        return verifiedSomething;
4961    }
4962
4963    public boolean blindTrustBeforeVerification() {
4964        return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
4965    }
4966
4967    public ShortcutService getShortcutService() {
4968        return mShortcutService;
4969    }
4970
4971    public void pushMamPreferences(Account account, Element prefs) {
4972        IqPacket set = new IqPacket(IqPacket.TYPE.SET);
4973        set.addChild(prefs);
4974        sendIqPacket(account, set, null);
4975    }
4976
4977    public void evictPreview(String uuid) {
4978        if (mBitmapCache.remove(uuid) != null) {
4979            Log.d(Config.LOGTAG, "deleted cached preview");
4980        }
4981    }
4982
4983    public interface OnMamPreferencesFetched {
4984        void onPreferencesFetched(Element prefs);
4985
4986        void onPreferencesFetchFailed();
4987    }
4988
4989    public interface OnAccountCreated {
4990        void onAccountCreated(Account account);
4991
4992        void informUser(int r);
4993    }
4994
4995    public interface OnMoreMessagesLoaded {
4996        void onMoreMessagesLoaded(int count, Conversation conversation);
4997
4998        void informUser(int r);
4999    }
5000
5001    public interface OnAccountPasswordChanged {
5002        void onPasswordChangeSucceeded();
5003
5004        void onPasswordChangeFailed();
5005    }
5006
5007    public interface OnRoomDestroy {
5008        void onRoomDestroySucceeded();
5009
5010        void onRoomDestroyFailed();
5011    }
5012
5013    public interface OnAffiliationChanged {
5014        void onAffiliationChangedSuccessful(Jid jid);
5015
5016        void onAffiliationChangeFailed(Jid jid, int resId);
5017    }
5018
5019    public interface OnConversationUpdate {
5020        void onConversationUpdate();
5021    }
5022
5023    public interface OnJingleRtpConnectionUpdate {
5024        void onJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state);
5025
5026        void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices);
5027    }
5028
5029    public interface OnAccountUpdate {
5030        void onAccountUpdate();
5031    }
5032
5033    public interface OnCaptchaRequested {
5034        void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
5035    }
5036
5037    public interface OnRosterUpdate {
5038        void onRosterUpdate();
5039    }
5040
5041    public interface OnMucRosterUpdate {
5042        void onMucRosterUpdate();
5043    }
5044
5045    public interface OnConferenceConfigurationFetched {
5046        void onConferenceConfigurationFetched(Conversation conversation);
5047
5048        void onFetchFailed(Conversation conversation, String errorCondition);
5049    }
5050
5051    public interface OnConferenceJoined {
5052        void onConferenceJoined(Conversation conversation);
5053    }
5054
5055    public interface OnConfigurationPushed {
5056        void onPushSucceeded();
5057
5058        void onPushFailed();
5059    }
5060
5061    public interface OnShowErrorToast {
5062        void onShowErrorToast(int resId);
5063    }
5064
5065    public class XmppConnectionBinder extends Binder {
5066        public XmppConnectionService getService() {
5067            return XmppConnectionService.this;
5068        }
5069    }
5070
5071    private class InternalEventReceiver extends BroadcastReceiver {
5072
5073        @Override
5074        public void onReceive(Context context, Intent intent) {
5075            onStartCommand(intent, 0, 0);
5076        }
5077    }
5078
5079    public static class OngoingCall {
5080        public final AbstractJingleConnection.Id id;
5081        public final Set<Media> media;
5082        public final boolean reconnecting;
5083
5084        public OngoingCall(AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
5085            this.id = id;
5086            this.media = media;
5087            this.reconnecting = reconnecting;
5088        }
5089
5090        @Override
5091        public boolean equals(Object o) {
5092            if (this == o) return true;
5093            if (o == null || getClass() != o.getClass()) return false;
5094            OngoingCall that = (OngoingCall) o;
5095            return reconnecting == that.reconnecting && Objects.equal(id, that.id) && Objects.equal(media, that.media);
5096        }
5097
5098        @Override
5099        public int hashCode() {
5100            return Objects.hashCode(id, media, reconnecting);
5101        }
5102    }
5103}