XmppConnectionService.java

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