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