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