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