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