XmppConnectionService.java

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