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