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