XmppConnectionService.java

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