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