XmppConnectionService.java

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