XmppConnectionService.java

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