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