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