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