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