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