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