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