XmppConnectionService.java

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