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