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.TelephonyCallback;
  40import android.telephony.TelephonyManager;
  41import android.text.TextUtils;
  42import android.util.DisplayMetrics;
  43import android.util.Log;
  44import android.util.LruCache;
  45import android.util.Pair;
  46
  47import androidx.annotation.BoolRes;
  48import androidx.annotation.IntegerRes;
  49import androidx.core.app.RemoteInput;
  50import androidx.core.content.ContextCompat;
  51
  52import com.google.common.base.Objects;
  53import com.google.common.base.Strings;
  54
  55import org.conscrypt.Conscrypt;
  56import org.openintents.openpgp.IOpenPgpService2;
  57import org.openintents.openpgp.util.OpenPgpApi;
  58import org.openintents.openpgp.util.OpenPgpServiceConnection;
  59
  60import java.io.File;
  61import java.security.SecureRandom;
  62import java.security.Security;
  63import java.security.cert.CertificateException;
  64import java.security.cert.X509Certificate;
  65import java.util.ArrayList;
  66import java.util.Arrays;
  67import java.util.Collection;
  68import java.util.Collections;
  69import java.util.HashSet;
  70import java.util.Hashtable;
  71import java.util.Iterator;
  72import java.util.List;
  73import java.util.ListIterator;
  74import java.util.Map;
  75import java.util.Set;
  76import java.util.WeakHashMap;
  77import java.util.concurrent.CopyOnWriteArrayList;
  78import java.util.concurrent.CountDownLatch;
  79import java.util.concurrent.Executor;
  80import java.util.concurrent.Executors;
  81import java.util.concurrent.atomic.AtomicBoolean;
  82import java.util.concurrent.atomic.AtomicLong;
  83import java.util.concurrent.atomic.AtomicReference;
  84
  85import eu.siacs.conversations.Config;
  86import eu.siacs.conversations.R;
  87import eu.siacs.conversations.android.JabberIdContact;
  88import eu.siacs.conversations.crypto.OmemoSetting;
  89import eu.siacs.conversations.crypto.PgpDecryptionService;
  90import eu.siacs.conversations.crypto.PgpEngine;
  91import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  92import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  93import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
  94import eu.siacs.conversations.entities.Account;
  95import eu.siacs.conversations.entities.Blockable;
  96import eu.siacs.conversations.entities.Bookmark;
  97import eu.siacs.conversations.entities.Contact;
  98import eu.siacs.conversations.entities.Conversation;
  99import eu.siacs.conversations.entities.Conversational;
 100import eu.siacs.conversations.entities.Message;
 101import eu.siacs.conversations.entities.MucOptions;
 102import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
 103import eu.siacs.conversations.entities.Presence;
 104import eu.siacs.conversations.entities.PresenceTemplate;
 105import eu.siacs.conversations.entities.Roster;
 106import eu.siacs.conversations.entities.ServiceDiscoveryResult;
 107import eu.siacs.conversations.generator.AbstractGenerator;
 108import eu.siacs.conversations.generator.IqGenerator;
 109import eu.siacs.conversations.generator.MessageGenerator;
 110import eu.siacs.conversations.generator.PresenceGenerator;
 111import eu.siacs.conversations.http.HttpConnectionManager;
 112import eu.siacs.conversations.parser.AbstractParser;
 113import eu.siacs.conversations.parser.IqParser;
 114import eu.siacs.conversations.parser.MessageParser;
 115import eu.siacs.conversations.parser.PresenceParser;
 116import eu.siacs.conversations.persistance.DatabaseBackend;
 117import eu.siacs.conversations.persistance.FileBackend;
 118import eu.siacs.conversations.ui.ChooseAccountForProfilePictureActivity;
 119import eu.siacs.conversations.ui.RtpSessionActivity;
 120import eu.siacs.conversations.ui.SettingsActivity;
 121import eu.siacs.conversations.ui.UiCallback;
 122import eu.siacs.conversations.ui.interfaces.OnAvatarPublication;
 123import eu.siacs.conversations.ui.interfaces.OnMediaLoaded;
 124import eu.siacs.conversations.ui.interfaces.OnSearchResultsAvailable;
 125import eu.siacs.conversations.utils.Compatibility;
 126import eu.siacs.conversations.utils.ConversationsFileObserver;
 127import eu.siacs.conversations.utils.CryptoHelper;
 128import eu.siacs.conversations.utils.EasyOnboardingInvite;
 129import eu.siacs.conversations.utils.ExceptionHelper;
 130import eu.siacs.conversations.utils.MimeUtils;
 131import eu.siacs.conversations.utils.PhoneHelper;
 132import eu.siacs.conversations.utils.QuickLoader;
 133import eu.siacs.conversations.utils.ReplacingSerialSingleThreadExecutor;
 134import eu.siacs.conversations.utils.ReplacingTaskManager;
 135import eu.siacs.conversations.utils.Resolver;
 136import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
 137import eu.siacs.conversations.utils.StringUtils;
 138import eu.siacs.conversations.utils.TorServiceUtils;
 139import eu.siacs.conversations.utils.WakeLockHelper;
 140import eu.siacs.conversations.utils.XmppUri;
 141import eu.siacs.conversations.xml.Element;
 142import eu.siacs.conversations.xml.LocalizedContent;
 143import eu.siacs.conversations.xml.Namespace;
 144import eu.siacs.conversations.xmpp.Jid;
 145import eu.siacs.conversations.xmpp.OnBindListener;
 146import eu.siacs.conversations.xmpp.OnContactStatusChanged;
 147import eu.siacs.conversations.xmpp.OnIqPacketReceived;
 148import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
 149import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
 150import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
 151import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
 152import eu.siacs.conversations.xmpp.OnStatusChanged;
 153import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 154import eu.siacs.conversations.xmpp.Patches;
 155import eu.siacs.conversations.xmpp.XmppConnection;
 156import eu.siacs.conversations.xmpp.chatstate.ChatState;
 157import eu.siacs.conversations.xmpp.forms.Data;
 158import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
 159import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
 160import eu.siacs.conversations.xmpp.jingle.JingleRtpConnection;
 161import eu.siacs.conversations.xmpp.jingle.Media;
 162import eu.siacs.conversations.xmpp.jingle.RtpEndUserState;
 163import eu.siacs.conversations.xmpp.mam.MamReference;
 164import eu.siacs.conversations.xmpp.pep.Avatar;
 165import eu.siacs.conversations.xmpp.pep.PublishOptions;
 166import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 167import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 168import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
 169import me.leolin.shortcutbadger.ShortcutBadger;
 170
 171public class XmppConnectionService extends Service {
 172
 173    public static final String ACTION_REPLY_TO_CONVERSATION = "reply_to_conversations";
 174    public static final String ACTION_MARK_AS_READ = "mark_as_read";
 175    public static final String ACTION_SNOOZE = "snooze";
 176    public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification";
 177    public static final String ACTION_DISMISS_ERROR_NOTIFICATIONS = "dismiss_error";
 178    public static final String ACTION_TRY_AGAIN = "try_again";
 179    public static final String ACTION_IDLE_PING = "idle_ping";
 180    public static final String ACTION_FCM_TOKEN_REFRESH = "fcm_token_refresh";
 181    public static final String ACTION_FCM_MESSAGE_RECEIVED = "fcm_message_received";
 182    public static final String ACTION_DISMISS_CALL = "dismiss_call";
 183    public static final String ACTION_END_CALL = "end_call";
 184    public static final String ACTION_PROVISION_ACCOUNT = "provision_account";
 185    private static final String ACTION_POST_CONNECTIVITY_CHANGE = "eu.siacs.conversations.POST_CONNECTIVITY_CHANGE";
 186
 187    private static final String SETTING_LAST_ACTIVITY_TS = "last_activity_timestamp";
 188
 189    public final CountDownLatch restoredFromDatabaseLatch = new CountDownLatch(1);
 190    private final static Executor FILE_OBSERVER_EXECUTOR = Executors.newSingleThreadExecutor();
 191    private final static Executor FILE_ATTACHMENT_EXECUTOR = Executors.newSingleThreadExecutor();
 192    private final static SerialSingleThreadExecutor VIDEO_COMPRESSION_EXECUTOR = new SerialSingleThreadExecutor("VideoCompression");
 193    private final SerialSingleThreadExecutor mDatabaseWriterExecutor = new SerialSingleThreadExecutor("DatabaseWriter");
 194    private final SerialSingleThreadExecutor mDatabaseReaderExecutor = new SerialSingleThreadExecutor("DatabaseReader");
 195    private final SerialSingleThreadExecutor mNotificationExecutor = new SerialSingleThreadExecutor("NotificationExecutor");
 196    private final ReplacingTaskManager mRosterSyncTaskManager = new ReplacingTaskManager();
 197    private final IBinder mBinder = new XmppConnectionBinder();
 198    private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
 199    private final IqGenerator mIqGenerator = new IqGenerator(this);
 200    private final Set<String> mInProgressAvatarFetches = new HashSet<>();
 201    private final Set<String> mOmittedPepAvatarFetches = new HashSet<>();
 202    private final HashSet<Jid> mLowPingTimeoutMode = new HashSet<>();
 203    private final OnIqPacketReceived mDefaultIqHandler = (account, packet) -> {
 204        if (packet.getType() != IqPacket.TYPE.RESULT) {
 205            Element error = packet.findChild("error");
 206            String text = error != null ? error.findChildContent("text") : null;
 207            if (text != null) {
 208                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received iq error - " + text);
 209            }
 210        }
 211    };
 212    public DatabaseBackend databaseBackend;
 213    private final ReplacingSerialSingleThreadExecutor mContactMergerExecutor = new ReplacingSerialSingleThreadExecutor("ContactMerger");
 214    private long mLastActivity = 0;
 215    private final FileBackend fileBackend = new FileBackend(this);
 216    private MemorizingTrustManager mMemorizingTrustManager;
 217    private final NotificationService mNotificationService = new NotificationService(this);
 218    private final ChannelDiscoveryService mChannelDiscoveryService = new ChannelDiscoveryService(this);
 219    private final ShortcutService mShortcutService = new ShortcutService(this);
 220    private final AtomicBoolean mInitialAddressbookSyncCompleted = new AtomicBoolean(false);
 221    private final AtomicBoolean mForceForegroundService = new AtomicBoolean(false);
 222    private final AtomicBoolean mForceDuringOnCreate = new AtomicBoolean(false);
 223    private final AtomicReference<OngoingCall> ongoingCall = new AtomicReference<>();
 224    private final OnMessagePacketReceived mMessageParser = new MessageParser(this);
 225    private final OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
 226    private final IqParser mIqParser = new IqParser(this);
 227    private final MessageGenerator mMessageGenerator = new MessageGenerator(this);
 228    public OnContactStatusChanged onContactStatusChanged = (contact, online) -> {
 229        Conversation conversation = find(getConversations(), contact);
 230        if (conversation != null) {
 231            if (online) {
 232                if (contact.getPresences().size() == 1) {
 233                    sendUnsentMessages(conversation);
 234                }
 235            }
 236        }
 237    };
 238    private final PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
 239    private List<Account> accounts;
 240    private final JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(this);
 241    private final HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(this);
 242    private final AvatarService mAvatarService = new AvatarService(this);
 243    private final MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
 244    private final PushManagementService mPushManagementService = new PushManagementService(this);
 245    private final QuickConversationsService mQuickConversationsService = new QuickConversationsService(this);
 246    private final ConversationsFileObserver fileObserver = new ConversationsFileObserver(
 247            Environment.getExternalStorageDirectory().getAbsolutePath()
 248    ) {
 249        @Override
 250        public void onEvent(final int event, final File file) {
 251            markFileDeleted(file);
 252        }
 253    };
 254    private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
 255
 256        @Override
 257        public boolean onMessageAcknowledged(final Account account, final Jid to, final String id) {
 258            if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
 259                final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
 260                mJingleConnectionManager.updateProposedSessionDiscovered(
 261                        account,
 262                        to,
 263                        sessionId,
 264                        JingleConnectionManager.DeviceDiscoveryState.SEARCHING_ACKNOWLEDGED
 265                );
 266            }
 267
 268
 269            final Jid bare = to.asBareJid();
 270
 271            for (final Conversation conversation : getConversations()) {
 272                if (conversation.getAccount() == account && conversation.getJid().asBareJid().equals(bare)) {
 273                    final Message message = conversation.findUnsentMessageWithUuid(id);
 274                    if (message != null) {
 275                        message.setStatus(Message.STATUS_SEND);
 276                        message.setErrorMessage(null);
 277                        databaseBackend.updateMessage(message, false);
 278                        return true;
 279                    }
 280                }
 281            }
 282            return false;
 283        }
 284    };
 285    private final AtomicBoolean isPhoneInCall = new AtomicBoolean(false);
 286    private final PhoneStateListener phoneStateListener = new PhoneStateListener() {
 287        @Override
 288        public void onCallStateChanged(final int state, final String phoneNumber) {
 289            isPhoneInCall.set(state != TelephonyManager.CALL_STATE_IDLE);
 290            if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
 291                mJingleConnectionManager.notifyPhoneCallStarted();
 292            }
 293        }
 294    };
 295
 296    private boolean destroyed = false;
 297
 298    private int unreadCount = -1;
 299
 300    //Ui callback listeners
 301    private final Set<OnConversationUpdate> mOnConversationUpdates = Collections.newSetFromMap(new WeakHashMap<OnConversationUpdate, Boolean>());
 302    private final Set<OnShowErrorToast> mOnShowErrorToasts = Collections.newSetFromMap(new WeakHashMap<OnShowErrorToast, Boolean>());
 303    private final Set<OnAccountUpdate> mOnAccountUpdates = Collections.newSetFromMap(new WeakHashMap<OnAccountUpdate, Boolean>());
 304    private final Set<OnCaptchaRequested> mOnCaptchaRequested = Collections.newSetFromMap(new WeakHashMap<OnCaptchaRequested, Boolean>());
 305    private final Set<OnRosterUpdate> mOnRosterUpdates = Collections.newSetFromMap(new WeakHashMap<OnRosterUpdate, Boolean>());
 306    private final Set<OnUpdateBlocklist> mOnUpdateBlocklist = Collections.newSetFromMap(new WeakHashMap<OnUpdateBlocklist, Boolean>());
 307    private final Set<OnMucRosterUpdate> mOnMucRosterUpdate = Collections.newSetFromMap(new WeakHashMap<OnMucRosterUpdate, Boolean>());
 308    private final Set<OnKeyStatusUpdated> mOnKeyStatusUpdated = Collections.newSetFromMap(new WeakHashMap<OnKeyStatusUpdated, Boolean>());
 309    private final Set<OnJingleRtpConnectionUpdate> onJingleRtpConnectionUpdate = Collections.newSetFromMap(new WeakHashMap<OnJingleRtpConnectionUpdate, Boolean>());
 310
 311    private final Object LISTENER_LOCK = new Object();
 312
 313
 314    public final Set<String> FILENAMES_TO_IGNORE_DELETION = new HashSet<>();
 315
 316
 317    private final OnBindListener mOnBindListener = new OnBindListener() {
 318
 319        @Override
 320        public void onBind(final Account account) {
 321            synchronized (mInProgressAvatarFetches) {
 322                for (Iterator<String> iterator = mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
 323                    final String KEY = iterator.next();
 324                    if (KEY.startsWith(account.getJid().asBareJid() + "_")) {
 325                        iterator.remove();
 326                    }
 327                }
 328            }
 329            boolean loggedInSuccessfully = account.setOption(Account.OPTION_LOGGED_IN_SUCCESSFULLY, true);
 330            boolean gainedFeature = account.setOption(Account.OPTION_HTTP_UPLOAD_AVAILABLE, account.getXmppConnection().getFeatures().httpUpload(0));
 331            if (loggedInSuccessfully || gainedFeature) {
 332                databaseBackend.updateAccount(account);
 333            }
 334
 335            if (loggedInSuccessfully) {
 336                if (!TextUtils.isEmpty(account.getDisplayName())) {
 337                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": display name wasn't empty on first log in. publishing");
 338                    publishDisplayName(account);
 339                }
 340            }
 341
 342            account.getRoster().clearPresences();
 343            synchronized (account.inProgressConferenceJoins) {
 344                account.inProgressConferenceJoins.clear();
 345            }
 346            synchronized (account.inProgressConferencePings) {
 347                account.inProgressConferencePings.clear();
 348            }
 349            mJingleConnectionManager.notifyRebound(account);
 350            mQuickConversationsService.considerSyncBackground(false);
 351            fetchRosterFromServer(account);
 352
 353            final XmppConnection connection = account.getXmppConnection();
 354
 355            if (connection.getFeatures().bookmarks2()) {
 356                fetchBookmarks2(account);
 357            } else if (!account.getXmppConnection().getFeatures().bookmarksConversion()) {
 358                fetchBookmarks(account);
 359            }
 360            final boolean flexible = account.getXmppConnection().getFeatures().flexibleOfflineMessageRetrieval();
 361            final boolean catchup = getMessageArchiveService().inCatchup(account);
 362            if (flexible && catchup && account.getXmppConnection().isMamPreferenceAlways()) {
 363                sendIqPacket(account, mIqGenerator.purgeOfflineMessages(), (acc, packet) -> {
 364                    if (packet.getType() == IqPacket.TYPE.RESULT) {
 365                        Log.d(Config.LOGTAG, acc.getJid().asBareJid() + ": successfully purged offline messages");
 366                    }
 367                });
 368            }
 369            sendPresence(account);
 370            if (mPushManagementService.available(account)) {
 371                mPushManagementService.registerPushTokenOnServer(account);
 372            }
 373            connectMultiModeConversations(account);
 374            syncDirtyContacts(account);
 375
 376        }
 377    };
 378    private final AtomicLong mLastExpiryRun = new AtomicLong(0);
 379    private SecureRandom mRandom;
 380    private final LruCache<Pair<String, String>, ServiceDiscoveryResult> discoCache = new LruCache<>(20);
 381    private final OnStatusChanged statusListener = new OnStatusChanged() {
 382
 383        @Override
 384        public void onStatusChanged(final Account account) {
 385            XmppConnection connection = account.getXmppConnection();
 386            updateAccountUi();
 387
 388            if (account.getStatus() == Account.State.ONLINE || account.getStatus().isError()) {
 389                mQuickConversationsService.signalAccountStateChange();
 390            }
 391
 392            if (account.getStatus() == Account.State.ONLINE) {
 393                synchronized (mLowPingTimeoutMode) {
 394                    if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
 395                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": leaving low ping timeout mode");
 396                    }
 397                }
 398                if (account.setShowErrorNotification(true)) {
 399                    databaseBackend.updateAccount(account);
 400                }
 401                mMessageArchiveService.executePendingQueries(account);
 402                if (connection != null && connection.getFeatures().csi()) {
 403                    if (checkListeners()) {
 404                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + " sending csi//inactive");
 405                        connection.sendInactive();
 406                    } else {
 407                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + " sending csi//active");
 408                        connection.sendActive();
 409                    }
 410                }
 411                List<Conversation> conversations = getConversations();
 412                for (Conversation conversation : conversations) {
 413                    final boolean inProgressJoin;
 414                    synchronized (account.inProgressConferenceJoins) {
 415                        inProgressJoin = account.inProgressConferenceJoins.contains(conversation);
 416                    }
 417                    final boolean pendingJoin;
 418                    synchronized (account.pendingConferenceJoins) {
 419                        pendingJoin = account.pendingConferenceJoins.contains(conversation);
 420                    }
 421                    if (conversation.getAccount() == account
 422                            && !pendingJoin
 423                            && !inProgressJoin) {
 424                        sendUnsentMessages(conversation);
 425                    }
 426                }
 427                final List<Conversation> pendingLeaves;
 428                synchronized (account.pendingConferenceLeaves) {
 429                    pendingLeaves = new ArrayList<>(account.pendingConferenceLeaves);
 430                    account.pendingConferenceLeaves.clear();
 431
 432                }
 433                for (Conversation conversation : pendingLeaves) {
 434                    leaveMuc(conversation);
 435                }
 436                final List<Conversation> pendingJoins;
 437                synchronized (account.pendingConferenceJoins) {
 438                    pendingJoins = new ArrayList<>(account.pendingConferenceJoins);
 439                    account.pendingConferenceJoins.clear();
 440                }
 441                for (Conversation conversation : pendingJoins) {
 442                    joinMuc(conversation);
 443                }
 444                scheduleWakeUpCall(Config.PING_MAX_INTERVAL, account.getUuid().hashCode());
 445            } else if (account.getStatus() == Account.State.OFFLINE || account.getStatus() == Account.State.DISABLED) {
 446                resetSendingToWaiting(account);
 447                if (account.isEnabled() && isInLowPingTimeoutMode(account)) {
 448                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": went into offline state during low ping mode. reconnecting now");
 449                    reconnectAccount(account, true, false);
 450                } else {
 451                    int timeToReconnect = mRandom.nextInt(10) + 2;
 452                    scheduleWakeUpCall(timeToReconnect, account.getUuid().hashCode());
 453                }
 454            } else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
 455                databaseBackend.updateAccount(account);
 456                reconnectAccount(account, true, false);
 457            } else if (account.getStatus() != Account.State.CONNECTING && account.getStatus() != Account.State.NO_INTERNET) {
 458                resetSendingToWaiting(account);
 459                if (connection != null && account.getStatus().isAttemptReconnect()) {
 460                    final int next = connection.getTimeToNextAttempt();
 461                    final boolean lowPingTimeoutMode = isInLowPingTimeoutMode(account);
 462                    if (next <= 0) {
 463                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error connecting account. reconnecting now. lowPingTimeout=" + lowPingTimeoutMode);
 464                        reconnectAccount(account, true, false);
 465                    } else {
 466                        final int attempt = connection.getAttempt() + 1;
 467                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error connecting account. try again in " + next + "s for the " + attempt + " time. lowPingTimeout=" + lowPingTimeoutMode);
 468                        scheduleWakeUpCall(next, account.getUuid().hashCode());
 469                    }
 470                }
 471            }
 472            getNotificationService().updateErrorNotification();
 473        }
 474    };
 475    private OpenPgpServiceConnection pgpServiceConnection;
 476    private PgpEngine mPgpEngine = null;
 477    private WakeLock wakeLock;
 478    private LruCache<String, Bitmap> mBitmapCache;
 479    private final BroadcastReceiver mInternalEventReceiver = new InternalEventReceiver();
 480    private final BroadcastReceiver mInternalScreenEventReceiver = new InternalEventReceiver();
 481
 482    private static String generateFetchKey(Account account, final Avatar avatar) {
 483        return account.getJid().asBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum;
 484    }
 485
 486    private boolean isInLowPingTimeoutMode(Account account) {
 487        synchronized (mLowPingTimeoutMode) {
 488            return mLowPingTimeoutMode.contains(account.getJid().asBareJid());
 489        }
 490    }
 491
 492    public void startForcingForegroundNotification() {
 493        mForceForegroundService.set(true);
 494        toggleForegroundService();
 495    }
 496
 497    public void stopForcingForegroundNotification() {
 498        mForceForegroundService.set(false);
 499        toggleForegroundService();
 500    }
 501
 502    public boolean areMessagesInitialized() {
 503        return this.restoredFromDatabaseLatch.getCount() == 0;
 504    }
 505
 506    public PgpEngine getPgpEngine() {
 507        if (!Config.supportOpenPgp()) {
 508            return null;
 509        } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
 510            if (this.mPgpEngine == null) {
 511                this.mPgpEngine = new PgpEngine(new OpenPgpApi(
 512                        getApplicationContext(),
 513                        pgpServiceConnection.getService()), this);
 514            }
 515            return mPgpEngine;
 516        } else {
 517            return null;
 518        }
 519
 520    }
 521
 522    public OpenPgpApi getOpenPgpApi() {
 523        if (!Config.supportOpenPgp()) {
 524            return null;
 525        } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
 526            return new OpenPgpApi(this, pgpServiceConnection.getService());
 527        } else {
 528            return null;
 529        }
 530    }
 531
 532    public FileBackend getFileBackend() {
 533        return this.fileBackend;
 534    }
 535
 536    public AvatarService getAvatarService() {
 537        return this.mAvatarService;
 538    }
 539
 540    public void attachLocationToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
 541        int encryption = conversation.getNextEncryption();
 542        if (encryption == Message.ENCRYPTION_PGP) {
 543            encryption = Message.ENCRYPTION_DECRYPTED;
 544        }
 545        Message message = new Message(conversation, uri.toString(), encryption);
 546        Message.configurePrivateMessage(message);
 547        if (encryption == Message.ENCRYPTION_DECRYPTED) {
 548            getPgpEngine().encrypt(message, callback);
 549        } else {
 550            sendMessage(message);
 551            callback.success(message);
 552        }
 553    }
 554
 555    public void attachFileToConversation(final Conversation conversation, final Uri uri, final String type, final UiCallback<Message> callback) {
 556        final Message message;
 557        if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 558            message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
 559        } else {
 560            message = new Message(conversation, "", conversation.getNextEncryption());
 561        }
 562        if (!Message.configurePrivateFileMessage(message)) {
 563            message.setCounterpart(conversation.getNextCounterpart());
 564            message.setType(Message.TYPE_FILE);
 565        }
 566        Log.d(Config.LOGTAG, "attachFile: type=" + message.getType());
 567        Log.d(Config.LOGTAG, "counterpart=" + message.getCounterpart());
 568        final AttachFileToConversationRunnable runnable = new AttachFileToConversationRunnable(this, uri, type, message, callback);
 569        if (runnable.isVideoMessage()) {
 570            VIDEO_COMPRESSION_EXECUTOR.execute(runnable);
 571        } else {
 572            FILE_ATTACHMENT_EXECUTOR.execute(runnable);
 573        }
 574    }
 575
 576    public void attachImageToConversation(final Conversation conversation, final Uri uri,  final String type, final UiCallback<Message> callback) {
 577        final String mimeType = MimeUtils.guessMimeTypeFromUriAndMime(this, uri, type);
 578        final String compressPictures = getCompressPicturesPreference();
 579
 580        if ("never".equals(compressPictures)
 581                || ("auto".equals(compressPictures) && getFileBackend().useImageAsIs(uri))
 582                || (mimeType != null && mimeType.endsWith("/gif"))
 583                || getFileBackend().unusualBounds(uri)) {
 584            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": not compressing picture. sending as file");
 585            attachFileToConversation(conversation, uri, mimeType, callback);
 586            return;
 587        }
 588        final Message message;
 589        if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 590            message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
 591        } else {
 592            message = new Message(conversation, "", conversation.getNextEncryption());
 593        }
 594        if (!Message.configurePrivateFileMessage(message)) {
 595            message.setCounterpart(conversation.getNextCounterpart());
 596            message.setType(Message.TYPE_IMAGE);
 597        }
 598        Log.d(Config.LOGTAG, "attachImage: type=" + message.getType());
 599        FILE_ATTACHMENT_EXECUTOR.execute(() -> {
 600            try {
 601                getFileBackend().copyImageToPrivateStorage(message, uri);
 602            } catch (FileBackend.ImageCompressionException e) {
 603                Log.d(Config.LOGTAG, "unable to compress image. fall back to file transfer", e);
 604                attachFileToConversation(conversation, uri, mimeType, callback);
 605                return;
 606            } catch (final FileBackend.FileCopyException e) {
 607                callback.error(e.getResId(), message);
 608                return;
 609            }
 610            if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 611                final PgpEngine pgpEngine = getPgpEngine();
 612                if (pgpEngine != null) {
 613                    pgpEngine.encrypt(message, callback);
 614                } else if (callback != null) {
 615                    callback.error(R.string.unable_to_connect_to_keychain, null);
 616                }
 617            } else {
 618                sendMessage(message);
 619                callback.success(message);
 620            }
 621        });
 622    }
 623
 624    public Conversation find(Bookmark bookmark) {
 625        return find(bookmark.getAccount(), bookmark.getJid());
 626    }
 627
 628    public Conversation find(final Account account, final Jid jid) {
 629        return find(getConversations(), account, jid);
 630    }
 631
 632    public boolean isMuc(final Account account, final Jid jid) {
 633        final Conversation c = find(account, jid);
 634        return c != null && c.getMode() == Conversational.MODE_MULTI;
 635    }
 636
 637    public void search(final List<String> term, final String uuid, final OnSearchResultsAvailable onSearchResultsAvailable) {
 638        MessageSearchTask.search(this, term, uuid, onSearchResultsAvailable);
 639    }
 640
 641    @Override
 642    public int onStartCommand(Intent intent, int flags, int startId) {
 643        final String action = intent == null ? null : intent.getAction();
 644        final boolean needsForegroundService = intent != null && intent.getBooleanExtra(EventReceiver.EXTRA_NEEDS_FOREGROUND_SERVICE, false);
 645        if (needsForegroundService) {
 646            Log.d(Config.LOGTAG, "toggle forced foreground service after receiving event (action=" + action + ")");
 647            toggleForegroundService(true);
 648        }
 649        String pushedAccountHash = null;
 650        boolean interactive = false;
 651        if (action != null) {
 652            final String uuid = intent.getStringExtra("uuid");
 653            switch (action) {
 654                case QuickConversationsService.SMS_RETRIEVED_ACTION:
 655                    mQuickConversationsService.handleSmsReceived(intent);
 656                    break;
 657                case ConnectivityManager.CONNECTIVITY_ACTION:
 658                    if (hasInternetConnection()) {
 659                        if (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL > 0) {
 660                            schedulePostConnectivityChange();
 661                        }
 662                        if (Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
 663                            resetAllAttemptCounts(true, false);
 664                        }
 665                        Resolver.clearCache();
 666                    }
 667                    break;
 668                case Intent.ACTION_SHUTDOWN:
 669                    logoutAndSave(true);
 670                    return START_NOT_STICKY;
 671                case ACTION_CLEAR_NOTIFICATION:
 672                    mNotificationExecutor.execute(() -> {
 673                        try {
 674                            final Conversation c = findConversationByUuid(uuid);
 675                            if (c != null) {
 676                                mNotificationService.clear(c);
 677                            } else {
 678                                mNotificationService.clear();
 679                            }
 680                            restoredFromDatabaseLatch.await();
 681
 682                        } catch (InterruptedException e) {
 683                            Log.d(Config.LOGTAG, "unable to process clear notification");
 684                        }
 685                    });
 686                    break;
 687                case ACTION_DISMISS_CALL: {
 688                    final String sessionId = intent.getStringExtra(RtpSessionActivity.EXTRA_SESSION_ID);
 689                    Log.d(Config.LOGTAG, "received intent to dismiss call with session id " + sessionId);
 690                    mJingleConnectionManager.rejectRtpSession(sessionId);
 691                    break;
 692                }
 693                case TorServiceUtils.ACTION_STATUS:
 694                    final String status = intent.getStringExtra(TorServiceUtils.EXTRA_STATUS);
 695                    //TODO port and host are in 'extras' - but this may not be a reliable source?
 696                    if ("ON".equals(status)) {
 697                        handleOrbotStartedEvent();
 698                        return START_STICKY;
 699                    }
 700                    break;
 701                case ACTION_END_CALL: {
 702                    final String sessionId = intent.getStringExtra(RtpSessionActivity.EXTRA_SESSION_ID);
 703                    Log.d(Config.LOGTAG, "received intent to end call with session id " + sessionId);
 704                    mJingleConnectionManager.endRtpSession(sessionId);
 705                }
 706                break;
 707                case ACTION_PROVISION_ACCOUNT: {
 708                    final String address = intent.getStringExtra("address");
 709                    final String password = intent.getStringExtra("password");
 710                    if (QuickConversationsService.isQuicksy() || Strings.isNullOrEmpty(address) || Strings.isNullOrEmpty(password)) {
 711                        break;
 712                    }
 713                    provisionAccount(address, password);
 714                    break;
 715                }
 716                case ACTION_DISMISS_ERROR_NOTIFICATIONS:
 717                    dismissErrorNotifications();
 718                    break;
 719                case ACTION_TRY_AGAIN:
 720                    resetAllAttemptCounts(false, true);
 721                    interactive = true;
 722                    break;
 723                case ACTION_REPLY_TO_CONVERSATION:
 724                    Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
 725                    if (remoteInput == null) {
 726                        break;
 727                    }
 728                    final CharSequence body = remoteInput.getCharSequence("text_reply");
 729                    final boolean dismissNotification = intent.getBooleanExtra("dismiss_notification", false);
 730                    final String lastMessageUuid = intent.getStringExtra("last_message_uuid");
 731                    if (body == null || body.length() <= 0) {
 732                        break;
 733                    }
 734                    mNotificationExecutor.execute(() -> {
 735                        try {
 736                            restoredFromDatabaseLatch.await();
 737                            final Conversation c = findConversationByUuid(uuid);
 738                            if (c != null) {
 739                                directReply(c, body.toString(), lastMessageUuid, dismissNotification);
 740                            }
 741                        } catch (InterruptedException e) {
 742                            Log.d(Config.LOGTAG, "unable to process direct reply");
 743                        }
 744                    });
 745                    break;
 746                case ACTION_MARK_AS_READ:
 747                    mNotificationExecutor.execute(() -> {
 748                        final Conversation c = findConversationByUuid(uuid);
 749                        if (c == null) {
 750                            Log.d(Config.LOGTAG, "received mark read intent for unknown conversation (" + uuid + ")");
 751                            return;
 752                        }
 753                        try {
 754                            restoredFromDatabaseLatch.await();
 755                            sendReadMarker(c, null);
 756                        } catch (InterruptedException e) {
 757                            Log.d(Config.LOGTAG, "unable to process notification read marker for conversation " + c.getName());
 758                        }
 759
 760                    });
 761                    break;
 762                case ACTION_SNOOZE:
 763                    mNotificationExecutor.execute(() -> {
 764                        final Conversation c = findConversationByUuid(uuid);
 765                        if (c == null) {
 766                            Log.d(Config.LOGTAG, "received snooze intent for unknown conversation (" + uuid + ")");
 767                            return;
 768                        }
 769                        c.setMutedTill(System.currentTimeMillis() + 30 * 60 * 1000);
 770                        mNotificationService.clear(c);
 771                        updateConversation(c);
 772                    });
 773                case AudioManager.RINGER_MODE_CHANGED_ACTION:
 774                case NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED:
 775                    if (dndOnSilentMode()) {
 776                        refreshAllPresences();
 777                    }
 778                    break;
 779                case Intent.ACTION_SCREEN_ON:
 780                    deactivateGracePeriod();
 781                case Intent.ACTION_USER_PRESENT:
 782                case Intent.ACTION_SCREEN_OFF:
 783                    if (awayWhenScreenLocked()) {
 784                        refreshAllPresences();
 785                    }
 786                    break;
 787                case ACTION_FCM_TOKEN_REFRESH:
 788                    refreshAllFcmTokens();
 789                    break;
 790                case ACTION_IDLE_PING:
 791                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
 792                        scheduleNextIdlePing();
 793                    }
 794                    break;
 795                case ACTION_FCM_MESSAGE_RECEIVED:
 796                    pushedAccountHash = intent.getStringExtra("account");
 797                    Log.d(Config.LOGTAG, "push message arrived in service. account=" + pushedAccountHash);
 798                    break;
 799                case Intent.ACTION_SEND:
 800                    Uri uri = intent.getData();
 801                    if (uri != null) {
 802                        Log.d(Config.LOGTAG, "received uri permission for " + uri.toString());
 803                    }
 804                    return START_STICKY;
 805            }
 806        }
 807        synchronized (this) {
 808            WakeLockHelper.acquire(wakeLock);
 809            boolean pingNow = ConnectivityManager.CONNECTIVITY_ACTION.equals(action) || (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL > 0 && ACTION_POST_CONNECTIVITY_CHANGE.equals(action));
 810            final HashSet<Account> pingCandidates = new HashSet<>();
 811            final String androidId = PhoneHelper.getAndroidId(this);
 812            for (Account account : accounts) {
 813                final boolean pushWasMeantForThisAccount = CryptoHelper.getAccountFingerprint(account, androidId).equals(pushedAccountHash);
 814                pingNow |= processAccountState(account,
 815                        interactive,
 816                        "ui".equals(action),
 817                        pushWasMeantForThisAccount,
 818                        pingCandidates);
 819            }
 820            if (pingNow) {
 821                for (Account account : pingCandidates) {
 822                    final boolean lowTimeout = isInLowPingTimeoutMode(account);
 823                    account.getXmppConnection().sendPing();
 824                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + " send ping (action=" + action + ",lowTimeout=" + lowTimeout + ")");
 825                    scheduleWakeUpCall(lowTimeout ? Config.LOW_PING_TIMEOUT : Config.PING_TIMEOUT, account.getUuid().hashCode());
 826                }
 827            }
 828            WakeLockHelper.release(wakeLock);
 829        }
 830        if (SystemClock.elapsedRealtime() - mLastExpiryRun.get() >= Config.EXPIRY_INTERVAL) {
 831            expireOldMessages();
 832        }
 833        return START_STICKY;
 834    }
 835
 836    private void handleOrbotStartedEvent() {
 837        for (final Account account : accounts) {
 838            if (account.getStatus() == Account.State.TOR_NOT_AVAILABLE) {
 839                reconnectAccount(account, true, false);
 840            }
 841        }
 842    }
 843
 844    private boolean processAccountState(Account account, boolean interactive, boolean isUiAction, boolean isAccountPushed, HashSet<Account> pingCandidates) {
 845        boolean pingNow = false;
 846        if (account.getStatus().isAttemptReconnect()) {
 847            if (!hasInternetConnection()) {
 848                account.setStatus(Account.State.NO_INTERNET);
 849                if (statusListener != null) {
 850                    statusListener.onStatusChanged(account);
 851                }
 852            } else {
 853                if (account.getStatus() == Account.State.NO_INTERNET) {
 854                    account.setStatus(Account.State.OFFLINE);
 855                    if (statusListener != null) {
 856                        statusListener.onStatusChanged(account);
 857                    }
 858                }
 859                if (account.getStatus() == Account.State.ONLINE) {
 860                    synchronized (mLowPingTimeoutMode) {
 861                        long lastReceived = account.getXmppConnection().getLastPacketReceived();
 862                        long lastSent = account.getXmppConnection().getLastPingSent();
 863                        long pingInterval = isUiAction ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
 864                        long msToNextPing = (Math.max(lastReceived, lastSent) + pingInterval) - SystemClock.elapsedRealtime();
 865                        int pingTimeout = mLowPingTimeoutMode.contains(account.getJid().asBareJid()) ? Config.LOW_PING_TIMEOUT * 1000 : Config.PING_TIMEOUT * 1000;
 866                        long pingTimeoutIn = (lastSent + pingTimeout) - SystemClock.elapsedRealtime();
 867                        if (lastSent > lastReceived) {
 868                            if (pingTimeoutIn < 0) {
 869                                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ping timeout");
 870                                this.reconnectAccount(account, true, interactive);
 871                            } else {
 872                                int secs = (int) (pingTimeoutIn / 1000);
 873                                this.scheduleWakeUpCall(secs, account.getUuid().hashCode());
 874                            }
 875                        } else {
 876                            pingCandidates.add(account);
 877                            if (isAccountPushed) {
 878                                pingNow = true;
 879                                if (mLowPingTimeoutMode.add(account.getJid().asBareJid())) {
 880                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": entering low ping timeout mode");
 881                                }
 882                            } else if (msToNextPing <= 0) {
 883                                pingNow = true;
 884                            } else {
 885                                this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
 886                                if (mLowPingTimeoutMode.remove(account.getJid().asBareJid())) {
 887                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": leaving low ping timeout mode");
 888                                }
 889                            }
 890                        }
 891                    }
 892                } else if (account.getStatus() == Account.State.OFFLINE) {
 893                    reconnectAccount(account, true, interactive);
 894                } else if (account.getStatus() == Account.State.CONNECTING) {
 895                    long secondsSinceLastConnect = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000;
 896                    long secondsSinceLastDisco = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastDiscoStarted()) / 1000;
 897                    long discoTimeout = Config.CONNECT_DISCO_TIMEOUT - secondsSinceLastDisco;
 898                    long timeout = Config.CONNECT_TIMEOUT - secondsSinceLastConnect;
 899                    if (timeout < 0) {
 900                        Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting (secondsSinceLast=" + secondsSinceLastConnect + ")");
 901                        account.getXmppConnection().resetAttemptCount(false);
 902                        reconnectAccount(account, true, interactive);
 903                    } else if (discoTimeout < 0) {
 904                        account.getXmppConnection().sendDiscoTimeout();
 905                        scheduleWakeUpCall((int) Math.min(timeout, discoTimeout), account.getUuid().hashCode());
 906                    } else {
 907                        scheduleWakeUpCall((int) Math.min(timeout, discoTimeout), account.getUuid().hashCode());
 908                    }
 909                } else {
 910                    if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
 911                        reconnectAccount(account, true, interactive);
 912                    }
 913                }
 914            }
 915        }
 916        return pingNow;
 917    }
 918
 919    public void reinitializeMuclumbusService() {
 920        mChannelDiscoveryService.initializeMuclumbusService();
 921    }
 922
 923    public void discoverChannels(String query, ChannelDiscoveryService.Method method, ChannelDiscoveryService.OnChannelSearchResultsFound onChannelSearchResultsFound) {
 924        mChannelDiscoveryService.discover(Strings.nullToEmpty(query).trim(), method, onChannelSearchResultsFound);
 925    }
 926
 927    public boolean isDataSaverDisabled() {
 928        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 929            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
 930            return !connectivityManager.isActiveNetworkMetered()
 931                    || connectivityManager.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
 932        } else {
 933            return true;
 934        }
 935    }
 936
 937    private void directReply(final Conversation conversation, final String body, final String lastMessageUuid, final boolean dismissAfterReply) {
 938        final Message inReplyTo = lastMessageUuid == null ? null : conversation.findMessageWithUuid(lastMessageUuid);
 939        final Message message = new Message(conversation, body, conversation.getNextEncryption());
 940        if (inReplyTo != null && inReplyTo.isPrivateMessage()) {
 941            Message.configurePrivateMessage(message, inReplyTo.getCounterpart());
 942        }
 943        message.markUnread();
 944        if (message.getEncryption() == Message.ENCRYPTION_PGP) {
 945            getPgpEngine().encrypt(message, new UiCallback<Message>() {
 946                @Override
 947                public void success(Message message) {
 948                    if (dismissAfterReply) {
 949                        markRead((Conversation) message.getConversation(), true);
 950                    } else {
 951                        mNotificationService.pushFromDirectReply(message);
 952                    }
 953                }
 954
 955                @Override
 956                public void error(int errorCode, Message object) {
 957
 958                }
 959
 960                @Override
 961                public void userInputRequired(PendingIntent pi, Message object) {
 962
 963                }
 964            });
 965        } else {
 966            sendMessage(message);
 967            if (dismissAfterReply) {
 968                markRead(conversation, true);
 969            } else {
 970                mNotificationService.pushFromDirectReply(message);
 971            }
 972        }
 973    }
 974
 975    private boolean dndOnSilentMode() {
 976        return getBooleanPreference(SettingsActivity.DND_ON_SILENT_MODE, R.bool.dnd_on_silent_mode);
 977    }
 978
 979    private boolean manuallyChangePresence() {
 980        return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
 981    }
 982
 983    private boolean treatVibrateAsSilent() {
 984        return getBooleanPreference(SettingsActivity.TREAT_VIBRATE_AS_SILENT, R.bool.treat_vibrate_as_silent);
 985    }
 986
 987    private boolean awayWhenScreenLocked() {
 988        return getBooleanPreference(SettingsActivity.AWAY_WHEN_SCREEN_IS_OFF, R.bool.away_when_screen_off);
 989    }
 990
 991    private String getCompressPicturesPreference() {
 992        return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression));
 993    }
 994
 995    private Presence.Status getTargetPresence() {
 996        if (dndOnSilentMode() && isPhoneSilenced()) {
 997            return Presence.Status.DND;
 998        } else if (awayWhenScreenLocked() && isScreenLocked()) {
 999            return Presence.Status.AWAY;
1000        } else {
1001            return Presence.Status.ONLINE;
1002        }
1003    }
1004
1005    public boolean isScreenLocked() {
1006        final KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
1007        final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
1008        final boolean locked = keyguardManager != null && keyguardManager.isKeyguardLocked();
1009        final boolean interactive = powerManager != null && powerManager.isInteractive();
1010        return locked || !interactive;
1011    }
1012
1013    private boolean isPhoneSilenced() {
1014        final boolean notificationDnd;
1015        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1016            final NotificationManager notificationManager = getSystemService(NotificationManager.class);
1017            final int filter = notificationManager == null ? NotificationManager.INTERRUPTION_FILTER_UNKNOWN : notificationManager.getCurrentInterruptionFilter();
1018            notificationDnd = filter >= NotificationManager.INTERRUPTION_FILTER_PRIORITY;
1019        } else {
1020            notificationDnd = false;
1021        }
1022        final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
1023        final int ringerMode = audioManager == null ? AudioManager.RINGER_MODE_NORMAL : audioManager.getRingerMode();
1024        try {
1025            if (treatVibrateAsSilent()) {
1026                return notificationDnd || ringerMode != AudioManager.RINGER_MODE_NORMAL;
1027            } else {
1028                return notificationDnd || ringerMode == AudioManager.RINGER_MODE_SILENT;
1029            }
1030        } catch (Throwable throwable) {
1031            Log.d(Config.LOGTAG, "platform bug in isPhoneSilenced (" + throwable.getMessage() + ")");
1032            return notificationDnd;
1033        }
1034    }
1035
1036    private void resetAllAttemptCounts(boolean reallyAll, boolean retryImmediately) {
1037        Log.d(Config.LOGTAG, "resetting all attempt counts");
1038        for (Account account : accounts) {
1039            if (account.hasErrorStatus() || reallyAll) {
1040                final XmppConnection connection = account.getXmppConnection();
1041                if (connection != null) {
1042                    connection.resetAttemptCount(retryImmediately);
1043                }
1044            }
1045            if (account.setShowErrorNotification(true)) {
1046                mDatabaseWriterExecutor.execute(() -> databaseBackend.updateAccount(account));
1047            }
1048        }
1049        mNotificationService.updateErrorNotification();
1050    }
1051
1052    private void dismissErrorNotifications() {
1053        for (final Account account : this.accounts) {
1054            if (account.hasErrorStatus()) {
1055                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": dismissing error notification");
1056                if (account.setShowErrorNotification(false)) {
1057                    mDatabaseWriterExecutor.execute(() -> databaseBackend.updateAccount(account));
1058                }
1059            }
1060        }
1061    }
1062
1063    private void expireOldMessages() {
1064        expireOldMessages(false);
1065    }
1066
1067    public void expireOldMessages(final boolean resetHasMessagesLeftOnServer) {
1068        mLastExpiryRun.set(SystemClock.elapsedRealtime());
1069        mDatabaseWriterExecutor.execute(() -> {
1070            long timestamp = getAutomaticMessageDeletionDate();
1071            if (timestamp > 0) {
1072                databaseBackend.expireOldMessages(timestamp);
1073                synchronized (XmppConnectionService.this.conversations) {
1074                    for (Conversation conversation : XmppConnectionService.this.conversations) {
1075                        conversation.expireOldMessages(timestamp);
1076                        if (resetHasMessagesLeftOnServer) {
1077                            conversation.messagesLoaded.set(true);
1078                            conversation.setHasMessagesLeftOnServer(true);
1079                        }
1080                    }
1081                }
1082                updateConversationUi();
1083            }
1084        });
1085    }
1086
1087    public boolean hasInternetConnection() {
1088        final ConnectivityManager cm = ContextCompat.getSystemService(this, ConnectivityManager.class);
1089        if (cm == null) {
1090            return true; //if internet connection can not be checked it is probably best to just try
1091        }
1092        try {
1093            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
1094                final Network activeNetwork = cm.getActiveNetwork();
1095                final NetworkCapabilities capabilities = activeNetwork == null ? null : cm.getNetworkCapabilities(activeNetwork);
1096                return capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1097            } else {
1098                final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
1099                return networkInfo != null && (networkInfo.isConnected() || networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET);
1100            }
1101        } catch (final RuntimeException e) {
1102            Log.d(Config.LOGTAG, "unable to check for internet connection", e);
1103            return true; //if internet connection can not be checked it is probably best to just try
1104        }
1105    }
1106
1107    @SuppressLint("TrulyRandom")
1108    @Override
1109    public void onCreate() {
1110        if (Compatibility.runsTwentySix()) {
1111            mNotificationService.initializeChannels();
1112        }
1113        mChannelDiscoveryService.initializeMuclumbusService();
1114        mForceDuringOnCreate.set(Compatibility.runsAndTargetsTwentySix(this));
1115        toggleForegroundService();
1116        this.destroyed = false;
1117        OmemoSetting.load(this);
1118        ExceptionHelper.init(getApplicationContext());
1119        try {
1120            Security.insertProviderAt(Conscrypt.newProvider(), 1);
1121        } catch (Throwable throwable) {
1122            Log.e(Config.LOGTAG, "unable to initialize security provider", throwable);
1123        }
1124        Resolver.init(this);
1125        this.mRandom = new SecureRandom();
1126        updateMemorizingTrustmanager();
1127        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
1128        final int cacheSize = maxMemory / 8;
1129        this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
1130            @Override
1131            protected int sizeOf(final String key, final Bitmap bitmap) {
1132                return bitmap.getByteCount() / 1024;
1133            }
1134        };
1135        if (mLastActivity == 0) {
1136            mLastActivity = getPreferences().getLong(SETTING_LAST_ACTIVITY_TS, System.currentTimeMillis());
1137        }
1138
1139        Log.d(Config.LOGTAG, "initializing database...");
1140        this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
1141        Log.d(Config.LOGTAG, "restoring accounts...");
1142        this.accounts = databaseBackend.getAccounts();
1143        final SharedPreferences.Editor editor = getPreferences().edit();
1144        if (this.accounts.size() == 0 && Arrays.asList("Sony", "Sony Ericsson").contains(Build.MANUFACTURER)) {
1145            editor.putBoolean(SettingsActivity.KEEP_FOREGROUND_SERVICE, true);
1146            Log.d(Config.LOGTAG, Build.MANUFACTURER + " is on blacklist. enabling foreground service");
1147        }
1148        final boolean hasEnabledAccounts = hasEnabledAccounts();
1149        editor.putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
1150        editor.apply();
1151        toggleSetProfilePictureActivity(hasEnabledAccounts);
1152
1153        restoreFromDatabase();
1154
1155        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
1156            startContactObserver();
1157        }
1158        FILE_OBSERVER_EXECUTOR.execute(fileBackend::deleteHistoricAvatarPath);
1159        if (Compatibility.hasStoragePermission(this)) {
1160            Log.d(Config.LOGTAG, "starting file observer");
1161            FILE_OBSERVER_EXECUTOR.execute(this.fileObserver::startWatching);
1162            FILE_OBSERVER_EXECUTOR.execute(this::checkForDeletedFiles);
1163        }
1164        if (Config.supportOpenPgp()) {
1165            this.pgpServiceConnection = new OpenPgpServiceConnection(this, "org.sufficientlysecure.keychain", new OpenPgpServiceConnection.OnBound() {
1166                @Override
1167                public void onBound(IOpenPgpService2 service) {
1168                    for (Account account : accounts) {
1169                        final PgpDecryptionService pgp = account.getPgpDecryptionService();
1170                        if (pgp != null) {
1171                            pgp.continueDecryption(true);
1172                        }
1173                    }
1174                }
1175
1176                @Override
1177                public void onError(Exception e) {
1178                }
1179            });
1180            this.pgpServiceConnection.bindToService();
1181        }
1182
1183        final PowerManager pm = ContextCompat.getSystemService(this, PowerManager.class);
1184        this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Conversations:Service");
1185
1186        toggleForegroundService();
1187        updateUnreadCountBadge();
1188        toggleScreenEventReceiver();
1189        final IntentFilter intentFilter = new IntentFilter();
1190        intentFilter.addAction(TorServiceUtils.ACTION_STATUS);
1191        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1192            scheduleNextIdlePing();
1193            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
1194                intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
1195            }
1196            intentFilter.addAction(NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED);
1197        }
1198        registerReceiver(this.mInternalEventReceiver, intentFilter);
1199        mForceDuringOnCreate.set(false);
1200        toggleForegroundService();
1201        setupPhoneStateListener();
1202    }
1203
1204
1205    private void setupPhoneStateListener() {
1206        final TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
1207        if (telephonyManager == null || Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
1208            return;
1209        }
1210        telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
1211    }
1212
1213    public boolean isPhoneInCall() {
1214        return isPhoneInCall.get();
1215    }
1216
1217    private void checkForDeletedFiles() {
1218        if (destroyed) {
1219            Log.d(Config.LOGTAG, "Do not check for deleted files because service has been destroyed");
1220            return;
1221        }
1222        final long start = SystemClock.elapsedRealtime();
1223        final List<DatabaseBackend.FilePathInfo> relativeFilePaths = databaseBackend.getFilePathInfo();
1224        final List<DatabaseBackend.FilePathInfo> changed = new ArrayList<>();
1225        for (final DatabaseBackend.FilePathInfo filePath : relativeFilePaths) {
1226            if (destroyed) {
1227                Log.d(Config.LOGTAG, "Stop checking for deleted files because service has been destroyed");
1228                return;
1229            }
1230            final File file = fileBackend.getFileForPath(filePath.path);
1231            if (filePath.setDeleted(!file.exists())) {
1232                changed.add(filePath);
1233            }
1234        }
1235        final long duration = SystemClock.elapsedRealtime() - start;
1236        Log.d(Config.LOGTAG, "found " + changed.size() + " changed files on start up. total=" + relativeFilePaths.size() + ". (" + duration + "ms)");
1237        if (changed.size() > 0) {
1238            databaseBackend.markFilesAsChanged(changed);
1239            markChangedFiles(changed);
1240        }
1241    }
1242
1243    public void startContactObserver() {
1244        getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, new ContentObserver(null) {
1245            @Override
1246            public void onChange(boolean selfChange) {
1247                super.onChange(selfChange);
1248                if (restoredFromDatabaseLatch.getCount() == 0) {
1249                    loadPhoneContacts();
1250                }
1251            }
1252        });
1253    }
1254
1255    @Override
1256    public void onTrimMemory(int level) {
1257        super.onTrimMemory(level);
1258        if (level >= TRIM_MEMORY_COMPLETE) {
1259            Log.d(Config.LOGTAG, "clear cache due to low memory");
1260            getBitmapCache().evictAll();
1261        }
1262    }
1263
1264    @Override
1265    public void onDestroy() {
1266        try {
1267            unregisterReceiver(this.mInternalEventReceiver);
1268            unregisterReceiver(this.mInternalScreenEventReceiver);
1269        } catch (final IllegalArgumentException e) {
1270            //ignored
1271        }
1272        destroyed = false;
1273        fileObserver.stopWatching();
1274        super.onDestroy();
1275    }
1276
1277    public void restartFileObserver() {
1278        Log.d(Config.LOGTAG, "restarting file observer");
1279        FILE_OBSERVER_EXECUTOR.execute(this.fileObserver::restartWatching);
1280        FILE_OBSERVER_EXECUTOR.execute(this::checkForDeletedFiles);
1281    }
1282
1283    public void toggleScreenEventReceiver() {
1284        if (awayWhenScreenLocked() && !manuallyChangePresence()) {
1285            final IntentFilter filter = new IntentFilter();
1286            filter.addAction(Intent.ACTION_SCREEN_ON);
1287            filter.addAction(Intent.ACTION_SCREEN_OFF);
1288            filter.addAction(Intent.ACTION_USER_PRESENT);
1289            registerReceiver(this.mInternalScreenEventReceiver, filter);
1290        } else {
1291            try {
1292                unregisterReceiver(this.mInternalScreenEventReceiver);
1293            } catch (IllegalArgumentException e) {
1294                //ignored
1295            }
1296        }
1297    }
1298
1299    public void toggleForegroundService() {
1300        toggleForegroundService(false);
1301    }
1302
1303    public void setOngoingCall(AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
1304        ongoingCall.set(new OngoingCall(id, media, reconnecting));
1305        toggleForegroundService(false);
1306    }
1307
1308    public void removeOngoingCall() {
1309        ongoingCall.set(null);
1310        toggleForegroundService(false);
1311    }
1312
1313    private void toggleForegroundService(boolean force) {
1314        final boolean status;
1315        final OngoingCall ongoing = ongoingCall.get();
1316        if (force || mForceDuringOnCreate.get() || mForceForegroundService.get() || ongoing != null || (Compatibility.keepForegroundService(this) && hasEnabledAccounts())) {
1317            final Notification notification;
1318            final int id;
1319            if (ongoing != null) {
1320                notification = this.mNotificationService.getOngoingCallNotification(ongoing);
1321                id = NotificationService.ONGOING_CALL_NOTIFICATION_ID;
1322                startForeground(id, notification);
1323                mNotificationService.cancel(NotificationService.FOREGROUND_NOTIFICATION_ID);
1324            } else {
1325                notification = this.mNotificationService.createForegroundNotification();
1326                id = NotificationService.FOREGROUND_NOTIFICATION_ID;
1327                startForeground(id, notification);
1328            }
1329
1330            if (!mForceForegroundService.get()) {
1331                mNotificationService.notify(id, notification);
1332            }
1333            status = true;
1334        } else {
1335            stopForeground(true);
1336            status = false;
1337        }
1338        if (!mForceForegroundService.get()) {
1339            mNotificationService.cancel(NotificationService.FOREGROUND_NOTIFICATION_ID);
1340        }
1341        if (ongoing == null) {
1342            mNotificationService.cancel(NotificationService.ONGOING_CALL_NOTIFICATION_ID);
1343        }
1344        Log.d(Config.LOGTAG, "ForegroundService: " + (status ? "on" : "off"));
1345    }
1346
1347    public boolean foregroundNotificationNeedsUpdatingWhenErrorStateChanges() {
1348        return !mForceForegroundService.get() && ongoingCall.get() == null && Compatibility.keepForegroundService(this) && hasEnabledAccounts();
1349    }
1350
1351    @Override
1352    public void onTaskRemoved(final Intent rootIntent) {
1353        super.onTaskRemoved(rootIntent);
1354        if ((Compatibility.keepForegroundService(this) && hasEnabledAccounts()) || mForceForegroundService.get() || ongoingCall.get() != null) {
1355            Log.d(Config.LOGTAG, "ignoring onTaskRemoved because foreground service is activated");
1356        } else {
1357            this.logoutAndSave(false);
1358        }
1359    }
1360
1361    private void logoutAndSave(boolean stop) {
1362        int activeAccounts = 0;
1363        for (final Account account : accounts) {
1364            if (account.getStatus() != Account.State.DISABLED) {
1365                databaseBackend.writeRoster(account.getRoster());
1366                activeAccounts++;
1367            }
1368            if (account.getXmppConnection() != null) {
1369                new Thread(() -> disconnect(account, false)).start();
1370            }
1371        }
1372        if (stop || activeAccounts == 0) {
1373            Log.d(Config.LOGTAG, "good bye");
1374            stopSelf();
1375        }
1376    }
1377
1378    private void schedulePostConnectivityChange() {
1379        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1380        if (alarmManager == null) {
1381            return;
1382        }
1383        final long triggerAtMillis = SystemClock.elapsedRealtime() + (Config.POST_CONNECTIVITY_CHANGE_PING_INTERVAL * 1000);
1384        final Intent intent = new Intent(this, EventReceiver.class);
1385        intent.setAction(ACTION_POST_CONNECTIVITY_CHANGE);
1386        try {
1387            final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
1388            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1389                alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1390            } else {
1391                alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
1392            }
1393        } catch (RuntimeException e) {
1394            Log.e(Config.LOGTAG, "unable to schedule alarm for post connectivity change", e);
1395        }
1396    }
1397
1398    public void scheduleWakeUpCall(int seconds, int requestCode) {
1399        final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
1400        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1401        if (alarmManager == null) {
1402            return;
1403        }
1404        final Intent intent = new Intent(this, EventReceiver.class);
1405        intent.setAction("ping");
1406        try {
1407            final PendingIntent pendingIntent;
1408            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
1409                pendingIntent =
1410                        PendingIntent.getBroadcast(
1411                                this, requestCode, intent, PendingIntent.FLAG_IMMUTABLE);
1412            } else {
1413                pendingIntent =
1414                        PendingIntent.getBroadcast(
1415                                this, requestCode, intent, 0);
1416            }
1417            alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1418        } catch (RuntimeException e) {
1419            Log.e(Config.LOGTAG, "unable to schedule alarm for ping", e);
1420        }
1421    }
1422
1423    @TargetApi(Build.VERSION_CODES.M)
1424    private void scheduleNextIdlePing() {
1425        final long timeToWake = SystemClock.elapsedRealtime() + (Config.IDLE_PING_INTERVAL * 1000);
1426        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1427        if (alarmManager == null) {
1428            return;
1429        }
1430        final Intent intent = new Intent(this, EventReceiver.class);
1431        intent.setAction(ACTION_IDLE_PING);
1432        try {
1433            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
1434            alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1435        } catch (RuntimeException e) {
1436            Log.d(Config.LOGTAG, "unable to schedule alarm for idle ping", e);
1437        }
1438    }
1439
1440    public XmppConnection createConnection(final Account account) {
1441        final XmppConnection connection = new XmppConnection(account, this);
1442        connection.setOnMessagePacketReceivedListener(this.mMessageParser);
1443        connection.setOnStatusChangedListener(this.statusListener);
1444        connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
1445        connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
1446        connection.setOnJinglePacketReceivedListener(((a, jp) -> mJingleConnectionManager.deliverPacket(a, jp)));
1447        connection.setOnBindListener(this.mOnBindListener);
1448        connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
1449        connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
1450        connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
1451        AxolotlService axolotlService = account.getAxolotlService();
1452        if (axolotlService != null) {
1453            connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
1454        }
1455        return connection;
1456    }
1457
1458    public void sendChatState(Conversation conversation) {
1459        if (sendChatStates()) {
1460            MessagePacket packet = mMessageGenerator.generateChatState(conversation);
1461            sendMessagePacket(conversation.getAccount(), packet);
1462        }
1463    }
1464
1465    private void sendFileMessage(final Message message, final boolean delay) {
1466        Log.d(Config.LOGTAG, "send file message");
1467        final Account account = message.getConversation().getAccount();
1468        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1469                || message.getConversation().getMode() == Conversation.MODE_MULTI) {
1470            mHttpConnectionManager.createNewUploadConnection(message, delay);
1471        } else {
1472            mJingleConnectionManager.startJingleFileTransfer(message);
1473        }
1474    }
1475
1476    public void sendMessage(final Message message) {
1477        sendMessage(message, false, false);
1478    }
1479
1480    private void sendMessage(final Message message, final boolean resend, final boolean delay) {
1481        final Account account = message.getConversation().getAccount();
1482        if (account.setShowErrorNotification(true)) {
1483            databaseBackend.updateAccount(account);
1484            mNotificationService.updateErrorNotification();
1485        }
1486        final Conversation conversation = (Conversation) message.getConversation();
1487        account.deactivateGracePeriod();
1488
1489
1490        if (QuickConversationsService.isQuicksy() && conversation.getMode() == Conversation.MODE_SINGLE) {
1491            final Contact contact = conversation.getContact();
1492            if (!contact.showInRoster() && contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1493                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": adding " + contact.getJid() + " on sending message");
1494                createContact(contact, true);
1495            }
1496        }
1497
1498        MessagePacket packet = null;
1499        final boolean addToConversation = (conversation.getMode() != Conversation.MODE_MULTI
1500                || !Patches.BAD_MUC_REFLECTION.contains(account.getServerIdentity()))
1501                && !message.edited();
1502        boolean saveInDb = addToConversation;
1503        message.setStatus(Message.STATUS_WAITING);
1504
1505        if (message.getEncryption() != Message.ENCRYPTION_NONE && conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous()) {
1506            if (conversation.setAttribute(Conversation.ATTRIBUTE_FORMERLY_PRIVATE_NON_ANONYMOUS, true)) {
1507                databaseBackend.updateConversation(conversation);
1508            }
1509        }
1510
1511        final boolean inProgressJoin = isJoinInProgress(conversation);
1512
1513
1514        if (account.isOnlineAndConnected() && !inProgressJoin) {
1515            switch (message.getEncryption()) {
1516                case Message.ENCRYPTION_NONE:
1517                    if (message.needsUploading()) {
1518                        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1519                                || conversation.getMode() == Conversation.MODE_MULTI
1520                                || message.fixCounterpart()) {
1521                            this.sendFileMessage(message, delay);
1522                        } else {
1523                            break;
1524                        }
1525                    } else {
1526                        packet = mMessageGenerator.generateChat(message);
1527                    }
1528                    break;
1529                case Message.ENCRYPTION_PGP:
1530                case Message.ENCRYPTION_DECRYPTED:
1531                    if (message.needsUploading()) {
1532                        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1533                                || conversation.getMode() == Conversation.MODE_MULTI
1534                                || message.fixCounterpart()) {
1535                            this.sendFileMessage(message, delay);
1536                        } else {
1537                            break;
1538                        }
1539                    } else {
1540                        packet = mMessageGenerator.generatePgpChat(message);
1541                    }
1542                    break;
1543                case Message.ENCRYPTION_AXOLOTL:
1544                    message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1545                    if (message.needsUploading()) {
1546                        if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1547                                || conversation.getMode() == Conversation.MODE_MULTI
1548                                || message.fixCounterpart()) {
1549                            this.sendFileMessage(message, delay);
1550                        } else {
1551                            break;
1552                        }
1553                    } else {
1554                        XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
1555                        if (axolotlMessage == null) {
1556                            account.getAxolotlService().preparePayloadMessage(message, delay);
1557                        } else {
1558                            packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
1559                        }
1560                    }
1561                    break;
1562
1563            }
1564            if (packet != null) {
1565                if (account.getXmppConnection().getFeatures().sm()
1566                        || (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1567                    message.setStatus(Message.STATUS_UNSEND);
1568                } else {
1569                    message.setStatus(Message.STATUS_SEND);
1570                }
1571            }
1572        } else {
1573            switch (message.getEncryption()) {
1574                case Message.ENCRYPTION_DECRYPTED:
1575                    if (!message.needsUploading()) {
1576                        String pgpBody = message.getEncryptedBody();
1577                        String decryptedBody = message.getBody();
1578                        message.setBody(pgpBody); //TODO might throw NPE
1579                        message.setEncryption(Message.ENCRYPTION_PGP);
1580                        if (message.edited()) {
1581                            message.setBody(decryptedBody);
1582                            message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1583                            if (!databaseBackend.updateMessage(message, message.getEditedId())) {
1584                                Log.e(Config.LOGTAG, "error updated message in DB after edit");
1585                            }
1586                            updateConversationUi();
1587                            return;
1588                        } else {
1589                            databaseBackend.createMessage(message);
1590                            saveInDb = false;
1591                            message.setBody(decryptedBody);
1592                            message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1593                        }
1594                    }
1595                    break;
1596                case Message.ENCRYPTION_AXOLOTL:
1597                    message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1598                    break;
1599            }
1600        }
1601
1602
1603        boolean mucMessage = conversation.getMode() == Conversation.MODE_MULTI && !message.isPrivateMessage();
1604        if (mucMessage) {
1605            message.setCounterpart(conversation.getMucOptions().getSelf().getFullJid());
1606        }
1607
1608        if (resend) {
1609            if (packet != null && addToConversation) {
1610                if (account.getXmppConnection().getFeatures().sm() || mucMessage) {
1611                    markMessage(message, Message.STATUS_UNSEND);
1612                } else {
1613                    markMessage(message, Message.STATUS_SEND);
1614                }
1615            }
1616        } else {
1617            if (addToConversation) {
1618                conversation.add(message);
1619            }
1620            if (saveInDb) {
1621                databaseBackend.createMessage(message);
1622            } else if (message.edited()) {
1623                if (!databaseBackend.updateMessage(message, message.getEditedId())) {
1624                    Log.e(Config.LOGTAG, "error updated message in DB after edit");
1625                }
1626            }
1627            updateConversationUi();
1628        }
1629        if (packet != null) {
1630            if (delay) {
1631                mMessageGenerator.addDelay(packet, message.getTimeSent());
1632            }
1633            if (conversation.setOutgoingChatState(Config.DEFAULT_CHAT_STATE)) {
1634                if (this.sendChatStates()) {
1635                    packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
1636                }
1637            }
1638            sendMessagePacket(account, packet);
1639        }
1640    }
1641
1642    private boolean isJoinInProgress(final Conversation conversation) {
1643        final Account account = conversation.getAccount();
1644        synchronized (account.inProgressConferenceJoins) {
1645            if (conversation.getMode() == Conversational.MODE_MULTI) {
1646                final boolean inProgress = account.inProgressConferenceJoins.contains(conversation);
1647                final boolean pending = account.pendingConferenceJoins.contains(conversation);
1648                final boolean inProgressJoin = inProgress || pending;
1649                if (inProgressJoin) {
1650                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": holding back message to group. inProgress=" + inProgress + ", pending=" + pending);
1651                }
1652                return inProgressJoin;
1653            } else {
1654                return false;
1655            }
1656        }
1657    }
1658
1659    private void sendUnsentMessages(final Conversation conversation) {
1660        conversation.findWaitingMessages(message -> resendMessage(message, true));
1661    }
1662
1663    public void resendMessage(final Message message, final boolean delay) {
1664        sendMessage(message, true, delay);
1665    }
1666
1667    public void requestEasyOnboardingInvite(final Account account, final EasyOnboardingInvite.OnInviteRequested callback) {
1668        final XmppConnection connection = account.getXmppConnection();
1669        final Jid jid = connection == null ? null : connection.getJidForCommand(Namespace.EASY_ONBOARDING_INVITE);
1670        if (jid == null) {
1671            callback.inviteRequestFailed(getString(R.string.server_does_not_support_easy_onboarding_invites));
1672            return;
1673        }
1674        final IqPacket request = new IqPacket(IqPacket.TYPE.SET);
1675        request.setTo(jid);
1676        final Element command = request.addChild("command", Namespace.COMMANDS);
1677        command.setAttribute("node", Namespace.EASY_ONBOARDING_INVITE);
1678        command.setAttribute("action", "execute");
1679        sendIqPacket(account, request, (a, response) -> {
1680            if (response.getType() == IqPacket.TYPE.RESULT) {
1681                final Element resultCommand = response.findChild("command", Namespace.COMMANDS);
1682                final Element x = resultCommand == null ? null : resultCommand.findChild("x", Namespace.DATA);
1683                if (x != null) {
1684                    final Data data = Data.parse(x);
1685                    final String uri = data.getValue("uri");
1686                    final String landingUrl = data.getValue("landing-url");
1687                    if (uri != null) {
1688                        final EasyOnboardingInvite invite = new EasyOnboardingInvite(jid.getDomain().toEscapedString(), uri, landingUrl);
1689                        callback.inviteRequested(invite);
1690                        return;
1691                    }
1692                }
1693                callback.inviteRequestFailed(getString(R.string.unable_to_parse_invite));
1694                Log.d(Config.LOGTAG, response.toString());
1695            } else if (response.getType() == IqPacket.TYPE.ERROR) {
1696                callback.inviteRequestFailed(IqParser.errorMessage(response));
1697            } else {
1698                callback.inviteRequestFailed(getString(R.string.remote_server_timeout));
1699            }
1700        });
1701
1702    }
1703
1704    public void fetchRosterFromServer(final Account account) {
1705        final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1706        if (!"".equals(account.getRosterVersion())) {
1707            Log.d(Config.LOGTAG, account.getJid().asBareJid()
1708                    + ": fetching roster version " + account.getRosterVersion());
1709        } else {
1710            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching roster");
1711        }
1712        iqPacket.query(Namespace.ROSTER).setAttribute("ver", account.getRosterVersion());
1713        sendIqPacket(account, iqPacket, mIqParser);
1714    }
1715
1716    public void fetchBookmarks(final Account account) {
1717        final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1718        final Element query = iqPacket.query("jabber:iq:private");
1719        query.addChild("storage", Namespace.BOOKMARKS);
1720        final OnIqPacketReceived callback = (a, response) -> {
1721            if (response.getType() == IqPacket.TYPE.RESULT) {
1722                final Element query1 = response.query();
1723                final Element storage = query1.findChild("storage", "storage:bookmarks");
1724                Map<Jid, Bookmark> bookmarks = Bookmark.parseFromStorage(storage, account);
1725                processBookmarksInitial(a, bookmarks, false);
1726            } else {
1727                Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": could not fetch bookmarks");
1728            }
1729        };
1730        sendIqPacket(account, iqPacket, callback);
1731    }
1732
1733    public void fetchBookmarks2(final Account account) {
1734        final IqPacket retrieve = mIqGenerator.retrieveBookmarks();
1735        sendIqPacket(account, retrieve, new OnIqPacketReceived() {
1736            @Override
1737            public void onIqPacketReceived(final Account account, final IqPacket response) {
1738                if (response.getType() == IqPacket.TYPE.RESULT) {
1739                    final Element pubsub = response.findChild("pubsub", Namespace.PUBSUB);
1740                    final Map<Jid, Bookmark> bookmarks = Bookmark.parseFromPubsub(pubsub, account);
1741                    processBookmarksInitial(account, bookmarks, true);
1742                }
1743            }
1744        });
1745    }
1746
1747    public void processBookmarksInitial(Account account, Map<Jid, Bookmark> bookmarks, final boolean pep) {
1748        final Set<Jid> previousBookmarks = account.getBookmarkedJids();
1749        final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
1750        for (Bookmark bookmark : bookmarks.values()) {
1751            previousBookmarks.remove(bookmark.getJid().asBareJid());
1752            processModifiedBookmark(bookmark, pep, synchronizeWithBookmarks);
1753        }
1754        if (pep && synchronizeWithBookmarks) {
1755            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + previousBookmarks.size() + " bookmarks have been removed");
1756            for (Jid jid : previousBookmarks) {
1757                processDeletedBookmark(account, jid);
1758            }
1759        }
1760        account.setBookmarks(bookmarks);
1761    }
1762
1763    public void processDeletedBookmark(Account account, Jid jid) {
1764        final Conversation conversation = find(account, jid);
1765        if (conversation != null && conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
1766            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving destroyed conference (" + conversation.getJid() + ") after receiving pep");
1767            archiveConversation(conversation, false);
1768        }
1769    }
1770
1771    private void processModifiedBookmark(Bookmark bookmark, final boolean pep, final boolean synchronizeWithBookmarks) {
1772        final Account account = bookmark.getAccount();
1773        Conversation conversation = find(bookmark);
1774        if (conversation != null) {
1775            if (conversation.getMode() != Conversation.MODE_MULTI) {
1776                return;
1777            }
1778            bookmark.setConversation(conversation);
1779            if (pep && synchronizeWithBookmarks && !bookmark.autojoin()) {
1780                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conference (" + conversation.getJid() + ") after receiving pep");
1781                archiveConversation(conversation, false);
1782            } else {
1783                final MucOptions mucOptions = conversation.getMucOptions();
1784                if (mucOptions.getError() == MucOptions.Error.NICK_IN_USE) {
1785                    final String current = mucOptions.getActualNick();
1786                    final String proposed = mucOptions.getProposedNick();
1787                    if (current != null && !current.equals(proposed)) {
1788                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": proposed nick changed after bookmark push " + current + "->" + proposed);
1789                        joinMuc(conversation);
1790                    }
1791                }
1792            }
1793        } else if (synchronizeWithBookmarks && bookmark.autojoin()) {
1794            conversation = findOrCreateConversation(account, bookmark.getFullJid(), true, true, false);
1795            bookmark.setConversation(conversation);
1796        }
1797    }
1798
1799    public void processModifiedBookmark(Bookmark bookmark) {
1800        final boolean synchronizeWithBookmarks = synchronizeWithBookmarks();
1801        processModifiedBookmark(bookmark, true, synchronizeWithBookmarks);
1802    }
1803
1804    public void createBookmark(final Account account, final Bookmark bookmark) {
1805        account.putBookmark(bookmark);
1806        final XmppConnection connection = account.getXmppConnection();
1807        if (connection == null) {
1808            Log.d(Config.LOGTAG, account.getJid().asBareJid()+": no connection. ignoring bookmark creation");
1809        } else if (connection.getFeatures().bookmarks2()) {
1810            final Element item = mIqGenerator.publishBookmarkItem(bookmark);
1811            pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS2, item, bookmark.getJid().asBareJid().toEscapedString(), PublishOptions.persistentWhitelistAccessMaxItems());
1812        } else if (connection.getFeatures().bookmarksConversion()) {
1813            pushBookmarksPep(account);
1814        } else {
1815            pushBookmarksPrivateXml(account);
1816        }
1817    }
1818
1819    public void deleteBookmark(final Account account, final Bookmark bookmark) {
1820        account.removeBookmark(bookmark);
1821        final XmppConnection connection = account.getXmppConnection();
1822        if (connection.getFeatures().bookmarks2()) {
1823            IqPacket request = mIqGenerator.deleteItem(Namespace.BOOKMARKS2, bookmark.getJid().asBareJid().toEscapedString());
1824            sendIqPacket(account, request, (a, response) -> {
1825                if (response.getType() == IqPacket.TYPE.ERROR) {
1826                    Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": unable to delete bookmark " + response.getErrorCondition());
1827                }
1828            });
1829        } else if (connection.getFeatures().bookmarksConversion()) {
1830            pushBookmarksPep(account);
1831        } else {
1832            pushBookmarksPrivateXml(account);
1833        }
1834    }
1835
1836    private void pushBookmarksPrivateXml(Account account) {
1837        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
1838        IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1839        Element query = iqPacket.query("jabber:iq:private");
1840        Element storage = query.addChild("storage", "storage:bookmarks");
1841        for (Bookmark bookmark : account.getBookmarks()) {
1842            storage.addChild(bookmark);
1843        }
1844        sendIqPacket(account, iqPacket, mDefaultIqHandler);
1845    }
1846
1847    private void pushBookmarksPep(Account account) {
1848        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
1849        Element storage = new Element("storage", "storage:bookmarks");
1850        for (Bookmark bookmark : account.getBookmarks()) {
1851            storage.addChild(bookmark);
1852        }
1853        pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS, storage, "current", PublishOptions.persistentWhitelistAccess());
1854
1855    }
1856
1857    private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options) {
1858        pushNodeAndEnforcePublishOptions(account, node, element, id, options, true);
1859
1860    }
1861
1862    private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options, final boolean retry) {
1863        final IqPacket packet = mIqGenerator.publishElement(node, element, id, options);
1864        sendIqPacket(account, packet, (a, response) -> {
1865            if (response.getType() == IqPacket.TYPE.RESULT) {
1866                return;
1867            }
1868            if (retry && PublishOptions.preconditionNotMet(response)) {
1869                pushNodeConfiguration(account, node, options, new OnConfigurationPushed() {
1870                    @Override
1871                    public void onPushSucceeded() {
1872                        pushNodeAndEnforcePublishOptions(account, node, element, id, options, false);
1873                    }
1874
1875                    @Override
1876                    public void onPushFailed() {
1877                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to push node configuration (" + node + ")");
1878                    }
1879                });
1880            } else {
1881                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error publishing bookmarks (retry=" + retry + ") " + response);
1882            }
1883        });
1884    }
1885
1886    private void restoreFromDatabase() {
1887        synchronized (this.conversations) {
1888            final Map<String, Account> accountLookupTable = new Hashtable<>();
1889            for (Account account : this.accounts) {
1890                accountLookupTable.put(account.getUuid(), account);
1891            }
1892            Log.d(Config.LOGTAG, "restoring conversations...");
1893            final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
1894            this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1895            for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
1896                Conversation conversation = iterator.next();
1897                Account account = accountLookupTable.get(conversation.getAccountUuid());
1898                if (account != null) {
1899                    conversation.setAccount(account);
1900                } else {
1901                    Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
1902                    iterator.remove();
1903                }
1904            }
1905            long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
1906            Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
1907            Runnable runnable = () -> {
1908                if (DatabaseBackend.requiresMessageIndexRebuild()) {
1909                    DatabaseBackend.getInstance(this).rebuildMessagesIndex();
1910                }
1911                final long deletionDate = getAutomaticMessageDeletionDate();
1912                mLastExpiryRun.set(SystemClock.elapsedRealtime());
1913                if (deletionDate > 0) {
1914                    Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
1915                    databaseBackend.expireOldMessages(deletionDate);
1916                }
1917                Log.d(Config.LOGTAG, "restoring roster...");
1918                for (Account account : accounts) {
1919                    databaseBackend.readRoster(account.getRoster());
1920                    account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1921                }
1922                getBitmapCache().evictAll();
1923                loadPhoneContacts();
1924                Log.d(Config.LOGTAG, "restoring messages...");
1925                final long startMessageRestore = SystemClock.elapsedRealtime();
1926                final Conversation quickLoad = QuickLoader.get(this.conversations);
1927                if (quickLoad != null) {
1928                    restoreMessages(quickLoad);
1929                    updateConversationUi();
1930                    final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1931                    Log.d(Config.LOGTAG, "quickly restored " + quickLoad.getName() + " after " + diffMessageRestore + "ms");
1932                }
1933                for (Conversation conversation : this.conversations) {
1934                    if (quickLoad != conversation) {
1935                        restoreMessages(conversation);
1936                    }
1937                }
1938                mNotificationService.finishBacklog(false);
1939                restoredFromDatabaseLatch.countDown();
1940                final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1941                Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
1942                updateConversationUi();
1943            };
1944            mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
1945        }
1946    }
1947
1948    private void restoreMessages(Conversation conversation) {
1949        conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1950        conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
1951        conversation.findUnreadMessages(mNotificationService::pushFromBacklog);
1952    }
1953
1954    public void loadPhoneContacts() {
1955        mContactMergerExecutor.execute(() -> {
1956            Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
1957            Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1958            for (Account account : accounts) {
1959                List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts(JabberIdContact.class);
1960                for (JabberIdContact jidContact : contacts.values()) {
1961                    final Contact contact = account.getRoster().getContact(jidContact.getJid());
1962                    boolean needsCacheClean = contact.setPhoneContact(jidContact);
1963                    if (needsCacheClean) {
1964                        getAvatarService().clear(contact);
1965                    }
1966                    withSystemAccounts.remove(contact);
1967                }
1968                for (Contact contact : withSystemAccounts) {
1969                    boolean needsCacheClean = contact.unsetPhoneContact(JabberIdContact.class);
1970                    if (needsCacheClean) {
1971                        getAvatarService().clear(contact);
1972                    }
1973                }
1974            }
1975            Log.d(Config.LOGTAG, "finished merging phone contacts");
1976            mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
1977            updateRosterUi();
1978            mQuickConversationsService.considerSync();
1979        });
1980    }
1981
1982
1983    public void syncRoster(final Account account) {
1984        mRosterSyncTaskManager.execute(account, () -> databaseBackend.writeRoster(account.getRoster()));
1985    }
1986
1987    public List<Conversation> getConversations() {
1988        return this.conversations;
1989    }
1990
1991    private void markFileDeleted(final File file) {
1992        synchronized (FILENAMES_TO_IGNORE_DELETION) {
1993            if (FILENAMES_TO_IGNORE_DELETION.remove(file.getAbsolutePath())) {
1994                Log.d(Config.LOGTAG, "ignored deletion of " + file.getAbsolutePath());
1995                return;
1996            }
1997        }
1998        final boolean isInternalFile = fileBackend.isInternalFile(file);
1999        final List<String> uuids = databaseBackend.markFileAsDeleted(file, isInternalFile);
2000        Log.d(Config.LOGTAG, "deleted file " + file.getAbsolutePath() + " internal=" + isInternalFile + ", database hits=" + uuids.size());
2001        markUuidsAsDeletedFiles(uuids);
2002    }
2003
2004    private void markUuidsAsDeletedFiles(List<String> uuids) {
2005        boolean deleted = false;
2006        for (Conversation conversation : getConversations()) {
2007            deleted |= conversation.markAsDeleted(uuids);
2008        }
2009        for (final String uuid : uuids) {
2010            evictPreview(uuid);
2011        }
2012        if (deleted) {
2013            updateConversationUi();
2014        }
2015    }
2016
2017    private void markChangedFiles(List<DatabaseBackend.FilePathInfo> infos) {
2018        boolean changed = false;
2019        for (Conversation conversation : getConversations()) {
2020            changed |= conversation.markAsChanged(infos);
2021        }
2022        if (changed) {
2023            updateConversationUi();
2024        }
2025    }
2026
2027    public void populateWithOrderedConversations(final List<Conversation> list) {
2028        populateWithOrderedConversations(list, true, true);
2029    }
2030
2031    public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload) {
2032        populateWithOrderedConversations(list, includeNoFileUpload, true);
2033    }
2034
2035    public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload, final boolean sort) {
2036        final List<String> orderedUuids;
2037        if (sort) {
2038            orderedUuids = null;
2039        } else {
2040            orderedUuids = new ArrayList<>();
2041            for (Conversation conversation : list) {
2042                orderedUuids.add(conversation.getUuid());
2043            }
2044        }
2045        list.clear();
2046        if (includeNoFileUpload) {
2047            list.addAll(getConversations());
2048        } else {
2049            for (Conversation conversation : getConversations()) {
2050                if (conversation.getMode() == Conversation.MODE_SINGLE
2051                        || (conversation.getAccount().httpUploadAvailable() && conversation.getMucOptions().participating())) {
2052                    list.add(conversation);
2053                }
2054            }
2055        }
2056        try {
2057            if (orderedUuids != null) {
2058                Collections.sort(list, (a, b) -> {
2059                    final int indexA = orderedUuids.indexOf(a.getUuid());
2060                    final int indexB = orderedUuids.indexOf(b.getUuid());
2061                    if (indexA == -1 || indexB == -1 || indexA == indexB) {
2062                        return a.compareTo(b);
2063                    }
2064                    return indexA - indexB;
2065                });
2066            } else {
2067                Collections.sort(list);
2068            }
2069        } catch (IllegalArgumentException e) {
2070            //ignore
2071        }
2072    }
2073
2074    public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
2075        if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
2076            return;
2077        } else if (timestamp == 0) {
2078            return;
2079        }
2080        Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
2081        final Runnable runnable = () -> {
2082            final Account account = conversation.getAccount();
2083            List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
2084            if (messages.size() > 0) {
2085                conversation.addAll(0, messages);
2086                callback.onMoreMessagesLoaded(messages.size(), conversation);
2087            } else if (conversation.hasMessagesLeftOnServer()
2088                    && account.isOnlineAndConnected()
2089                    && conversation.getLastClearHistory().getTimestamp() == 0) {
2090                final boolean mamAvailable;
2091                if (conversation.getMode() == Conversation.MODE_SINGLE) {
2092                    mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
2093                } else {
2094                    mamAvailable = conversation.getMucOptions().mamSupport();
2095                }
2096                if (mamAvailable) {
2097                    MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
2098                    if (query != null) {
2099                        query.setCallback(callback);
2100                        callback.informUser(R.string.fetching_history_from_server);
2101                    } else {
2102                        callback.informUser(R.string.not_fetching_history_retention_period);
2103                    }
2104
2105                }
2106            }
2107        };
2108        mDatabaseReaderExecutor.execute(runnable);
2109    }
2110
2111    public List<Account> getAccounts() {
2112        return this.accounts;
2113    }
2114
2115
2116    /**
2117     * 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)
2118     */
2119    public List<Conversation> findAllConferencesWith(Contact contact) {
2120        final ArrayList<Conversation> results = new ArrayList<>();
2121        for (final Conversation c : conversations) {
2122            if (c.getMode() != Conversation.MODE_MULTI) {
2123                continue;
2124            }
2125            final MucOptions mucOptions = c.getMucOptions();
2126            if (c.getJid().asBareJid().equals(contact.getJid().asBareJid()) || (mucOptions != null && mucOptions.isContactInRoom(contact))) {
2127                results.add(c);
2128            }
2129        }
2130        return results;
2131    }
2132
2133    public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
2134        for (final Conversation conversation : haystack) {
2135            if (conversation.getContact() == contact) {
2136                return conversation;
2137            }
2138        }
2139        return null;
2140    }
2141
2142    public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
2143        if (jid == null) {
2144            return null;
2145        }
2146        for (final Conversation conversation : haystack) {
2147            if ((account == null || conversation.getAccount() == account)
2148                    && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
2149                return conversation;
2150            }
2151        }
2152        return null;
2153    }
2154
2155    public boolean isConversationsListEmpty(final Conversation ignore) {
2156        synchronized (this.conversations) {
2157            final int size = this.conversations.size();
2158            return size == 0 || size == 1 && this.conversations.get(0) == ignore;
2159        }
2160    }
2161
2162    public boolean isConversationStillOpen(final Conversation conversation) {
2163        synchronized (this.conversations) {
2164            for (Conversation current : this.conversations) {
2165                if (current == conversation) {
2166                    return true;
2167                }
2168            }
2169        }
2170        return false;
2171    }
2172
2173    public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
2174        return this.findOrCreateConversation(account, jid, muc, false, async);
2175    }
2176
2177    public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
2178        return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
2179    }
2180
2181    public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
2182        synchronized (this.conversations) {
2183            Conversation conversation = find(account, jid);
2184            if (conversation != null) {
2185                return conversation;
2186            }
2187            conversation = databaseBackend.findConversation(account, jid);
2188            final boolean loadMessagesFromDb;
2189            if (conversation != null) {
2190                conversation.setStatus(Conversation.STATUS_AVAILABLE);
2191                conversation.setAccount(account);
2192                if (muc) {
2193                    conversation.setMode(Conversation.MODE_MULTI);
2194                    conversation.setContactJid(jid);
2195                } else {
2196                    conversation.setMode(Conversation.MODE_SINGLE);
2197                    conversation.setContactJid(jid.asBareJid());
2198                }
2199                databaseBackend.updateConversation(conversation);
2200                loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
2201            } else {
2202                String conversationName;
2203                Contact contact = account.getRoster().getContact(jid);
2204                if (contact != null) {
2205                    conversationName = contact.getDisplayName();
2206                } else {
2207                    conversationName = jid.getLocal();
2208                }
2209                if (muc) {
2210                    conversation = new Conversation(conversationName, account, jid,
2211                            Conversation.MODE_MULTI);
2212                } else {
2213                    conversation = new Conversation(conversationName, account, jid.asBareJid(),
2214                            Conversation.MODE_SINGLE);
2215                }
2216                this.databaseBackend.createConversation(conversation);
2217                loadMessagesFromDb = false;
2218            }
2219            final Conversation c = conversation;
2220            final Runnable runnable = () -> {
2221                if (loadMessagesFromDb) {
2222                    c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
2223                    updateConversationUi();
2224                    c.messagesLoaded.set(true);
2225                }
2226                if (account.getXmppConnection() != null
2227                        && !c.getContact().isBlocked()
2228                        && account.getXmppConnection().getFeatures().mam()
2229                        && !muc) {
2230                    if (query == null) {
2231                        mMessageArchiveService.query(c);
2232                    } else {
2233                        if (query.getConversation() == null) {
2234                            mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
2235                        }
2236                    }
2237                }
2238                if (joinAfterCreate) {
2239                    joinMuc(c);
2240                }
2241            };
2242            if (async) {
2243                mDatabaseReaderExecutor.execute(runnable);
2244            } else {
2245                runnable.run();
2246            }
2247            this.conversations.add(conversation);
2248            updateConversationUi();
2249            return conversation;
2250        }
2251    }
2252
2253    public void archiveConversation(Conversation conversation) {
2254        archiveConversation(conversation, true);
2255    }
2256
2257    private void archiveConversation(Conversation conversation, final boolean maySynchronizeWithBookmarks) {
2258        getNotificationService().clear(conversation);
2259        conversation.setStatus(Conversation.STATUS_ARCHIVED);
2260        conversation.setNextMessage(null);
2261        synchronized (this.conversations) {
2262            getMessageArchiveService().kill(conversation);
2263            if (conversation.getMode() == Conversation.MODE_MULTI) {
2264                if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2265                    final Bookmark bookmark = conversation.getBookmark();
2266                    if (maySynchronizeWithBookmarks && bookmark != null && synchronizeWithBookmarks()) {
2267                        if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2268                            Account account = bookmark.getAccount();
2269                            bookmark.setConversation(null);
2270                            deleteBookmark(account, bookmark);
2271                        } else if (bookmark.autojoin()) {
2272                            bookmark.setAutojoin(false);
2273                            createBookmark(bookmark.getAccount(), bookmark);
2274                        }
2275                    }
2276                }
2277                leaveMuc(conversation);
2278            } else {
2279                if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2280                    stopPresenceUpdatesTo(conversation.getContact());
2281                }
2282            }
2283            updateConversation(conversation);
2284            this.conversations.remove(conversation);
2285            updateConversationUi();
2286        }
2287    }
2288
2289    public void stopPresenceUpdatesTo(Contact contact) {
2290        Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
2291        sendPresencePacket(contact.getAccount(), mPresenceGenerator.stopPresenceUpdatesTo(contact));
2292        contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2293    }
2294
2295    public void createAccount(final Account account) {
2296        account.initAccountServices(this);
2297        databaseBackend.createAccount(account);
2298        this.accounts.add(account);
2299        this.reconnectAccountInBackground(account);
2300        updateAccountUi();
2301        syncEnabledAccountSetting();
2302        toggleForegroundService();
2303    }
2304
2305    private void syncEnabledAccountSetting() {
2306        final boolean hasEnabledAccounts = hasEnabledAccounts();
2307        getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
2308        toggleSetProfilePictureActivity(hasEnabledAccounts);
2309    }
2310
2311    private void toggleSetProfilePictureActivity(final boolean enabled) {
2312        try {
2313            final ComponentName name = new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
2314            final int targetState = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
2315            getPackageManager().setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
2316        } catch (IllegalStateException e) {
2317            Log.d(Config.LOGTAG, "unable to toggle profile picture actvitiy");
2318        }
2319    }
2320
2321    private void provisionAccount(final String address, final String password) {
2322        final Jid jid = Jid.ofEscaped(address);
2323        final Account account = new Account(jid, password);
2324        account.setOption(Account.OPTION_DISABLED, true);
2325        Log.d(Config.LOGTAG, jid.asBareJid().toEscapedString() + ": provisioning account");
2326        createAccount(account);
2327    }
2328
2329    public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
2330        new Thread(() -> {
2331            try {
2332                final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
2333                final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
2334                if (cert == null) {
2335                    callback.informUser(R.string.unable_to_parse_certificate);
2336                    return;
2337                }
2338                Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
2339                if (info == null) {
2340                    callback.informUser(R.string.certificate_does_not_contain_jid);
2341                    return;
2342                }
2343                if (findAccountByJid(info.first) == null) {
2344                    final Account account = new Account(info.first, "");
2345                    account.setPrivateKeyAlias(alias);
2346                    account.setOption(Account.OPTION_DISABLED, true);
2347                    account.setOption(Account.OPTION_FIXED_USERNAME, true);
2348                    account.setDisplayName(info.second);
2349                    createAccount(account);
2350                    callback.onAccountCreated(account);
2351                    if (Config.X509_VERIFICATION) {
2352                        try {
2353                            getMemorizingTrustManager().getNonInteractive(account.getServer()).checkClientTrusted(chain, "RSA");
2354                        } catch (CertificateException e) {
2355                            callback.informUser(R.string.certificate_chain_is_not_trusted);
2356                        }
2357                    }
2358                } else {
2359                    callback.informUser(R.string.account_already_exists);
2360                }
2361            } catch (Exception e) {
2362                callback.informUser(R.string.unable_to_parse_certificate);
2363            }
2364        }).start();
2365
2366    }
2367
2368    public void updateKeyInAccount(final Account account, final String alias) {
2369        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
2370        try {
2371            X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
2372            Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
2373            Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
2374            if (info == null) {
2375                showErrorToastInUi(R.string.certificate_does_not_contain_jid);
2376                return;
2377            }
2378            if (account.getJid().asBareJid().equals(info.first)) {
2379                account.setPrivateKeyAlias(alias);
2380                account.setDisplayName(info.second);
2381                databaseBackend.updateAccount(account);
2382                if (Config.X509_VERIFICATION) {
2383                    try {
2384                        getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
2385                    } catch (CertificateException e) {
2386                        showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
2387                    }
2388                    account.getAxolotlService().regenerateKeys(true);
2389                }
2390            } else {
2391                showErrorToastInUi(R.string.jid_does_not_match_certificate);
2392            }
2393        } catch (Exception e) {
2394            e.printStackTrace();
2395        }
2396    }
2397
2398    public boolean updateAccount(final Account account) {
2399        if (databaseBackend.updateAccount(account)) {
2400            account.setShowErrorNotification(true);
2401            this.statusListener.onStatusChanged(account);
2402            databaseBackend.updateAccount(account);
2403            reconnectAccountInBackground(account);
2404            updateAccountUi();
2405            getNotificationService().updateErrorNotification();
2406            toggleForegroundService();
2407            syncEnabledAccountSetting();
2408            mChannelDiscoveryService.cleanCache();
2409            return true;
2410        } else {
2411            return false;
2412        }
2413    }
2414
2415    public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
2416        final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
2417        sendIqPacket(account, iq, (a, packet) -> {
2418            if (packet.getType() == IqPacket.TYPE.RESULT) {
2419                a.setPassword(newPassword);
2420                a.setOption(Account.OPTION_MAGIC_CREATE, false);
2421                databaseBackend.updateAccount(a);
2422                callback.onPasswordChangeSucceeded();
2423            } else {
2424                callback.onPasswordChangeFailed();
2425            }
2426        });
2427    }
2428
2429    public void deleteAccount(final Account account) {
2430        final boolean connected = account.getStatus() == Account.State.ONLINE;
2431        synchronized (this.conversations) {
2432            if (connected) {
2433                account.getAxolotlService().deleteOmemoIdentity();
2434            }
2435            for (final Conversation conversation : conversations) {
2436                if (conversation.getAccount() == account) {
2437                    if (conversation.getMode() == Conversation.MODE_MULTI) {
2438                        if (connected) {
2439                            leaveMuc(conversation);
2440                        }
2441                    }
2442                    conversations.remove(conversation);
2443                    mNotificationService.clear(conversation);
2444                }
2445            }
2446            if (account.getXmppConnection() != null) {
2447                new Thread(() -> disconnect(account, !connected)).start();
2448            }
2449            final Runnable runnable = () -> {
2450                if (!databaseBackend.deleteAccount(account)) {
2451                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
2452                }
2453            };
2454            mDatabaseWriterExecutor.execute(runnable);
2455            this.accounts.remove(account);
2456            this.mRosterSyncTaskManager.clear(account);
2457            updateAccountUi();
2458            mNotificationService.updateErrorNotification();
2459            syncEnabledAccountSetting();
2460            toggleForegroundService();
2461        }
2462    }
2463
2464    public void setOnConversationListChangedListener(OnConversationUpdate listener) {
2465        final boolean remainingListeners;
2466        synchronized (LISTENER_LOCK) {
2467            remainingListeners = checkListeners();
2468            if (!this.mOnConversationUpdates.add(listener)) {
2469                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as ConversationListChangedListener");
2470            }
2471            this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2472        }
2473        if (remainingListeners) {
2474            switchToForeground();
2475        }
2476    }
2477
2478    public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
2479        final boolean remainingListeners;
2480        synchronized (LISTENER_LOCK) {
2481            this.mOnConversationUpdates.remove(listener);
2482            this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2483            remainingListeners = checkListeners();
2484        }
2485        if (remainingListeners) {
2486            switchToBackground();
2487        }
2488    }
2489
2490    public void setOnShowErrorToastListener(OnShowErrorToast listener) {
2491        final boolean remainingListeners;
2492        synchronized (LISTENER_LOCK) {
2493            remainingListeners = checkListeners();
2494            if (!this.mOnShowErrorToasts.add(listener)) {
2495                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnShowErrorToastListener");
2496            }
2497        }
2498        if (remainingListeners) {
2499            switchToForeground();
2500        }
2501    }
2502
2503    public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
2504        final boolean remainingListeners;
2505        synchronized (LISTENER_LOCK) {
2506            this.mOnShowErrorToasts.remove(onShowErrorToast);
2507            remainingListeners = checkListeners();
2508        }
2509        if (remainingListeners) {
2510            switchToBackground();
2511        }
2512    }
2513
2514    public void setOnAccountListChangedListener(OnAccountUpdate listener) {
2515        final boolean remainingListeners;
2516        synchronized (LISTENER_LOCK) {
2517            remainingListeners = checkListeners();
2518            if (!this.mOnAccountUpdates.add(listener)) {
2519                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnAccountListChangedtListener");
2520            }
2521        }
2522        if (remainingListeners) {
2523            switchToForeground();
2524        }
2525    }
2526
2527    public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
2528        final boolean remainingListeners;
2529        synchronized (LISTENER_LOCK) {
2530            this.mOnAccountUpdates.remove(listener);
2531            remainingListeners = checkListeners();
2532        }
2533        if (remainingListeners) {
2534            switchToBackground();
2535        }
2536    }
2537
2538    public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2539        final boolean remainingListeners;
2540        synchronized (LISTENER_LOCK) {
2541            remainingListeners = checkListeners();
2542            if (!this.mOnCaptchaRequested.add(listener)) {
2543                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnCaptchaRequestListener");
2544            }
2545        }
2546        if (remainingListeners) {
2547            switchToForeground();
2548        }
2549    }
2550
2551    public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2552        final boolean remainingListeners;
2553        synchronized (LISTENER_LOCK) {
2554            this.mOnCaptchaRequested.remove(listener);
2555            remainingListeners = checkListeners();
2556        }
2557        if (remainingListeners) {
2558            switchToBackground();
2559        }
2560    }
2561
2562    public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
2563        final boolean remainingListeners;
2564        synchronized (LISTENER_LOCK) {
2565            remainingListeners = checkListeners();
2566            if (!this.mOnRosterUpdates.add(listener)) {
2567                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnRosterUpdateListener");
2568            }
2569        }
2570        if (remainingListeners) {
2571            switchToForeground();
2572        }
2573    }
2574
2575    public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
2576        final boolean remainingListeners;
2577        synchronized (LISTENER_LOCK) {
2578            this.mOnRosterUpdates.remove(listener);
2579            remainingListeners = checkListeners();
2580        }
2581        if (remainingListeners) {
2582            switchToBackground();
2583        }
2584    }
2585
2586    public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2587        final boolean remainingListeners;
2588        synchronized (LISTENER_LOCK) {
2589            remainingListeners = checkListeners();
2590            if (!this.mOnUpdateBlocklist.add(listener)) {
2591                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnUpdateBlocklistListener");
2592            }
2593        }
2594        if (remainingListeners) {
2595            switchToForeground();
2596        }
2597    }
2598
2599    public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2600        final boolean remainingListeners;
2601        synchronized (LISTENER_LOCK) {
2602            this.mOnUpdateBlocklist.remove(listener);
2603            remainingListeners = checkListeners();
2604        }
2605        if (remainingListeners) {
2606            switchToBackground();
2607        }
2608    }
2609
2610    public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2611        final boolean remainingListeners;
2612        synchronized (LISTENER_LOCK) {
2613            remainingListeners = checkListeners();
2614            if (!this.mOnKeyStatusUpdated.add(listener)) {
2615                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnKeyStatusUpdateListener");
2616            }
2617        }
2618        if (remainingListeners) {
2619            switchToForeground();
2620        }
2621    }
2622
2623    public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
2624        final boolean remainingListeners;
2625        synchronized (LISTENER_LOCK) {
2626            this.mOnKeyStatusUpdated.remove(listener);
2627            remainingListeners = checkListeners();
2628        }
2629        if (remainingListeners) {
2630            switchToBackground();
2631        }
2632    }
2633
2634    public void setOnRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
2635        final boolean remainingListeners;
2636        synchronized (LISTENER_LOCK) {
2637            remainingListeners = checkListeners();
2638            if (!this.onJingleRtpConnectionUpdate.add(listener)) {
2639                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnJingleRtpConnectionUpdate");
2640            }
2641        }
2642        if (remainingListeners) {
2643            switchToForeground();
2644        }
2645    }
2646
2647    public void removeRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
2648        final boolean remainingListeners;
2649        synchronized (LISTENER_LOCK) {
2650            this.onJingleRtpConnectionUpdate.remove(listener);
2651            remainingListeners = checkListeners();
2652        }
2653        if (remainingListeners) {
2654            switchToBackground();
2655        }
2656    }
2657
2658    public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2659        final boolean remainingListeners;
2660        synchronized (LISTENER_LOCK) {
2661            remainingListeners = checkListeners();
2662            if (!this.mOnMucRosterUpdate.add(listener)) {
2663                Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnMucRosterListener");
2664            }
2665        }
2666        if (remainingListeners) {
2667            switchToForeground();
2668        }
2669    }
2670
2671    public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
2672        final boolean remainingListeners;
2673        synchronized (LISTENER_LOCK) {
2674            this.mOnMucRosterUpdate.remove(listener);
2675            remainingListeners = checkListeners();
2676        }
2677        if (remainingListeners) {
2678            switchToBackground();
2679        }
2680    }
2681
2682    public boolean checkListeners() {
2683        return (this.mOnAccountUpdates.size() == 0
2684                && this.mOnConversationUpdates.size() == 0
2685                && this.mOnRosterUpdates.size() == 0
2686                && this.mOnCaptchaRequested.size() == 0
2687                && this.mOnMucRosterUpdate.size() == 0
2688                && this.mOnUpdateBlocklist.size() == 0
2689                && this.mOnShowErrorToasts.size() == 0
2690                && this.onJingleRtpConnectionUpdate.size() == 0
2691                && this.mOnKeyStatusUpdated.size() == 0);
2692    }
2693
2694    private void switchToForeground() {
2695        final boolean broadcastLastActivity = broadcastLastActivity();
2696        for (Conversation conversation : getConversations()) {
2697            if (conversation.getMode() == Conversation.MODE_MULTI) {
2698                conversation.getMucOptions().resetChatState();
2699            } else {
2700                conversation.setIncomingChatState(Config.DEFAULT_CHAT_STATE);
2701            }
2702        }
2703        for (Account account : getAccounts()) {
2704            if (account.getStatus() == Account.State.ONLINE) {
2705                account.deactivateGracePeriod();
2706                final XmppConnection connection = account.getXmppConnection();
2707                if (connection != null) {
2708                    if (connection.getFeatures().csi()) {
2709                        connection.sendActive();
2710                    }
2711                    if (broadcastLastActivity) {
2712                        sendPresence(account, false); //send new presence but don't include idle because we are not
2713                    }
2714                }
2715            }
2716        }
2717        Log.d(Config.LOGTAG, "app switched into foreground");
2718    }
2719
2720    private void switchToBackground() {
2721        final boolean broadcastLastActivity = broadcastLastActivity();
2722        if (broadcastLastActivity) {
2723            mLastActivity = System.currentTimeMillis();
2724            final SharedPreferences.Editor editor = getPreferences().edit();
2725            editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
2726            editor.apply();
2727        }
2728        for (Account account : getAccounts()) {
2729            if (account.getStatus() == Account.State.ONLINE) {
2730                XmppConnection connection = account.getXmppConnection();
2731                if (connection != null) {
2732                    if (broadcastLastActivity) {
2733                        sendPresence(account, true);
2734                    }
2735                    if (connection.getFeatures().csi()) {
2736                        connection.sendInactive();
2737                    }
2738                }
2739            }
2740        }
2741        this.mNotificationService.setIsInForeground(false);
2742        Log.d(Config.LOGTAG, "app switched into background");
2743    }
2744
2745    private void connectMultiModeConversations(Account account) {
2746        List<Conversation> conversations = getConversations();
2747        for (Conversation conversation : conversations) {
2748            if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2749                joinMuc(conversation);
2750            }
2751        }
2752    }
2753
2754    public void mucSelfPingAndRejoin(final Conversation conversation) {
2755        final Account account = conversation.getAccount();
2756        synchronized (account.inProgressConferenceJoins) {
2757            if (account.inProgressConferenceJoins.contains(conversation)) {
2758                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because join is already under way");
2759                return;
2760            }
2761        }
2762        synchronized (account.inProgressConferencePings) {
2763            if (!account.inProgressConferencePings.add(conversation)) {
2764                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because ping is already under way");
2765                return;
2766            }
2767        }
2768        final Jid self = conversation.getMucOptions().getSelf().getFullJid();
2769        final IqPacket ping = new IqPacket(IqPacket.TYPE.GET);
2770        ping.setTo(self);
2771        ping.addChild("ping", Namespace.PING);
2772        sendIqPacket(conversation.getAccount(), ping, (a, response) -> {
2773            if (response.getType() == IqPacket.TYPE.ERROR) {
2774                Element error = response.findChild("error");
2775                if (error == null || error.hasChild("service-unavailable") || error.hasChild("feature-not-implemented") || error.hasChild("item-not-found")) {
2776                    Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back as ignorable error");
2777                } else {
2778                    Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " failed. attempting rejoin");
2779                    joinMuc(conversation);
2780                }
2781            } else if (response.getType() == IqPacket.TYPE.RESULT) {
2782                Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back fine");
2783            }
2784            synchronized (account.inProgressConferencePings) {
2785                account.inProgressConferencePings.remove(conversation);
2786            }
2787        });
2788    }
2789
2790    public void joinMuc(Conversation conversation) {
2791        joinMuc(conversation, null, false);
2792    }
2793
2794    public void joinMuc(Conversation conversation, boolean followedInvite) {
2795        joinMuc(conversation, null, followedInvite);
2796    }
2797
2798    private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2799        joinMuc(conversation, onConferenceJoined, false);
2800    }
2801
2802    private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2803        final Account account = conversation.getAccount();
2804        synchronized (account.pendingConferenceJoins) {
2805            account.pendingConferenceJoins.remove(conversation);
2806        }
2807        synchronized (account.pendingConferenceLeaves) {
2808            account.pendingConferenceLeaves.remove(conversation);
2809        }
2810        if (account.getStatus() == Account.State.ONLINE) {
2811            synchronized (account.inProgressConferenceJoins) {
2812                account.inProgressConferenceJoins.add(conversation);
2813            }
2814            if (Config.MUC_LEAVE_BEFORE_JOIN) {
2815                sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
2816            }
2817            conversation.resetMucOptions();
2818            if (onConferenceJoined != null) {
2819                conversation.getMucOptions().flagNoAutoPushConfiguration();
2820            }
2821            conversation.setHasMessagesLeftOnServer(false);
2822            fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2823
2824                private void join(Conversation conversation) {
2825                    Account account = conversation.getAccount();
2826                    final MucOptions mucOptions = conversation.getMucOptions();
2827
2828                    if (mucOptions.nonanonymous() && !mucOptions.membersOnly() && !conversation.getBooleanAttribute("accept_non_anonymous", false)) {
2829                        synchronized (account.inProgressConferenceJoins) {
2830                            account.inProgressConferenceJoins.remove(conversation);
2831                        }
2832                        mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
2833                        updateConversationUi();
2834                        if (onConferenceJoined != null) {
2835                            onConferenceJoined.onConferenceJoined(conversation);
2836                        }
2837                        return;
2838                    }
2839
2840                    final Jid joinJid = mucOptions.getSelf().getFullJid();
2841                    Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
2842                    PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
2843                    packet.setTo(joinJid);
2844                    Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2845                    if (conversation.getMucOptions().getPassword() != null) {
2846                        x.addChild("password").setContent(mucOptions.getPassword());
2847                    }
2848
2849                    if (mucOptions.mamSupport()) {
2850                        // Use MAM instead of the limited muc history to get history
2851                        x.addChild("history").setAttribute("maxchars", "0");
2852                    } else {
2853                        // Fallback to muc history
2854                        x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
2855                    }
2856                    sendPresencePacket(account, packet);
2857                    if (onConferenceJoined != null) {
2858                        onConferenceJoined.onConferenceJoined(conversation);
2859                    }
2860                    if (!joinJid.equals(conversation.getJid())) {
2861                        conversation.setContactJid(joinJid);
2862                        databaseBackend.updateConversation(conversation);
2863                    }
2864
2865                    if (mucOptions.mamSupport()) {
2866                        getMessageArchiveService().catchupMUC(conversation);
2867                    }
2868                    if (mucOptions.isPrivateAndNonAnonymous()) {
2869                        fetchConferenceMembers(conversation);
2870
2871                        if (followedInvite) {
2872                            final Bookmark bookmark = conversation.getBookmark();
2873                            if (bookmark != null) {
2874                                if (!bookmark.autojoin()) {
2875                                    bookmark.setAutojoin(true);
2876                                    createBookmark(account, bookmark);
2877                                }
2878                            } else {
2879                                saveConversationAsBookmark(conversation, null);
2880                            }
2881                        }
2882                    }
2883                    synchronized (account.inProgressConferenceJoins) {
2884                        account.inProgressConferenceJoins.remove(conversation);
2885                        sendUnsentMessages(conversation);
2886                    }
2887                }
2888
2889                @Override
2890                public void onConferenceConfigurationFetched(Conversation conversation) {
2891                    if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2892                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
2893                        return;
2894                    }
2895                    join(conversation);
2896                }
2897
2898                @Override
2899                public void onFetchFailed(final Conversation conversation, final String errorCondition) {
2900                    if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2901                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
2902                        return;
2903                    }
2904                    if ("remote-server-not-found".equals(errorCondition)) {
2905                        synchronized (account.inProgressConferenceJoins) {
2906                            account.inProgressConferenceJoins.remove(conversation);
2907                        }
2908                        conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2909                        updateConversationUi();
2910                    } else {
2911                        join(conversation);
2912                        fetchConferenceConfiguration(conversation);
2913                    }
2914                }
2915            });
2916            updateConversationUi();
2917        } else {
2918            synchronized (account.pendingConferenceJoins) {
2919                account.pendingConferenceJoins.add(conversation);
2920            }
2921            conversation.resetMucOptions();
2922            conversation.setHasMessagesLeftOnServer(false);
2923            updateConversationUi();
2924        }
2925    }
2926
2927    private void fetchConferenceMembers(final Conversation conversation) {
2928        final Account account = conversation.getAccount();
2929        final AxolotlService axolotlService = account.getAxolotlService();
2930        final String[] affiliations = {"member", "admin", "owner"};
2931        OnIqPacketReceived callback = new OnIqPacketReceived() {
2932
2933            private int i = 0;
2934            private boolean success = true;
2935
2936            @Override
2937            public void onIqPacketReceived(Account account, IqPacket packet) {
2938                final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
2939                Element query = packet.query("http://jabber.org/protocol/muc#admin");
2940                if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2941                    for (Element child : query.getChildren()) {
2942                        if ("item".equals(child.getName())) {
2943                            MucOptions.User user = AbstractParser.parseItem(conversation, child);
2944                            if (!user.realJidMatchesAccount()) {
2945                                boolean isNew = conversation.getMucOptions().updateUser(user);
2946                                Contact contact = user.getContact();
2947                                if (omemoEnabled
2948                                        && isNew
2949                                        && user.getRealJid() != null
2950                                        && (contact == null || !contact.mutualPresenceSubscription())
2951                                        && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
2952                                    axolotlService.fetchDeviceIds(user.getRealJid());
2953                                }
2954                            }
2955                        }
2956                    }
2957                } else {
2958                    success = false;
2959                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
2960                }
2961                ++i;
2962                if (i >= affiliations.length) {
2963                    List<Jid> members = conversation.getMucOptions().getMembers(true);
2964                    if (success) {
2965                        List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
2966                        boolean changed = false;
2967                        for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
2968                            Jid jid = iterator.next();
2969                            if (!members.contains(jid) && !members.contains(jid.getDomain())) {
2970                                iterator.remove();
2971                                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
2972                                changed = true;
2973                            }
2974                        }
2975                        if (changed) {
2976                            conversation.setAcceptedCryptoTargets(cryptoTargets);
2977                            updateConversation(conversation);
2978                        }
2979                    }
2980                    getAvatarService().clear(conversation);
2981                    updateMucRosterUi();
2982                    updateConversationUi();
2983                }
2984            }
2985        };
2986        for (String affiliation : affiliations) {
2987            sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2988        }
2989        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
2990    }
2991
2992    public void providePasswordForMuc(Conversation conversation, String password) {
2993        if (conversation.getMode() == Conversation.MODE_MULTI) {
2994            conversation.getMucOptions().setPassword(password);
2995            if (conversation.getBookmark() != null) {
2996                final Bookmark bookmark = conversation.getBookmark();
2997                if (synchronizeWithBookmarks()) {
2998                    bookmark.setAutojoin(true);
2999                }
3000                createBookmark(conversation.getAccount(), bookmark);
3001            }
3002            updateConversation(conversation);
3003            joinMuc(conversation);
3004        }
3005    }
3006
3007    private boolean hasEnabledAccounts() {
3008        if (this.accounts == null) {
3009            return false;
3010        }
3011        for (Account account : this.accounts) {
3012            if (account.isEnabled()) {
3013                return true;
3014            }
3015        }
3016        return false;
3017    }
3018
3019
3020    public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
3021        getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
3022    }
3023
3024    public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3025        getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
3026    }
3027
3028
3029    public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3030        new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
3031    }
3032
3033    public void persistSelfNick(MucOptions.User self) {
3034        final Conversation conversation = self.getConversation();
3035        final boolean tookProposedNickFromBookmark = conversation.getMucOptions().isTookProposedNickFromBookmark();
3036        Jid full = self.getFullJid();
3037        if (!full.equals(conversation.getJid())) {
3038            Log.d(Config.LOGTAG, "nick changed. updating");
3039            conversation.setContactJid(full);
3040            databaseBackend.updateConversation(conversation);
3041        }
3042
3043        final Bookmark bookmark = conversation.getBookmark();
3044        final String bookmarkedNick = bookmark == null ? null : bookmark.getNick();
3045        if (bookmark != null && (tookProposedNickFromBookmark || TextUtils.isEmpty(bookmarkedNick)) && !full.getResource().equals(bookmarkedNick)) {
3046            final Account account = conversation.getAccount();
3047            final String defaultNick = MucOptions.defaultNick(account);
3048            if (TextUtils.isEmpty(bookmarkedNick) && full.getResource().equals(defaultNick)) {
3049                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not overwrite empty bookmark nick with default nick for " + conversation.getJid().asBareJid());
3050                return;
3051            }
3052            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persist nick '" + full.getResource() + "' into bookmark for " + conversation.getJid().asBareJid());
3053            bookmark.setNick(full.getResource());
3054            createBookmark(bookmark.getAccount(), bookmark);
3055        }
3056    }
3057
3058    public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
3059        final MucOptions options = conversation.getMucOptions();
3060        final Jid joinJid = options.createJoinJid(nick);
3061        if (joinJid == null) {
3062            return false;
3063        }
3064        if (options.online()) {
3065            Account account = conversation.getAccount();
3066            options.setOnRenameListener(new OnRenameListener() {
3067
3068                @Override
3069                public void onSuccess() {
3070                    callback.success(conversation);
3071                }
3072
3073                @Override
3074                public void onFailure() {
3075                    callback.error(R.string.nick_in_use, conversation);
3076                }
3077            });
3078
3079            final PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous());
3080            packet.setTo(joinJid);
3081            sendPresencePacket(account, packet);
3082        } else {
3083            conversation.setContactJid(joinJid);
3084            databaseBackend.updateConversation(conversation);
3085            if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
3086                Bookmark bookmark = conversation.getBookmark();
3087                if (bookmark != null) {
3088                    bookmark.setNick(nick);
3089                    createBookmark(bookmark.getAccount(), bookmark);
3090                }
3091                joinMuc(conversation);
3092            }
3093        }
3094        return true;
3095    }
3096
3097    public void leaveMuc(Conversation conversation) {
3098        leaveMuc(conversation, false);
3099    }
3100
3101    private void leaveMuc(Conversation conversation, boolean now) {
3102        final Account account = conversation.getAccount();
3103        synchronized (account.pendingConferenceJoins) {
3104            account.pendingConferenceJoins.remove(conversation);
3105        }
3106        synchronized (account.pendingConferenceLeaves) {
3107            account.pendingConferenceLeaves.remove(conversation);
3108        }
3109        if (account.getStatus() == Account.State.ONLINE || now) {
3110            sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
3111            conversation.getMucOptions().setOffline();
3112            Bookmark bookmark = conversation.getBookmark();
3113            if (bookmark != null) {
3114                bookmark.setConversation(null);
3115            }
3116            Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
3117        } else {
3118            synchronized (account.pendingConferenceLeaves) {
3119                account.pendingConferenceLeaves.add(conversation);
3120            }
3121        }
3122    }
3123
3124    public String findConferenceServer(final Account account) {
3125        String server;
3126        if (account.getXmppConnection() != null) {
3127            server = account.getXmppConnection().getMucServer();
3128            if (server != null) {
3129                return server;
3130            }
3131        }
3132        for (Account other : getAccounts()) {
3133            if (other != account && other.getXmppConnection() != null) {
3134                server = other.getXmppConnection().getMucServer();
3135                if (server != null) {
3136                    return server;
3137                }
3138            }
3139        }
3140        return null;
3141    }
3142
3143
3144    public void createPublicChannel(final Account account, final String name, final Jid address, final UiCallback<Conversation> callback) {
3145        joinMuc(findOrCreateConversation(account, address, true, false, true), conversation -> {
3146            final Bundle configuration = IqGenerator.defaultChannelConfiguration();
3147            if (!TextUtils.isEmpty(name)) {
3148                configuration.putString("muc#roomconfig_roomname", name);
3149            }
3150            pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3151                @Override
3152                public void onPushSucceeded() {
3153                    saveConversationAsBookmark(conversation, name);
3154                    callback.success(conversation);
3155                }
3156
3157                @Override
3158                public void onPushFailed() {
3159                    if (conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
3160                        callback.error(R.string.unable_to_set_channel_configuration, conversation);
3161                    } else {
3162                        callback.error(R.string.joined_an_existing_channel, conversation);
3163                    }
3164                }
3165            });
3166        });
3167    }
3168
3169    public boolean createAdhocConference(final Account account,
3170                                         final String name,
3171                                         final Iterable<Jid> jids,
3172                                         final UiCallback<Conversation> callback) {
3173        Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
3174        if (account.getStatus() == Account.State.ONLINE) {
3175            try {
3176                String server = findConferenceServer(account);
3177                if (server == null) {
3178                    if (callback != null) {
3179                        callback.error(R.string.no_conference_server_found, null);
3180                    }
3181                    return false;
3182                }
3183                final Jid jid = Jid.of(CryptoHelper.pronounceable(getRNG()), server, null);
3184                final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
3185                joinMuc(conversation, new OnConferenceJoined() {
3186                    @Override
3187                    public void onConferenceJoined(final Conversation conversation) {
3188                        final Bundle configuration = IqGenerator.defaultGroupChatConfiguration();
3189                        if (!TextUtils.isEmpty(name)) {
3190                            configuration.putString("muc#roomconfig_roomname", name);
3191                        }
3192                        pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3193                            @Override
3194                            public void onPushSucceeded() {
3195                                for (Jid invite : jids) {
3196                                    invite(conversation, invite);
3197                                }
3198                                for (String resource : account.getSelfContact().getPresences().toResourceArray()) {
3199                                    Jid other = account.getJid().withResource(resource);
3200                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending direct invite to " + other);
3201                                    directInvite(conversation, other);
3202                                }
3203                                saveConversationAsBookmark(conversation, name);
3204                                if (callback != null) {
3205                                    callback.success(conversation);
3206                                }
3207                            }
3208
3209                            @Override
3210                            public void onPushFailed() {
3211                                archiveConversation(conversation);
3212                                if (callback != null) {
3213                                    callback.error(R.string.conference_creation_failed, conversation);
3214                                }
3215                            }
3216                        });
3217                    }
3218                });
3219                return true;
3220            } catch (IllegalArgumentException e) {
3221                if (callback != null) {
3222                    callback.error(R.string.conference_creation_failed, null);
3223                }
3224                return false;
3225            }
3226        } else {
3227            if (callback != null) {
3228                callback.error(R.string.not_connected_try_again, null);
3229            }
3230            return false;
3231        }
3232    }
3233
3234    public void fetchConferenceConfiguration(final Conversation conversation) {
3235        fetchConferenceConfiguration(conversation, null);
3236    }
3237
3238    public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
3239        IqPacket request = mIqGenerator.queryDiscoInfo(conversation.getJid().asBareJid());
3240        sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3241            @Override
3242            public void onIqPacketReceived(Account account, IqPacket packet) {
3243                if (packet.getType() == IqPacket.TYPE.RESULT) {
3244                    final MucOptions mucOptions = conversation.getMucOptions();
3245                    final Bookmark bookmark = conversation.getBookmark();
3246                    final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
3247
3248                    if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
3249                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
3250                        updateConversation(conversation);
3251                    }
3252
3253                    if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
3254                        if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
3255                            createBookmark(account, bookmark);
3256                        }
3257                    }
3258
3259
3260                    if (callback != null) {
3261                        callback.onConferenceConfigurationFetched(conversation);
3262                    }
3263
3264
3265                    updateConversationUi();
3266                } else if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
3267                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received timeout waiting for conference configuration fetch");
3268                } else {
3269                    if (callback != null) {
3270                        callback.onFetchFailed(conversation, packet.getErrorCondition());
3271                    }
3272                }
3273            }
3274        });
3275    }
3276
3277    public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
3278        pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
3279    }
3280
3281    public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
3282        Log.d(Config.LOGTAG, "pushing node configuration");
3283        sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
3284            @Override
3285            public void onIqPacketReceived(Account account, IqPacket packet) {
3286                if (packet.getType() == IqPacket.TYPE.RESULT) {
3287                    Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
3288                    Element configuration = pubsub == null ? null : pubsub.findChild("configure");
3289                    Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
3290                    if (x != null) {
3291                        Data data = Data.parse(x);
3292                        data.submit(options);
3293                        sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
3294                            @Override
3295                            public void onIqPacketReceived(Account account, IqPacket packet) {
3296                                if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
3297                                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully changed node configuration for node " + node);
3298                                    callback.onPushSucceeded();
3299                                } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3300                                    callback.onPushFailed();
3301                                }
3302                            }
3303                        });
3304                    } else if (callback != null) {
3305                        callback.onPushFailed();
3306                    }
3307                } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3308                    callback.onPushFailed();
3309                }
3310            }
3311        });
3312    }
3313
3314    public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
3315        if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
3316            conversation.setAttribute("accept_non_anonymous", true);
3317            updateConversation(conversation);
3318        }
3319        if (options.containsKey("muc#roomconfig_moderatedroom")) {
3320            final boolean moderated = "1".equals(options.getString("muc#roomconfig_moderatedroom"));
3321            options.putString("members_by_default", moderated ? "0" : "1");
3322        }
3323        final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3324        request.setTo(conversation.getJid().asBareJid());
3325        request.query("http://jabber.org/protocol/muc#owner");
3326        sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3327            @Override
3328            public void onIqPacketReceived(Account account, IqPacket packet) {
3329                if (packet.getType() == IqPacket.TYPE.RESULT) {
3330                    final Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
3331                    data.submit(options);
3332                    final IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3333                    set.setTo(conversation.getJid().asBareJid());
3334                    set.query("http://jabber.org/protocol/muc#owner").addChild(data);
3335                    sendIqPacket(account, set, new OnIqPacketReceived() {
3336                        @Override
3337                        public void onIqPacketReceived(Account account, IqPacket packet) {
3338                            if (callback != null) {
3339                                if (packet.getType() == IqPacket.TYPE.RESULT) {
3340                                    callback.onPushSucceeded();
3341                                } else {
3342                                    callback.onPushFailed();
3343                                }
3344                            }
3345                        }
3346                    });
3347                } else {
3348                    if (callback != null) {
3349                        callback.onPushFailed();
3350                    }
3351                }
3352            }
3353        });
3354    }
3355
3356    public void pushSubjectToConference(final Conversation conference, final String subject) {
3357        MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
3358        this.sendMessagePacket(conference.getAccount(), packet);
3359    }
3360
3361    public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
3362        final Jid jid = user.asBareJid();
3363        final IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
3364        sendIqPacket(conference.getAccount(), request, (account, response) -> {
3365            if (response.getType() == IqPacket.TYPE.RESULT) {
3366                conference.getMucOptions().changeAffiliation(jid, affiliation);
3367                getAvatarService().clear(conference);
3368                if (callback != null) {
3369                    callback.onAffiliationChangedSuccessful(jid);
3370                } else {
3371                    Log.d(Config.LOGTAG, "changed affiliation of " + user + " to " + affiliation);
3372                }
3373            } else if (callback != null) {
3374                callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
3375            } else {
3376                Log.d(Config.LOGTAG, "unable to change affiliation");
3377            }
3378        });
3379    }
3380
3381    public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) {
3382        IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
3383        sendIqPacket(conference.getAccount(), request, (account, packet) -> {
3384            if (packet.getType() != IqPacket.TYPE.RESULT) {
3385                Log.d(Config.LOGTAG, account.getJid().asBareJid() + " unable to change role of " + nick);
3386            }
3387        });
3388    }
3389
3390    public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
3391        IqPacket request = new IqPacket(IqPacket.TYPE.SET);
3392        request.setTo(conversation.getJid().asBareJid());
3393        request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
3394        sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3395            @Override
3396            public void onIqPacketReceived(Account account, IqPacket packet) {
3397                if (packet.getType() == IqPacket.TYPE.RESULT) {
3398                    if (callback != null) {
3399                        callback.onRoomDestroySucceeded();
3400                    }
3401                } else if (packet.getType() == IqPacket.TYPE.ERROR) {
3402                    if (callback != null) {
3403                        callback.onRoomDestroyFailed();
3404                    }
3405                }
3406            }
3407        });
3408    }
3409
3410    private void disconnect(Account account, boolean force) {
3411        if ((account.getStatus() == Account.State.ONLINE)
3412                || (account.getStatus() == Account.State.DISABLED)) {
3413            final XmppConnection connection = account.getXmppConnection();
3414            if (!force) {
3415                List<Conversation> conversations = getConversations();
3416                for (Conversation conversation : conversations) {
3417                    if (conversation.getAccount() == account) {
3418                        if (conversation.getMode() == Conversation.MODE_MULTI) {
3419                            leaveMuc(conversation, true);
3420                        }
3421                    }
3422                }
3423                sendOfflinePresence(account);
3424            }
3425            connection.disconnect(force);
3426        }
3427    }
3428
3429    @Override
3430    public IBinder onBind(Intent intent) {
3431        return mBinder;
3432    }
3433
3434    public void updateMessage(Message message) {
3435        updateMessage(message, true);
3436    }
3437
3438    public void updateMessage(Message message, boolean includeBody) {
3439        databaseBackend.updateMessage(message, includeBody);
3440        updateConversationUi();
3441    }
3442
3443    public void createMessageAsync(final Message message) {
3444        mDatabaseWriterExecutor.execute(() -> databaseBackend.createMessage(message));
3445    }
3446
3447    public void updateMessage(Message message, String uuid) {
3448        if (!databaseBackend.updateMessage(message, uuid)) {
3449            Log.e(Config.LOGTAG, "error updated message in DB after edit");
3450        }
3451        updateConversationUi();
3452    }
3453
3454    protected void syncDirtyContacts(Account account) {
3455        for (Contact contact : account.getRoster().getContacts()) {
3456            if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
3457                pushContactToServer(contact);
3458            }
3459            if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
3460                deleteContactOnServer(contact);
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 (final 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}