XmppConnectionService.java

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