XmppConnectionService.java

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