XmppConnectionService.java

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