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