XmppConnectionService.java

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