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