XmppConnectionService.java

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