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