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            JabberIdContact.load(this, contacts -> {
1524                Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1525                for (Account account : accounts) {
1526                    List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
1527                    for (JabberIdContact jidContact : contacts) {
1528                        final Contact contact = account.getRoster().getContact(jidContact.getJid());
1529                        contact.setSystemAccount(jidContact.getLookupUri());
1530                        boolean needsCacheClean = contact.setPhotoUri(jidContact.getPhotoUri());
1531                        needsCacheClean |= contact.setSystemName(jidContact.getDisplayName());
1532                        if (needsCacheClean) {
1533                            getAvatarService().clear(contact);
1534                        }
1535                        withSystemAccounts.remove(contact);
1536                    }
1537                    for (Contact contact : withSystemAccounts) {
1538                        contact.setSystemAccount(null);
1539                        boolean needsCacheClean = contact.setPhotoUri(null);
1540                        needsCacheClean |= contact.setSystemName(null);
1541                        if (needsCacheClean) {
1542                            getAvatarService().clear(contact);
1543                        }
1544                    }
1545                }
1546                Log.d(Config.LOGTAG, "finished merging phone contacts");
1547                mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
1548                updateRosterUi();
1549            });
1550            mQuickConversationsService.considerSync();
1551        });
1552	}
1553
1554
1555	public void syncRoster(final Account account) {
1556		mRosterSyncTaskManager.execute(account, () -> databaseBackend.writeRoster(account.getRoster()));
1557	}
1558
1559	public List<Conversation> getConversations() {
1560		return this.conversations;
1561	}
1562
1563	private void checkDeletedFiles(Conversation conversation) {
1564		conversation.findMessagesWithFiles(message -> {
1565			if (!getFileBackend().isFileAvailable(message)) {
1566				message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1567				final int s = message.getStatus();
1568				if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1569					markMessage(message, Message.STATUS_SEND_FAILED);
1570				}
1571			}
1572		});
1573	}
1574
1575	private void markFileDeleted(final String path) {
1576		Log.d(Config.LOGTAG, "deleted file " + path);
1577		for (Conversation conversation : getConversations()) {
1578			conversation.findMessagesWithFiles(message -> {
1579				DownloadableFile file = fileBackend.getFile(message);
1580				if (file.getAbsolutePath().equals(path)) {
1581					if (!file.exists()) {
1582						message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1583						final int s = message.getStatus();
1584						if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1585							markMessage(message, Message.STATUS_SEND_FAILED);
1586						} else {
1587							updateConversationUi();
1588						}
1589					} else {
1590						Log.d(Config.LOGTAG, "found matching message for file " + path + " but file still exists");
1591					}
1592				}
1593			});
1594		}
1595	}
1596
1597	public void populateWithOrderedConversations(final List<Conversation> list) {
1598		populateWithOrderedConversations(list, true);
1599	}
1600
1601	public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1602		list.clear();
1603		if (includeNoFileUpload) {
1604			list.addAll(getConversations());
1605		} else {
1606			for (Conversation conversation : getConversations()) {
1607				if (conversation.getMode() == Conversation.MODE_SINGLE
1608						|| (conversation.getAccount().httpUploadAvailable() && conversation.getMucOptions().participating())) {
1609					list.add(conversation);
1610				}
1611			}
1612		}
1613		try {
1614			Collections.sort(list);
1615		} catch (IllegalArgumentException e) {
1616			//ignore
1617		}
1618	}
1619
1620	public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1621		if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
1622			return;
1623		} else if (timestamp == 0) {
1624			return;
1625		}
1626		Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1627		final Runnable runnable = () -> {
1628			final Account account = conversation.getAccount();
1629			List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
1630			if (messages.size() > 0) {
1631				conversation.addAll(0, messages);
1632				checkDeletedFiles(conversation);
1633				callback.onMoreMessagesLoaded(messages.size(), conversation);
1634			} else if (conversation.hasMessagesLeftOnServer()
1635					&& account.isOnlineAndConnected()
1636					&& conversation.getLastClearHistory().getTimestamp() == 0) {
1637				final boolean mamAvailable;
1638				if (conversation.getMode() == Conversation.MODE_SINGLE) {
1639					mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
1640				} else {
1641					mamAvailable = conversation.getMucOptions().mamSupport();
1642				}
1643				if (mamAvailable) {
1644					MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
1645					if (query != null) {
1646						query.setCallback(callback);
1647						callback.informUser(R.string.fetching_history_from_server);
1648					} else {
1649						callback.informUser(R.string.not_fetching_history_retention_period);
1650					}
1651
1652				}
1653			}
1654		};
1655		mDatabaseReaderExecutor.execute(runnable);
1656	}
1657
1658	public List<Account> getAccounts() {
1659		return this.accounts;
1660	}
1661
1662	public List<Conversation> findAllConferencesWith(Contact contact) {
1663		ArrayList<Conversation> results = new ArrayList<>();
1664		for (final Conversation c : conversations) {
1665			if (c.getMode() == Conversation.MODE_MULTI && c.getMucOptions().isContactInRoom(contact)) {
1666			    results.add(c);
1667			}
1668		}
1669		return results;
1670	}
1671
1672	public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1673		for (final Conversation conversation : haystack) {
1674			if (conversation.getContact() == contact) {
1675				return conversation;
1676			}
1677		}
1678		return null;
1679	}
1680
1681	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1682		if (jid == null) {
1683			return null;
1684		}
1685		for (final Conversation conversation : haystack) {
1686			if ((account == null || conversation.getAccount() == account)
1687					&& (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
1688				return conversation;
1689			}
1690		}
1691		return null;
1692	}
1693
1694	public boolean isConversationsListEmpty(final Conversation ignore) {
1695		synchronized (this.conversations) {
1696			final int size = this.conversations.size();
1697			return size == 0 || size == 1 && this.conversations.get(0) == ignore;
1698		}
1699	}
1700
1701	public boolean isConversationStillOpen(final Conversation conversation) {
1702		synchronized (this.conversations) {
1703			for (Conversation current : this.conversations) {
1704				if (current == conversation) {
1705					return true;
1706				}
1707			}
1708		}
1709		return false;
1710	}
1711
1712	public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
1713		return this.findOrCreateConversation(account, jid, muc, false, async);
1714	}
1715
1716	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
1717		return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
1718	}
1719
1720	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
1721		synchronized (this.conversations) {
1722			Conversation conversation = find(account, jid);
1723			if (conversation != null) {
1724				return conversation;
1725			}
1726			conversation = databaseBackend.findConversation(account, jid);
1727			final boolean loadMessagesFromDb;
1728			if (conversation != null) {
1729				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1730				conversation.setAccount(account);
1731				if (muc) {
1732					conversation.setMode(Conversation.MODE_MULTI);
1733					conversation.setContactJid(jid);
1734				} else {
1735					conversation.setMode(Conversation.MODE_SINGLE);
1736					conversation.setContactJid(jid.asBareJid());
1737				}
1738				databaseBackend.updateConversation(conversation);
1739				loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
1740			} else {
1741				String conversationName;
1742				Contact contact = account.getRoster().getContact(jid);
1743				if (contact != null) {
1744					conversationName = contact.getDisplayName();
1745				} else {
1746					conversationName = jid.getLocal();
1747				}
1748				if (muc) {
1749					conversation = new Conversation(conversationName, account, jid,
1750							Conversation.MODE_MULTI);
1751				} else {
1752					conversation = new Conversation(conversationName, account, jid.asBareJid(),
1753							Conversation.MODE_SINGLE);
1754				}
1755				this.databaseBackend.createConversation(conversation);
1756				loadMessagesFromDb = false;
1757			}
1758			final Conversation c = conversation;
1759			final Runnable runnable = () -> {
1760				if (loadMessagesFromDb) {
1761					c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
1762					updateConversationUi();
1763					c.messagesLoaded.set(true);
1764				}
1765				if (account.getXmppConnection() != null
1766						&& !c.getContact().isBlocked()
1767						&& account.getXmppConnection().getFeatures().mam()
1768						&& !muc) {
1769					if (query == null) {
1770						mMessageArchiveService.query(c);
1771					} else {
1772						if (query.getConversation() == null) {
1773							mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
1774						}
1775					}
1776				}
1777				checkDeletedFiles(c);
1778				if (joinAfterCreate) {
1779					joinMuc(c);
1780				}
1781			};
1782			if (async) {
1783				mDatabaseReaderExecutor.execute(runnable);
1784			} else {
1785				runnable.run();
1786			}
1787			this.conversations.add(conversation);
1788			updateConversationUi();
1789			return conversation;
1790		}
1791	}
1792
1793	public void archiveConversation(Conversation conversation) {
1794		getNotificationService().clear(conversation);
1795		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1796		conversation.setNextMessage(null);
1797		synchronized (this.conversations) {
1798			getMessageArchiveService().kill(conversation);
1799			if (conversation.getMode() == Conversation.MODE_MULTI) {
1800				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1801					Bookmark bookmark = conversation.getBookmark();
1802					if (bookmark != null && bookmark.autojoin() && respectAutojoin()) {
1803						bookmark.setAutojoin(false);
1804						pushBookmarks(bookmark.getAccount());
1805					}
1806				}
1807				leaveMuc(conversation);
1808			} else {
1809				if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1810					Log.d(Config.LOGTAG, "Canceling presence request from " + conversation.getJid().toString());
1811					sendPresencePacket(
1812							conversation.getAccount(),
1813							mPresenceGenerator.stopPresenceUpdatesTo(conversation.getContact())
1814					);
1815				}
1816			}
1817			updateConversation(conversation);
1818			this.conversations.remove(conversation);
1819			updateConversationUi();
1820		}
1821	}
1822
1823	public void createAccount(final Account account) {
1824		account.initAccountServices(this);
1825		databaseBackend.createAccount(account);
1826		this.accounts.add(account);
1827		this.reconnectAccountInBackground(account);
1828		updateAccountUi();
1829		syncEnabledAccountSetting();
1830		toggleForegroundService();
1831	}
1832
1833	private void syncEnabledAccountSetting() {
1834		getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts()).apply();
1835	}
1836
1837	public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1838		new Thread(() -> {
1839			try {
1840				final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
1841				final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
1842				if (cert == null) {
1843					callback.informUser(R.string.unable_to_parse_certificate);
1844					return;
1845				}
1846				Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
1847				if (info == null) {
1848					callback.informUser(R.string.certificate_does_not_contain_jid);
1849					return;
1850				}
1851				if (findAccountByJid(info.first) == null) {
1852					Account account = new Account(info.first, "");
1853					account.setPrivateKeyAlias(alias);
1854					account.setOption(Account.OPTION_DISABLED, true);
1855					account.setDisplayName(info.second);
1856					createAccount(account);
1857					callback.onAccountCreated(account);
1858					if (Config.X509_VERIFICATION) {
1859						try {
1860							getMemorizingTrustManager().getNonInteractive(account.getJid().getDomain()).checkClientTrusted(chain, "RSA");
1861						} catch (CertificateException e) {
1862							callback.informUser(R.string.certificate_chain_is_not_trusted);
1863						}
1864					}
1865				} else {
1866					callback.informUser(R.string.account_already_exists);
1867				}
1868			} catch (Exception e) {
1869				e.printStackTrace();
1870				callback.informUser(R.string.unable_to_parse_certificate);
1871			}
1872		}).start();
1873
1874	}
1875
1876	public void updateKeyInAccount(final Account account, final String alias) {
1877		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
1878		try {
1879			X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1880			Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
1881			Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1882			if (info == null) {
1883				showErrorToastInUi(R.string.certificate_does_not_contain_jid);
1884				return;
1885			}
1886			if (account.getJid().asBareJid().equals(info.first)) {
1887				account.setPrivateKeyAlias(alias);
1888				account.setDisplayName(info.second);
1889				databaseBackend.updateAccount(account);
1890				if (Config.X509_VERIFICATION) {
1891					try {
1892						getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1893					} catch (CertificateException e) {
1894						showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1895					}
1896					account.getAxolotlService().regenerateKeys(true);
1897				}
1898			} else {
1899				showErrorToastInUi(R.string.jid_does_not_match_certificate);
1900			}
1901		} catch (Exception e) {
1902			e.printStackTrace();
1903		}
1904	}
1905
1906	public boolean updateAccount(final Account account) {
1907		if (databaseBackend.updateAccount(account)) {
1908			account.setShowErrorNotification(true);
1909			this.statusListener.onStatusChanged(account);
1910			databaseBackend.updateAccount(account);
1911			reconnectAccountInBackground(account);
1912			updateAccountUi();
1913			getNotificationService().updateErrorNotification();
1914			toggleForegroundService();
1915			syncEnabledAccountSetting();
1916			return true;
1917		} else {
1918			return false;
1919		}
1920	}
1921
1922	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1923		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1924		sendIqPacket(account, iq, (a, packet) -> {
1925			if (packet.getType() == IqPacket.TYPE.RESULT) {
1926				a.setPassword(newPassword);
1927				a.setOption(Account.OPTION_MAGIC_CREATE, false);
1928				databaseBackend.updateAccount(a);
1929				callback.onPasswordChangeSucceeded();
1930			} else {
1931				callback.onPasswordChangeFailed();
1932			}
1933		});
1934	}
1935
1936	public void deleteAccount(final Account account) {
1937		synchronized (this.conversations) {
1938			for (final Conversation conversation : conversations) {
1939				if (conversation.getAccount() == account) {
1940					if (conversation.getMode() == Conversation.MODE_MULTI) {
1941						leaveMuc(conversation);
1942					}
1943					conversations.remove(conversation);
1944				}
1945			}
1946			if (account.getXmppConnection() != null) {
1947				new Thread(() -> disconnect(account, true)).start();
1948			}
1949			final Runnable runnable = () -> {
1950				if (!databaseBackend.deleteAccount(account)) {
1951					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
1952				}
1953			};
1954			mDatabaseWriterExecutor.execute(runnable);
1955			this.accounts.remove(account);
1956			this.mRosterSyncTaskManager.clear(account);
1957			updateAccountUi();
1958			getNotificationService().updateErrorNotification();
1959			syncEnabledAccountSetting();
1960			toggleForegroundService();
1961		}
1962	}
1963
1964	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1965		final boolean remainingListeners;
1966		synchronized (LISTENER_LOCK) {
1967			remainingListeners = checkListeners();
1968			if (!this.mOnConversationUpdates.add(listener)) {
1969				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as ConversationListChangedListener");
1970			}
1971			this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
1972		}
1973		if (remainingListeners) {
1974			switchToForeground();
1975		}
1976	}
1977
1978	public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
1979		final boolean remainingListeners;
1980		synchronized (LISTENER_LOCK) {
1981			this.mOnConversationUpdates.remove(listener);
1982			this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
1983			remainingListeners = checkListeners();
1984		}
1985		if (remainingListeners) {
1986			switchToBackground();
1987		}
1988	}
1989
1990	public void setOnShowErrorToastListener(OnShowErrorToast listener) {
1991		final boolean remainingListeners;
1992		synchronized (LISTENER_LOCK) {
1993			remainingListeners = checkListeners();
1994			if (!this.mOnShowErrorToasts.add(listener)) {
1995				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnShowErrorToastListener");
1996			}
1997		}
1998		if (remainingListeners) {
1999			switchToForeground();
2000		}
2001	}
2002
2003	public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
2004		final boolean remainingListeners;
2005		synchronized (LISTENER_LOCK) {
2006			this.mOnShowErrorToasts.remove(onShowErrorToast);
2007			remainingListeners = checkListeners();
2008		}
2009		if (remainingListeners) {
2010			switchToBackground();
2011		}
2012	}
2013
2014	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
2015		final boolean remainingListeners;
2016		synchronized (LISTENER_LOCK) {
2017			remainingListeners = checkListeners();
2018			if (!this.mOnAccountUpdates.add(listener)) {
2019				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnAccountListChangedtListener");
2020			}
2021		}
2022		if (remainingListeners) {
2023			switchToForeground();
2024		}
2025	}
2026
2027	public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
2028		final boolean remainingListeners;
2029		synchronized (LISTENER_LOCK) {
2030			this.mOnAccountUpdates.remove(listener);
2031			remainingListeners = checkListeners();
2032		}
2033		if (remainingListeners) {
2034			switchToBackground();
2035		}
2036	}
2037
2038	public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2039		final boolean remainingListeners;
2040		synchronized (LISTENER_LOCK) {
2041			remainingListeners = checkListeners();
2042			if (!this.mOnCaptchaRequested.add(listener)) {
2043				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnCaptchaRequestListener");
2044			}
2045		}
2046		if (remainingListeners) {
2047			switchToForeground();
2048		}
2049	}
2050
2051	public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2052		final boolean remainingListeners;
2053		synchronized (LISTENER_LOCK) {
2054			this.mOnCaptchaRequested.remove(listener);
2055			remainingListeners = checkListeners();
2056		}
2057		if (remainingListeners) {
2058			switchToBackground();
2059		}
2060	}
2061
2062	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
2063		final boolean remainingListeners;
2064		synchronized (LISTENER_LOCK) {
2065			remainingListeners = checkListeners();
2066			if (!this.mOnRosterUpdates.add(listener)) {
2067				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnRosterUpdateListener");
2068			}
2069		}
2070		if (remainingListeners) {
2071			switchToForeground();
2072		}
2073	}
2074
2075	public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
2076		final boolean remainingListeners;
2077		synchronized (LISTENER_LOCK) {
2078			this.mOnRosterUpdates.remove(listener);
2079			remainingListeners = checkListeners();
2080		}
2081		if (remainingListeners) {
2082			switchToBackground();
2083		}
2084	}
2085
2086	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2087		final boolean remainingListeners;
2088		synchronized (LISTENER_LOCK) {
2089			remainingListeners = checkListeners();
2090			if (!this.mOnUpdateBlocklist.add(listener)) {
2091				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnUpdateBlocklistListener");
2092			}
2093		}
2094		if (remainingListeners) {
2095			switchToForeground();
2096		}
2097	}
2098
2099	public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2100		final boolean remainingListeners;
2101		synchronized (LISTENER_LOCK) {
2102			this.mOnUpdateBlocklist.remove(listener);
2103			remainingListeners = checkListeners();
2104		}
2105		if (remainingListeners) {
2106			switchToBackground();
2107		}
2108	}
2109
2110	public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2111		final boolean remainingListeners;
2112		synchronized (LISTENER_LOCK) {
2113			remainingListeners = checkListeners();
2114			if (!this.mOnKeyStatusUpdated.add(listener)) {
2115				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnKeyStatusUpdateListener");
2116			}
2117		}
2118		if (remainingListeners) {
2119			switchToForeground();
2120		}
2121	}
2122
2123	public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
2124		final boolean remainingListeners;
2125		synchronized (LISTENER_LOCK) {
2126			this.mOnKeyStatusUpdated.remove(listener);
2127			remainingListeners = checkListeners();
2128		}
2129		if (remainingListeners) {
2130			switchToBackground();
2131		}
2132	}
2133
2134	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2135		final boolean remainingListeners;
2136		synchronized (LISTENER_LOCK) {
2137			remainingListeners = checkListeners();
2138			if (!this.mOnMucRosterUpdate.add(listener)) {
2139				Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnMucRosterListener");
2140			}
2141		}
2142		if (remainingListeners) {
2143			switchToForeground();
2144		}
2145	}
2146
2147	public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
2148		final boolean remainingListeners;
2149		synchronized (LISTENER_LOCK) {
2150			this.mOnMucRosterUpdate.remove(listener);
2151			remainingListeners = checkListeners();
2152		}
2153		if (remainingListeners) {
2154			switchToBackground();
2155		}
2156	}
2157
2158	public boolean checkListeners() {
2159		return (this.mOnAccountUpdates.size() == 0
2160				&& this.mOnConversationUpdates.size() == 0
2161				&& this.mOnRosterUpdates.size() == 0
2162				&& this.mOnCaptchaRequested.size() == 0
2163				&& this.mOnMucRosterUpdate.size() == 0
2164				&& this.mOnUpdateBlocklist.size() == 0
2165				&& this.mOnShowErrorToasts.size() == 0
2166				&& this.mOnKeyStatusUpdated.size() == 0);
2167	}
2168
2169	private void switchToForeground() {
2170		final boolean broadcastLastActivity = broadcastLastActivity();
2171		for (Conversation conversation : getConversations()) {
2172			if (conversation.getMode() == Conversation.MODE_MULTI) {
2173				conversation.getMucOptions().resetChatState();
2174			} else {
2175				conversation.setIncomingChatState(Config.DEFAULT_CHATSTATE);
2176			}
2177		}
2178		for (Account account : getAccounts()) {
2179			if (account.getStatus() == Account.State.ONLINE) {
2180				account.deactivateGracePeriod();
2181				final XmppConnection connection = account.getXmppConnection();
2182				if (connection != null) {
2183					if (connection.getFeatures().csi()) {
2184						connection.sendActive();
2185					}
2186					if (broadcastLastActivity) {
2187						sendPresence(account, false); //send new presence but don't include idle because we are not
2188					}
2189				}
2190			}
2191		}
2192		Log.d(Config.LOGTAG, "app switched into foreground");
2193	}
2194
2195	private void switchToBackground() {
2196		final boolean broadcastLastActivity = broadcastLastActivity();
2197		if (broadcastLastActivity) {
2198			mLastActivity = System.currentTimeMillis();
2199			final SharedPreferences.Editor editor = getPreferences().edit();
2200			editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
2201			editor.apply();
2202		}
2203		for (Account account : getAccounts()) {
2204			if (account.getStatus() == Account.State.ONLINE) {
2205				XmppConnection connection = account.getXmppConnection();
2206				if (connection != null) {
2207					if (broadcastLastActivity) {
2208						sendPresence(account, true);
2209					}
2210					if (connection.getFeatures().csi()) {
2211						connection.sendInactive();
2212					}
2213				}
2214			}
2215		}
2216		this.mNotificationService.setIsInForeground(false);
2217		Log.d(Config.LOGTAG, "app switched into background");
2218	}
2219
2220	private void connectMultiModeConversations(Account account) {
2221		List<Conversation> conversations = getConversations();
2222		for (Conversation conversation : conversations) {
2223			if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2224				joinMuc(conversation);
2225			}
2226		}
2227	}
2228
2229	public void joinMuc(Conversation conversation) {
2230		joinMuc(conversation, null, false);
2231	}
2232
2233	public void joinMuc(Conversation conversation, boolean followedInvite) {
2234		joinMuc(conversation, null, followedInvite);
2235	}
2236
2237	private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2238		joinMuc(conversation, onConferenceJoined, false);
2239	}
2240
2241	private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2242		Account account = conversation.getAccount();
2243		account.pendingConferenceJoins.remove(conversation);
2244		account.pendingConferenceLeaves.remove(conversation);
2245		if (account.getStatus() == Account.State.ONLINE) {
2246			sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
2247			conversation.resetMucOptions();
2248			if (onConferenceJoined != null) {
2249				conversation.getMucOptions().flagNoAutoPushConfiguration();
2250			}
2251			conversation.setHasMessagesLeftOnServer(false);
2252			fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2253
2254				private void join(Conversation conversation) {
2255					Account account = conversation.getAccount();
2256					final MucOptions mucOptions = conversation.getMucOptions();
2257					final Jid joinJid = mucOptions.getSelf().getFullJid();
2258					Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
2259					PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
2260					packet.setTo(joinJid);
2261					Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2262					if (conversation.getMucOptions().getPassword() != null) {
2263						x.addChild("password").setContent(mucOptions.getPassword());
2264					}
2265
2266					if (mucOptions.mamSupport()) {
2267						// Use MAM instead of the limited muc history to get history
2268						x.addChild("history").setAttribute("maxchars", "0");
2269					} else {
2270						// Fallback to muc history
2271						x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
2272					}
2273					sendPresencePacket(account, packet);
2274					if (onConferenceJoined != null) {
2275						onConferenceJoined.onConferenceJoined(conversation);
2276					}
2277					if (!joinJid.equals(conversation.getJid())) {
2278						conversation.setContactJid(joinJid);
2279						databaseBackend.updateConversation(conversation);
2280					}
2281
2282					if (mucOptions.mamSupport()) {
2283						getMessageArchiveService().catchupMUC(conversation);
2284					}
2285					if (mucOptions.isPrivateAndNonAnonymous()) {
2286						fetchConferenceMembers(conversation);
2287						if (followedInvite && conversation.getBookmark() == null) {
2288							saveConversationAsBookmark(conversation, null);
2289						}
2290					}
2291					sendUnsentMessages(conversation);
2292				}
2293
2294				@Override
2295				public void onConferenceConfigurationFetched(Conversation conversation) {
2296					join(conversation);
2297				}
2298
2299				@Override
2300				public void onFetchFailed(final Conversation conversation, Element error) {
2301					if (error != null && "remote-server-not-found".equals(error.getName())) {
2302						conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2303						updateConversationUi();
2304					} else {
2305						join(conversation);
2306						fetchConferenceConfiguration(conversation);
2307					}
2308				}
2309			});
2310			updateConversationUi();
2311		} else {
2312			account.pendingConferenceJoins.add(conversation);
2313			conversation.resetMucOptions();
2314			conversation.setHasMessagesLeftOnServer(false);
2315			updateConversationUi();
2316		}
2317	}
2318
2319	private void fetchConferenceMembers(final Conversation conversation) {
2320		final Account account = conversation.getAccount();
2321		final AxolotlService axolotlService = account.getAxolotlService();
2322		final String[] affiliations = {"member", "admin", "owner"};
2323		OnIqPacketReceived callback = new OnIqPacketReceived() {
2324
2325			private int i = 0;
2326			private boolean success = true;
2327
2328			@Override
2329			public void onIqPacketReceived(Account account, IqPacket packet) {
2330				final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
2331				Element query = packet.query("http://jabber.org/protocol/muc#admin");
2332				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2333					for (Element child : query.getChildren()) {
2334						if ("item".equals(child.getName())) {
2335							MucOptions.User user = AbstractParser.parseItem(conversation, child);
2336							if (!user.realJidMatchesAccount()) {
2337								boolean isNew = conversation.getMucOptions().updateUser(user);
2338								Contact contact = user.getContact();
2339								if (omemoEnabled
2340										&& isNew
2341										&& user.getRealJid() != null
2342										&& (contact == null || !contact.mutualPresenceSubscription())
2343										&& axolotlService.hasEmptyDeviceList(user.getRealJid())) {
2344									axolotlService.fetchDeviceIds(user.getRealJid());
2345								}
2346							}
2347						}
2348					}
2349				} else {
2350					success = false;
2351					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
2352				}
2353				++i;
2354				if (i >= affiliations.length) {
2355					List<Jid> members = conversation.getMucOptions().getMembers(true);
2356					if (success) {
2357						List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
2358						boolean changed = false;
2359						for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
2360							Jid jid = iterator.next();
2361							if (!members.contains(jid) && !members.contains(Jid.ofDomain(jid.getDomain()))) {
2362								iterator.remove();
2363								Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
2364								changed = true;
2365							}
2366						}
2367						if (changed) {
2368							conversation.setAcceptedCryptoTargets(cryptoTargets);
2369							updateConversation(conversation);
2370						}
2371					}
2372					getAvatarService().clear(conversation);
2373					updateMucRosterUi();
2374					updateConversationUi();
2375				}
2376			}
2377		};
2378		for (String affiliation : affiliations) {
2379			sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2380		}
2381		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
2382	}
2383
2384	public void providePasswordForMuc(Conversation conversation, String password) {
2385		if (conversation.getMode() == Conversation.MODE_MULTI) {
2386			conversation.getMucOptions().setPassword(password);
2387			if (conversation.getBookmark() != null) {
2388				if (respectAutojoin()) {
2389					conversation.getBookmark().setAutojoin(true);
2390				}
2391				pushBookmarks(conversation.getAccount());
2392			}
2393			updateConversation(conversation);
2394			joinMuc(conversation);
2395		}
2396	}
2397
2398	private boolean hasEnabledAccounts() {
2399		for (Account account : this.accounts) {
2400			if (account.isEnabled()) {
2401				return true;
2402			}
2403		}
2404		return false;
2405	}
2406
2407
2408	public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
2409        getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
2410    }
2411
2412    public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2413        getAttachments(account.getUuid(),jid.asBareJid(),limit, onMediaLoaded);
2414    }
2415
2416
2417	public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2418        new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
2419    }
2420
2421	public void persistSelfNick(MucOptions.User self) {
2422		final Conversation conversation = self.getConversation();
2423		Jid full = self.getFullJid();
2424		if (!full.equals(conversation.getJid())) {
2425			Log.d(Config.LOGTAG, "nick changed. updating");
2426			conversation.setContactJid(full);
2427			databaseBackend.updateConversation(conversation);
2428		}
2429
2430		Bookmark bookmark = conversation.getBookmark();
2431		if (bookmark != null && !full.getResource().equals(bookmark.getNick())) {
2432			bookmark.setNick(full.getResource());
2433			pushBookmarks(bookmark.getAccount());
2434		}
2435	}
2436
2437	public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2438		final MucOptions options = conversation.getMucOptions();
2439		final Jid joinJid = options.createJoinJid(nick);
2440		if (joinJid == null) {
2441			return false;
2442		}
2443		if (options.online()) {
2444			Account account = conversation.getAccount();
2445			options.setOnRenameListener(new OnRenameListener() {
2446
2447				@Override
2448				public void onSuccess() {
2449					callback.success(conversation);
2450				}
2451
2452				@Override
2453				public void onFailure() {
2454					callback.error(R.string.nick_in_use, conversation);
2455				}
2456			});
2457
2458			PresencePacket packet = new PresencePacket();
2459			packet.setTo(joinJid);
2460			packet.setFrom(conversation.getAccount().getJid());
2461
2462			String sig = account.getPgpSignature();
2463			if (sig != null) {
2464				packet.addChild("status").setContent("online");
2465				packet.addChild("x", "jabber:x:signed").setContent(sig);
2466			}
2467			sendPresencePacket(account, packet);
2468		} else {
2469			conversation.setContactJid(joinJid);
2470			databaseBackend.updateConversation(conversation);
2471			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2472				Bookmark bookmark = conversation.getBookmark();
2473				if (bookmark != null) {
2474					bookmark.setNick(nick);
2475					pushBookmarks(bookmark.getAccount());
2476				}
2477				joinMuc(conversation);
2478			}
2479		}
2480		return true;
2481	}
2482
2483	public void leaveMuc(Conversation conversation) {
2484		leaveMuc(conversation, false);
2485	}
2486
2487	private void leaveMuc(Conversation conversation, boolean now) {
2488		Account account = conversation.getAccount();
2489		account.pendingConferenceJoins.remove(conversation);
2490		account.pendingConferenceLeaves.remove(conversation);
2491		if (account.getStatus() == Account.State.ONLINE || now) {
2492			sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
2493			conversation.getMucOptions().setOffline();
2494			Bookmark bookmark = conversation.getBookmark();
2495			if (bookmark != null) {
2496				bookmark.setConversation(null);
2497			}
2498			Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
2499		} else {
2500			account.pendingConferenceLeaves.add(conversation);
2501		}
2502	}
2503
2504	public String findConferenceServer(final Account account) {
2505		String server;
2506		if (account.getXmppConnection() != null) {
2507			server = account.getXmppConnection().getMucServer();
2508			if (server != null) {
2509				return server;
2510			}
2511		}
2512		for (Account other : getAccounts()) {
2513			if (other != account && other.getXmppConnection() != null) {
2514				server = other.getXmppConnection().getMucServer();
2515				if (server != null) {
2516					return server;
2517				}
2518			}
2519		}
2520		return null;
2521	}
2522
2523	public boolean createAdhocConference(final Account account,
2524	                                     final String name,
2525	                                     final Iterable<Jid> jids,
2526	                                     final UiCallback<Conversation> callback) {
2527		Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2528		if (account.getStatus() == Account.State.ONLINE) {
2529			try {
2530				String server = findConferenceServer(account);
2531				if (server == null) {
2532					if (callback != null) {
2533						callback.error(R.string.no_conference_server_found, null);
2534					}
2535					return false;
2536				}
2537				final Jid jid = Jid.of(CryptoHelper.pronounceable(getRNG()), server, null);
2538				final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
2539				joinMuc(conversation, new OnConferenceJoined() {
2540					@Override
2541					public void onConferenceJoined(final Conversation conversation) {
2542						final Bundle configuration = IqGenerator.defaultRoomConfiguration();
2543						if (!TextUtils.isEmpty(name)) {
2544							configuration.putString("muc#roomconfig_roomname", name);
2545						}
2546						pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
2547							@Override
2548							public void onPushSucceeded() {
2549								for (Jid invite : jids) {
2550									invite(conversation, invite);
2551								}
2552								if (account.countPresences() > 1) {
2553									directInvite(conversation, account.getJid().asBareJid());
2554								}
2555								saveConversationAsBookmark(conversation, name);
2556								if (callback != null) {
2557									callback.success(conversation);
2558								}
2559							}
2560
2561							@Override
2562							public void onPushFailed() {
2563								archiveConversation(conversation);
2564								if (callback != null) {
2565									callback.error(R.string.conference_creation_failed, conversation);
2566								}
2567							}
2568						});
2569					}
2570				});
2571				return true;
2572			} catch (IllegalArgumentException e) {
2573				if (callback != null) {
2574					callback.error(R.string.conference_creation_failed, null);
2575				}
2576				return false;
2577			}
2578		} else {
2579			if (callback != null) {
2580				callback.error(R.string.not_connected_try_again, null);
2581			}
2582			return false;
2583		}
2584	}
2585
2586	public void fetchConferenceConfiguration(final Conversation conversation) {
2587		fetchConferenceConfiguration(conversation, null);
2588	}
2589
2590	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2591		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2592		request.setTo(conversation.getJid().asBareJid());
2593		request.query("http://jabber.org/protocol/disco#info");
2594		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2595			@Override
2596			public void onIqPacketReceived(Account account, IqPacket packet) {
2597				if (packet.getType() == IqPacket.TYPE.RESULT) {
2598
2599					final MucOptions mucOptions = conversation.getMucOptions();
2600					final Bookmark bookmark = conversation.getBookmark();
2601					final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
2602
2603					if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
2604						Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
2605						updateConversation(conversation);
2606					}
2607
2608					if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
2609						if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
2610							pushBookmarks(account);
2611						}
2612					}
2613
2614
2615					if (callback != null) {
2616						callback.onConferenceConfigurationFetched(conversation);
2617					}
2618
2619
2620
2621					updateConversationUi();
2622				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
2623					if (callback != null) {
2624						callback.onFetchFailed(conversation, packet.getError());
2625					}
2626				}
2627			}
2628		});
2629	}
2630
2631	public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
2632		pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
2633	}
2634
2635	public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
2636        Log.d(Config.LOGTAG,"pushing node configuration");
2637		sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
2638			@Override
2639			public void onIqPacketReceived(Account account, IqPacket packet) {
2640				if (packet.getType() == IqPacket.TYPE.RESULT) {
2641					Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
2642					Element configuration = pubsub == null ? null : pubsub.findChild("configure");
2643					Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
2644					if (x != null) {
2645						Data data = Data.parse(x);
2646						data.submit(options);
2647						sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
2648							@Override
2649							public void onIqPacketReceived(Account account, IqPacket packet) {
2650								if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
2651									Log.d(Config.LOGTAG,account.getJid().asBareJid()+": successfully changed node configuration for node "+node);
2652									callback.onPushSucceeded();
2653								} else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
2654									callback.onPushFailed();
2655								}
2656							}
2657						});
2658					} else if (callback != null) {
2659						callback.onPushFailed();
2660					}
2661				} else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
2662					callback.onPushFailed();
2663				}
2664			}
2665		});
2666	}
2667
2668	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
2669		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2670		request.setTo(conversation.getJid().asBareJid());
2671		request.query("http://jabber.org/protocol/muc#owner");
2672		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2673			@Override
2674			public void onIqPacketReceived(Account account, IqPacket packet) {
2675				if (packet.getType() == IqPacket.TYPE.RESULT) {
2676					Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
2677					data.submit(options);
2678					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2679					set.setTo(conversation.getJid().asBareJid());
2680					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2681					sendIqPacket(account, set, new OnIqPacketReceived() {
2682						@Override
2683						public void onIqPacketReceived(Account account, IqPacket packet) {
2684							if (callback != null) {
2685								if (packet.getType() == IqPacket.TYPE.RESULT) {
2686									callback.onPushSucceeded();
2687								} else {
2688									callback.onPushFailed();
2689								}
2690							}
2691						}
2692					});
2693				} else {
2694					if (callback != null) {
2695						callback.onPushFailed();
2696					}
2697				}
2698			}
2699		});
2700	}
2701
2702	public void pushSubjectToConference(final Conversation conference, final String subject) {
2703		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
2704		this.sendMessagePacket(conference.getAccount(), packet);
2705	}
2706
2707	public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2708		final Jid jid = user.asBareJid();
2709		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2710		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2711			@Override
2712			public void onIqPacketReceived(Account account, IqPacket packet) {
2713				if (packet.getType() == IqPacket.TYPE.RESULT) {
2714					conference.getMucOptions().changeAffiliation(jid, affiliation);
2715					getAvatarService().clear(conference);
2716					callback.onAffiliationChangedSuccessful(jid);
2717				} else {
2718					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2719				}
2720			}
2721		});
2722	}
2723
2724	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2725		List<Jid> jids = new ArrayList<>();
2726		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2727			if (user.getAffiliation() == before && user.getRealJid() != null) {
2728				jids.add(user.getRealJid());
2729			}
2730		}
2731		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2732		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2733	}
2734
2735	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2736		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2737		Log.d(Config.LOGTAG, request.toString());
2738		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2739			@Override
2740			public void onIqPacketReceived(Account account, IqPacket packet) {
2741				Log.d(Config.LOGTAG, packet.toString());
2742				if (packet.getType() == IqPacket.TYPE.RESULT) {
2743					callback.onRoleChangedSuccessful(nick);
2744				} else {
2745					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2746				}
2747			}
2748		});
2749	}
2750
2751	private void disconnect(Account account, boolean force) {
2752		if ((account.getStatus() == Account.State.ONLINE)
2753				|| (account.getStatus() == Account.State.DISABLED)) {
2754			final XmppConnection connection = account.getXmppConnection();
2755			if (!force) {
2756				List<Conversation> conversations = getConversations();
2757				for (Conversation conversation : conversations) {
2758					if (conversation.getAccount() == account) {
2759						if (conversation.getMode() == Conversation.MODE_MULTI) {
2760							leaveMuc(conversation, true);
2761						}
2762					}
2763				}
2764				sendOfflinePresence(account);
2765			}
2766			connection.disconnect(force);
2767		}
2768	}
2769
2770	@Override
2771	public IBinder onBind(Intent intent) {
2772		return mBinder;
2773	}
2774
2775	public void updateMessage(Message message) {
2776		updateMessage(message, true);
2777	}
2778
2779	public void updateMessage(Message message, boolean includeBody) {
2780		databaseBackend.updateMessage(message, includeBody);
2781		updateConversationUi();
2782	}
2783
2784	public void updateMessage(Message message, String uuid) {
2785		databaseBackend.updateMessage(message, uuid);
2786		updateConversationUi();
2787	}
2788
2789	protected void syncDirtyContacts(Account account) {
2790		for (Contact contact : account.getRoster().getContacts()) {
2791			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2792				pushContactToServer(contact);
2793			}
2794			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2795				deleteContactOnServer(contact);
2796			}
2797		}
2798	}
2799
2800	public void createContact(Contact contact, boolean autoGrant) {
2801		if (autoGrant) {
2802			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2803			contact.setOption(Contact.Options.ASKING);
2804		}
2805		pushContactToServer(contact);
2806	}
2807
2808	public void pushContactToServer(final Contact contact) {
2809		contact.resetOption(Contact.Options.DIRTY_DELETE);
2810		contact.setOption(Contact.Options.DIRTY_PUSH);
2811		final Account account = contact.getAccount();
2812		if (account.getStatus() == Account.State.ONLINE) {
2813			final boolean ask = contact.getOption(Contact.Options.ASKING);
2814			final boolean sendUpdates = contact
2815					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2816					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2817			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2818			iq.query(Namespace.ROSTER).addChild(contact.asElement());
2819			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2820			if (sendUpdates) {
2821				sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
2822			}
2823			if (ask) {
2824				sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2825			}
2826		} else {
2827			syncRoster(contact.getAccount());
2828		}
2829	}
2830
2831	public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
2832		new Thread(() -> {
2833			final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2834			final int size = Config.AVATAR_SIZE;
2835			final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2836			if (avatar != null) {
2837				if (!getFileBackend().save(avatar)) {
2838					callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
2839					return;
2840				}
2841				avatar.owner = conversation.getJid().asBareJid();
2842				publishMucAvatar(conversation, avatar, callback);
2843			} else {
2844				callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
2845			}
2846		}).start();
2847	}
2848
2849	public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
2850		new Thread(() -> {
2851			final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2852			final int size = Config.AVATAR_SIZE;
2853			final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2854			if (avatar != null) {
2855				if (!getFileBackend().save(avatar)) {
2856					Log.d(Config.LOGTAG,"unable to save vcard");
2857					callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
2858					return;
2859				}
2860				publishAvatar(account, avatar, callback);
2861			} else {
2862				callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
2863			}
2864		}).start();
2865
2866	}
2867
2868	private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
2869		final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
2870		sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
2871			boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
2872			if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
2873				Element vcard = response.findChild("vCard", "vcard-temp");
2874				if (vcard == null) {
2875					vcard = new Element("vCard", "vcard-temp");
2876				}
2877				Element photo = vcard.findChild("PHOTO");
2878				if (photo == null) {
2879					photo = vcard.addChild("PHOTO");
2880				}
2881				photo.clearChildren();
2882				photo.addChild("TYPE").setContent(avatar.type);
2883				photo.addChild("BINVAL").setContent(avatar.image);
2884				IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
2885				publication.setTo(conversation.getJid().asBareJid());
2886				publication.addChild(vcard);
2887				sendIqPacket(account, publication, (a1, publicationResponse) -> {
2888					if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
2889						callback.onAvatarPublicationSucceeded();
2890					} else {
2891						Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getError());
2892						callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
2893					}
2894				});
2895			} else {
2896				Log.d(Config.LOGTAG, "failed to request vcard " + response.toString());
2897				callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
2898			}
2899		});
2900	}
2901
2902	public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
2903		IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2904		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2905
2906			@Override
2907			public void onIqPacketReceived(Account account, IqPacket result) {
2908				if (result.getType() == IqPacket.TYPE.RESULT) {
2909					final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar);
2910					sendIqPacket(account, packet, new OnIqPacketReceived() {
2911						@Override
2912						public void onIqPacketReceived(Account account, IqPacket result) {
2913							if (result.getType() == IqPacket.TYPE.RESULT) {
2914								if (account.setAvatar(avatar.getFilename())) {
2915									getAvatarService().clear(account);
2916									databaseBackend.updateAccount(account);
2917								}
2918								Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
2919								if (callback != null) {
2920									callback.onAvatarPublicationSucceeded();
2921								}
2922							} else {
2923								if (callback != null) {
2924									callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
2925								}
2926							}
2927						}
2928					});
2929				} else {
2930					Element error = result.findChild("error");
2931					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
2932					if (callback != null) {
2933						callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
2934					}
2935				}
2936			}
2937		});
2938	}
2939
2940	public void republishAvatarIfNeeded(Account account) {
2941		if (account.getAxolotlService().isPepBroken()) {
2942			Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
2943			return;
2944		}
2945		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2946		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2947
2948			private Avatar parseAvatar(IqPacket packet) {
2949				Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2950				if (pubsub != null) {
2951					Element items = pubsub.findChild("items");
2952					if (items != null) {
2953						return Avatar.parseMetadata(items);
2954					}
2955				}
2956				return null;
2957			}
2958
2959			private boolean errorIsItemNotFound(IqPacket packet) {
2960				Element error = packet.findChild("error");
2961				return packet.getType() == IqPacket.TYPE.ERROR
2962						&& error != null
2963						&& error.hasChild("item-not-found");
2964			}
2965
2966			@Override
2967			public void onIqPacketReceived(Account account, IqPacket packet) {
2968				if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2969					Avatar serverAvatar = parseAvatar(packet);
2970					if (serverAvatar == null && account.getAvatar() != null) {
2971						Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2972						if (avatar != null) {
2973							Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
2974							publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2975						} else {
2976							Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
2977						}
2978					}
2979				}
2980			}
2981		});
2982	}
2983
2984	public void fetchAvatar(Account account, Avatar avatar) {
2985		fetchAvatar(account, avatar, null);
2986	}
2987
2988	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2989		final String KEY = generateFetchKey(account, avatar);
2990		synchronized (this.mInProgressAvatarFetches) {
2991			if (!this.mInProgressAvatarFetches.contains(KEY)) {
2992				switch (avatar.origin) {
2993					case PEP:
2994						this.mInProgressAvatarFetches.add(KEY);
2995						fetchAvatarPep(account, avatar, callback);
2996						break;
2997					case VCARD:
2998						this.mInProgressAvatarFetches.add(KEY);
2999						fetchAvatarVcard(account, avatar, callback);
3000						break;
3001				}
3002			}
3003		}
3004	}
3005
3006	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3007		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
3008		sendIqPacket(account, packet, (a, result) -> {
3009			synchronized (mInProgressAvatarFetches) {
3010				mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
3011			}
3012			final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
3013			if (result.getType() == IqPacket.TYPE.RESULT) {
3014				avatar.image = mIqParser.avatarData(result);
3015				if (avatar.image != null) {
3016					if (getFileBackend().save(avatar)) {
3017						if (a.getJid().asBareJid().equals(avatar.owner)) {
3018							if (a.setAvatar(avatar.getFilename())) {
3019								databaseBackend.updateAccount(a);
3020							}
3021							getAvatarService().clear(a);
3022							updateConversationUi();
3023							updateAccountUi();
3024						} else {
3025							Contact contact = a.getRoster().getContact(avatar.owner);
3026							if (contact.setAvatar(avatar)) {
3027								syncRoster(account);
3028								getAvatarService().clear(contact);
3029								updateConversationUi();
3030								updateRosterUi();
3031							}
3032						}
3033						if (callback != null) {
3034							callback.success(avatar);
3035						}
3036						Log.d(Config.LOGTAG, a.getJid().asBareJid()
3037								+ ": successfully fetched pep avatar for " + avatar.owner);
3038						return;
3039					}
3040				} else {
3041
3042					Log.d(Config.LOGTAG, ERROR + "(parsing error)");
3043				}
3044			} else {
3045				Element error = result.findChild("error");
3046				if (error == null) {
3047					Log.d(Config.LOGTAG, ERROR + "(server error)");
3048				} else {
3049					Log.d(Config.LOGTAG, ERROR + error.toString());
3050				}
3051			}
3052			if (callback != null) {
3053				callback.error(0, null);
3054			}
3055
3056		});
3057	}
3058
3059	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3060		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
3061		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3062			@Override
3063			public void onIqPacketReceived(Account account, IqPacket packet) {
3064				synchronized (mInProgressAvatarFetches) {
3065					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
3066				}
3067				if (packet.getType() == IqPacket.TYPE.RESULT) {
3068					Element vCard = packet.findChild("vCard", "vcard-temp");
3069					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
3070					String image = photo != null ? photo.findChildContent("BINVAL") : null;
3071					if (image != null) {
3072						avatar.image = image;
3073						if (getFileBackend().save(avatar)) {
3074							Log.d(Config.LOGTAG, account.getJid().asBareJid()
3075									+ ": successfully fetched vCard avatar for " + avatar.owner);
3076							if (avatar.owner.isBareJid()) {
3077								if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
3078									Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
3079									account.setAvatar(avatar.getFilename());
3080									databaseBackend.updateAccount(account);
3081									getAvatarService().clear(account);
3082									updateAccountUi();
3083								} else {
3084									Contact contact = account.getRoster().getContact(avatar.owner);
3085									if (contact.setAvatar(avatar)) {
3086										syncRoster(account);
3087										getAvatarService().clear(contact);
3088										updateRosterUi();
3089									}
3090								}
3091								updateConversationUi();
3092							} else {
3093								Conversation conversation = find(account, avatar.owner.asBareJid());
3094								if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
3095									MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
3096									if (user != null) {
3097										if (user.setAvatar(avatar)) {
3098											getAvatarService().clear(user);
3099											updateConversationUi();
3100											updateMucRosterUi();
3101										}
3102										if (user.getRealJid() != null) {
3103										    Contact contact = account.getRoster().getContact(user.getRealJid());
3104										    if (contact.setAvatar(avatar)) {
3105                                                syncRoster(account);
3106                                                getAvatarService().clear(contact);
3107                                                updateRosterUi();
3108                                            }
3109                                        }
3110									}
3111								}
3112							}
3113						}
3114					}
3115				}
3116			}
3117		});
3118	}
3119
3120	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
3121		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3122		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3123
3124			@Override
3125			public void onIqPacketReceived(Account account, IqPacket packet) {
3126				if (packet.getType() == IqPacket.TYPE.RESULT) {
3127					Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3128					if (pubsub != null) {
3129						Element items = pubsub.findChild("items");
3130						if (items != null) {
3131							Avatar avatar = Avatar.parseMetadata(items);
3132							if (avatar != null) {
3133								avatar.owner = account.getJid().asBareJid();
3134								if (fileBackend.isAvatarCached(avatar)) {
3135									if (account.setAvatar(avatar.getFilename())) {
3136										databaseBackend.updateAccount(account);
3137									}
3138									getAvatarService().clear(account);
3139									callback.success(avatar);
3140								} else {
3141									fetchAvatarPep(account, avatar, callback);
3142								}
3143								return;
3144							}
3145						}
3146					}
3147				}
3148				callback.error(0, null);
3149			}
3150		});
3151	}
3152
3153	public void deleteContactOnServer(Contact contact) {
3154		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
3155		contact.resetOption(Contact.Options.DIRTY_PUSH);
3156		contact.setOption(Contact.Options.DIRTY_DELETE);
3157		Account account = contact.getAccount();
3158		if (account.getStatus() == Account.State.ONLINE) {
3159			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3160			Element item = iq.query(Namespace.ROSTER).addChild("item");
3161			item.setAttribute("jid", contact.getJid().toString());
3162			item.setAttribute("subscription", "remove");
3163			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3164		}
3165	}
3166
3167	public void updateConversation(final Conversation conversation) {
3168		mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
3169	}
3170
3171	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
3172		synchronized (account) {
3173			XmppConnection connection = account.getXmppConnection();
3174			if (connection == null) {
3175				connection = createConnection(account);
3176				account.setXmppConnection(connection);
3177			}
3178			boolean hasInternet = hasInternetConnection();
3179			if (account.isEnabled() && hasInternet) {
3180				if (!force) {
3181					disconnect(account, false);
3182				}
3183				Thread thread = new Thread(connection);
3184				connection.setInteractive(interactive);
3185				connection.prepareNewConnection();
3186				connection.interrupt();
3187				thread.start();
3188				scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
3189			} else {
3190				disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
3191				account.getRoster().clearPresences();
3192				connection.resetEverything();
3193				final AxolotlService axolotlService = account.getAxolotlService();
3194				if (axolotlService != null) {
3195					axolotlService.resetBrokenness();
3196				}
3197				if (!hasInternet) {
3198					account.setStatus(Account.State.NO_INTERNET);
3199				}
3200			}
3201		}
3202	}
3203
3204	public void reconnectAccountInBackground(final Account account) {
3205		new Thread(() -> reconnectAccount(account, false, true)).start();
3206	}
3207
3208	public void invite(Conversation conversation, Jid contact) {
3209		Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
3210		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
3211		sendMessagePacket(conversation.getAccount(), packet);
3212	}
3213
3214	public void directInvite(Conversation conversation, Jid jid) {
3215		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
3216		sendMessagePacket(conversation.getAccount(), packet);
3217	}
3218
3219	public void resetSendingToWaiting(Account account) {
3220		for (Conversation conversation : getConversations()) {
3221			if (conversation.getAccount() == account) {
3222				conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
3223			}
3224		}
3225	}
3226
3227	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
3228		return markMessage(account, recipient, uuid, status, null);
3229	}
3230
3231	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
3232		if (uuid == null) {
3233			return null;
3234		}
3235		for (Conversation conversation : getConversations()) {
3236			if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
3237				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
3238				if (message != null) {
3239					markMessage(message, status, errorMessage);
3240				}
3241				return message;
3242			}
3243		}
3244		return null;
3245	}
3246
3247	public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) {
3248		if (uuid == null) {
3249			return false;
3250		} else {
3251			Message message = conversation.findSentMessageWithUuid(uuid);
3252			if (message != null) {
3253				if (message.getServerMsgId() == null) {
3254					message.setServerMsgId(serverMessageId);
3255				}
3256				markMessage(message, status);
3257				return true;
3258			} else {
3259				return false;
3260			}
3261		}
3262	}
3263
3264	public void markMessage(Message message, int status) {
3265		markMessage(message, status, null);
3266	}
3267
3268
3269	public void markMessage(Message message, int status, String errorMessage) {
3270		final int c = message.getStatus();
3271		if (status == Message.STATUS_SEND_FAILED && (c == Message.STATUS_SEND_RECEIVED || c == Message.STATUS_SEND_DISPLAYED)) {
3272			return;
3273		}
3274		if (status == Message.STATUS_SEND_RECEIVED && c == Message.STATUS_SEND_DISPLAYED) {
3275			return;
3276		}
3277		message.setErrorMessage(errorMessage);
3278		message.setStatus(status);
3279		databaseBackend.updateMessage(message, false);
3280		updateConversationUi();
3281	}
3282
3283	private SharedPreferences getPreferences() {
3284		return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
3285	}
3286
3287	public long getAutomaticMessageDeletionDate() {
3288		final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
3289		return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
3290	}
3291
3292	public long getLongPreference(String name, @IntegerRes int res) {
3293		long defaultValue = getResources().getInteger(res);
3294		try {
3295			return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
3296		} catch (NumberFormatException e) {
3297			return defaultValue;
3298		}
3299	}
3300
3301	public boolean getBooleanPreference(String name, @BoolRes int res) {
3302		return getPreferences().getBoolean(name, getResources().getBoolean(res));
3303	}
3304
3305	public boolean confirmMessages() {
3306		return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
3307	}
3308
3309	public boolean allowMessageCorrection() {
3310		return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
3311	}
3312
3313	public boolean sendChatStates() {
3314		return getBooleanPreference("chat_states", R.bool.chat_states);
3315	}
3316
3317	private boolean respectAutojoin() {
3318		return getBooleanPreference("autojoin", R.bool.autojoin);
3319	}
3320
3321	public boolean indicateReceived() {
3322		return getBooleanPreference("indicate_received", R.bool.indicate_received);
3323	}
3324
3325	public boolean useTorToConnect() {
3326		return QuickConversationsService.isFull() && getBooleanPreference("use_tor", R.bool.use_tor);
3327	}
3328
3329	public boolean showExtendedConnectionOptions() {
3330		return QuickConversationsService.isFull() && getBooleanPreference("show_connection_options", R.bool.show_connection_options);
3331	}
3332
3333	public boolean broadcastLastActivity() {
3334		return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
3335	}
3336
3337	public int unreadCount() {
3338		int count = 0;
3339		for (Conversation conversation : getConversations()) {
3340			count += conversation.unreadCount();
3341		}
3342		return count;
3343	}
3344
3345
3346	private <T> List<T> threadSafeList(Set<T> set) {
3347		synchronized (LISTENER_LOCK) {
3348			return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
3349		}
3350	}
3351
3352	public void showErrorToastInUi(int resId) {
3353		for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
3354			listener.onShowErrorToast(resId);
3355		}
3356	}
3357
3358	public void updateConversationUi() {
3359		for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
3360			listener.onConversationUpdate();
3361		}
3362	}
3363
3364	public void updateAccountUi() {
3365		for (OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
3366			listener.onAccountUpdate();
3367		}
3368	}
3369
3370	public void updateRosterUi() {
3371		for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
3372			listener.onRosterUpdate();
3373		}
3374	}
3375
3376	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3377		if (mOnCaptchaRequested.size() > 0) {
3378			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3379			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3380					(int) (captcha.getHeight() * metrics.scaledDensity), false);
3381			for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
3382				listener.onCaptchaRequested(account, id, data, scaled);
3383			}
3384			return true;
3385		}
3386		return false;
3387	}
3388
3389	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3390		for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
3391			listener.OnUpdateBlocklist(status);
3392		}
3393	}
3394
3395	public void updateMucRosterUi() {
3396		for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
3397			listener.onMucRosterUpdate();
3398		}
3399	}
3400
3401	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3402		for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
3403			listener.onKeyStatusUpdated(report);
3404		}
3405	}
3406
3407	public Account findAccountByJid(final Jid accountJid) {
3408		for (Account account : this.accounts) {
3409			if (account.getJid().asBareJid().equals(accountJid.asBareJid())) {
3410				return account;
3411			}
3412		}
3413		return null;
3414	}
3415
3416	public Account findAccountByUuid(final String uuid) {
3417		for(Account account : this.accounts) {
3418			if (account.getUuid().equals(uuid)) {
3419				return account;
3420			}
3421		}
3422		return null;
3423	}
3424
3425	public Conversation findConversationByUuid(String uuid) {
3426		for (Conversation conversation : getConversations()) {
3427			if (conversation.getUuid().equals(uuid)) {
3428				return conversation;
3429			}
3430		}
3431		return null;
3432	}
3433
3434	public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
3435		List<Conversation> findings = new ArrayList<>();
3436		for (Conversation c : getConversations()) {
3437			if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
3438				findings.add(c);
3439			}
3440		}
3441		return findings.size() == 1 ? findings.get(0) : null;
3442	}
3443
3444	public boolean markRead(final Conversation conversation, boolean dismiss) {
3445		return markRead(conversation, null, dismiss).size() > 0;
3446	}
3447
3448	public void markRead(final Conversation conversation) {
3449		markRead(conversation, null, true);
3450	}
3451
3452	public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
3453		if (dismiss) {
3454			mNotificationService.clear(conversation);
3455		}
3456		final List<Message> readMessages = conversation.markRead(upToUuid);
3457		if (readMessages.size() > 0) {
3458			Runnable runnable = () -> {
3459				for (Message message : readMessages) {
3460					databaseBackend.updateMessage(message, false);
3461				}
3462			};
3463			mDatabaseWriterExecutor.execute(runnable);
3464			updateUnreadCountBadge();
3465			return readMessages;
3466		} else {
3467			return readMessages;
3468		}
3469	}
3470
3471	public synchronized void updateUnreadCountBadge() {
3472		int count = unreadCount();
3473		if (unreadCount != count) {
3474			Log.d(Config.LOGTAG, "update unread count to " + count);
3475			if (count > 0) {
3476				ShortcutBadger.applyCount(getApplicationContext(), count);
3477			} else {
3478				ShortcutBadger.removeCount(getApplicationContext());
3479			}
3480			unreadCount = count;
3481		}
3482	}
3483
3484	public void sendReadMarker(final Conversation conversation, String upToUuid) {
3485		final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
3486		final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
3487		if (readMessages.size() > 0) {
3488			updateConversationUi();
3489		}
3490		final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
3491		if (confirmMessages()
3492				&& markable != null
3493				&& (markable.trusted() || isPrivateAndNonAnonymousMuc)
3494				&& markable.getRemoteMsgId() != null) {
3495			Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
3496			Account account = conversation.getAccount();
3497			final Jid to = markable.getCounterpart();
3498			final boolean groupChat = conversation.getMode() == Conversation.MODE_MULTI;
3499			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId(), markable.getCounterpart(), groupChat);
3500			this.sendMessagePacket(conversation.getAccount(), packet);
3501		}
3502	}
3503
3504	public SecureRandom getRNG() {
3505		return this.mRandom;
3506	}
3507
3508	public MemorizingTrustManager getMemorizingTrustManager() {
3509		return this.mMemorizingTrustManager;
3510	}
3511
3512	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
3513		this.mMemorizingTrustManager = trustManager;
3514	}
3515
3516	public void updateMemorizingTrustmanager() {
3517		final MemorizingTrustManager tm;
3518		final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
3519		if (dontTrustSystemCAs) {
3520			tm = new MemorizingTrustManager(getApplicationContext(), null);
3521		} else {
3522			tm = new MemorizingTrustManager(getApplicationContext());
3523		}
3524		setMemorizingTrustManager(tm);
3525	}
3526
3527	public LruCache<String, Bitmap> getBitmapCache() {
3528		return this.mBitmapCache;
3529	}
3530
3531	public Collection<String> getKnownHosts() {
3532		final Set<String> hosts = new HashSet<>();
3533		for (final Account account : getAccounts()) {
3534			hosts.add(account.getServer());
3535			for (final Contact contact : account.getRoster().getContacts()) {
3536				if (contact.showInRoster()) {
3537					final String server = contact.getServer();
3538					if (server != null) {
3539						hosts.add(server);
3540					}
3541				}
3542			}
3543		}
3544		if (Config.QUICKSY_DOMAIN != null) {
3545		    hosts.remove(Config.QUICKSY_DOMAIN); //we only want to show this when we type a e164 number
3546        }
3547		if (Config.DOMAIN_LOCK != null) {
3548			hosts.add(Config.DOMAIN_LOCK);
3549		}
3550		if (Config.MAGIC_CREATE_DOMAIN != null) {
3551			hosts.add(Config.MAGIC_CREATE_DOMAIN);
3552		}
3553		return hosts;
3554	}
3555
3556	public Collection<String> getKnownConferenceHosts() {
3557		final Set<String> mucServers = new HashSet<>();
3558		for (final Account account : accounts) {
3559			if (account.getXmppConnection() != null) {
3560				mucServers.addAll(account.getXmppConnection().getMucServers());
3561				for (Bookmark bookmark : account.getBookmarks()) {
3562					final Jid jid = bookmark.getJid();
3563					final String s = jid == null ? null : jid.getDomain();
3564					if (s != null) {
3565						mucServers.add(s);
3566					}
3567				}
3568			}
3569		}
3570		return mucServers;
3571	}
3572
3573	public void sendMessagePacket(Account account, MessagePacket packet) {
3574		XmppConnection connection = account.getXmppConnection();
3575		if (connection != null) {
3576			connection.sendMessagePacket(packet);
3577		}
3578	}
3579
3580	public void sendPresencePacket(Account account, PresencePacket packet) {
3581		XmppConnection connection = account.getXmppConnection();
3582		if (connection != null) {
3583			connection.sendPresencePacket(packet);
3584		}
3585	}
3586
3587	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3588		final XmppConnection connection = account.getXmppConnection();
3589		if (connection != null) {
3590			IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3591			connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
3592		}
3593	}
3594
3595	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3596		final XmppConnection connection = account.getXmppConnection();
3597		if (connection != null) {
3598			connection.sendIqPacket(packet, callback);
3599		} else if (callback != null) {
3600		    callback.onIqPacketReceived(account,new IqPacket(IqPacket.TYPE.TIMEOUT));
3601        }
3602	}
3603
3604	public void sendPresence(final Account account) {
3605		sendPresence(account, checkListeners() && broadcastLastActivity());
3606	}
3607
3608	private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3609		Presence.Status status;
3610		if (manuallyChangePresence()) {
3611			status = account.getPresenceStatus();
3612		} else {
3613			status = getTargetPresence();
3614		}
3615		PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
3616		String message = account.getPresenceStatusMessage();
3617		if (message != null && !message.isEmpty()) {
3618			packet.addChild(new Element("status").setContent(message));
3619		}
3620		if (mLastActivity > 0 && includeIdleTimestamp) {
3621			long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3622			packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
3623		}
3624		sendPresencePacket(account, packet);
3625	}
3626
3627	private void deactivateGracePeriod() {
3628		for (Account account : getAccounts()) {
3629			account.deactivateGracePeriod();
3630		}
3631	}
3632
3633	public void refreshAllPresences() {
3634		boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3635		for (Account account : getAccounts()) {
3636			if (account.isEnabled()) {
3637				sendPresence(account, includeIdleTimestamp);
3638			}
3639		}
3640	}
3641
3642	private void refreshAllFcmTokens() {
3643		for (Account account : getAccounts()) {
3644			if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3645				mPushManagementService.registerPushTokenOnServer(account);
3646			}
3647		}
3648	}
3649
3650	private void sendOfflinePresence(final Account account) {
3651		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
3652		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3653	}
3654
3655	public MessageGenerator getMessageGenerator() {
3656		return this.mMessageGenerator;
3657	}
3658
3659	public PresenceGenerator getPresenceGenerator() {
3660		return this.mPresenceGenerator;
3661	}
3662
3663	public IqGenerator getIqGenerator() {
3664		return this.mIqGenerator;
3665	}
3666
3667	public IqParser getIqParser() {
3668		return this.mIqParser;
3669	}
3670
3671	public JingleConnectionManager getJingleConnectionManager() {
3672		return this.mJingleConnectionManager;
3673	}
3674
3675	public MessageArchiveService getMessageArchiveService() {
3676		return this.mMessageArchiveService;
3677	}
3678
3679	public QuickConversationsService getQuickConversationsService() {
3680        return this.mQuickConversationsService;
3681    }
3682
3683	public List<Contact> findContacts(Jid jid, String accountJid) {
3684		ArrayList<Contact> contacts = new ArrayList<>();
3685		for (Account account : getAccounts()) {
3686			if ((account.isEnabled() || accountJid != null)
3687					&& (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
3688				Contact contact = account.getRoster().getContactFromRoster(jid);
3689				if (contact != null) {
3690					contacts.add(contact);
3691				}
3692			}
3693		}
3694		return contacts;
3695	}
3696
3697	public Conversation findFirstMuc(Jid jid) {
3698		for (Conversation conversation : getConversations()) {
3699			if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
3700				return conversation;
3701			}
3702		}
3703		return null;
3704	}
3705
3706	public NotificationService getNotificationService() {
3707		return this.mNotificationService;
3708	}
3709
3710	public HttpConnectionManager getHttpConnectionManager() {
3711		return this.mHttpConnectionManager;
3712	}
3713
3714	public void resendFailedMessages(final Message message) {
3715		final Collection<Message> messages = new ArrayList<>();
3716		Message current = message;
3717		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3718			messages.add(current);
3719			if (current.mergeable(current.next())) {
3720				current = current.next();
3721			} else {
3722				break;
3723			}
3724		}
3725		for (final Message msg : messages) {
3726			msg.setTime(System.currentTimeMillis());
3727			markMessage(msg, Message.STATUS_WAITING);
3728			this.resendMessage(msg, false);
3729		}
3730		if (message.getConversation() instanceof Conversation) {
3731			((Conversation) message.getConversation()).sort();
3732		}
3733		updateConversationUi();
3734	}
3735
3736	public void clearConversationHistory(final Conversation conversation) {
3737		final long clearDate;
3738		final String reference;
3739		if (conversation.countMessages() > 0) {
3740			Message latestMessage = conversation.getLatestMessage();
3741			clearDate = latestMessage.getTimeSent() + 1000;
3742			reference = latestMessage.getServerMsgId();
3743		} else {
3744			clearDate = System.currentTimeMillis();
3745			reference = null;
3746		}
3747		conversation.clearMessages();
3748		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3749		conversation.setLastClearHistory(clearDate, reference);
3750		Runnable runnable = () -> {
3751			databaseBackend.deleteMessagesInConversation(conversation);
3752			databaseBackend.updateConversation(conversation);
3753		};
3754		mDatabaseWriterExecutor.execute(runnable);
3755	}
3756
3757	public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
3758		if (blockable != null && blockable.getBlockedJid() != null) {
3759			final Jid jid = blockable.getBlockedJid();
3760			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), new OnIqPacketReceived() {
3761
3762				@Override
3763				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3764					if (packet.getType() == IqPacket.TYPE.RESULT) {
3765						account.getBlocklist().add(jid);
3766						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3767					}
3768				}
3769			});
3770			if (removeBlockedConversations(blockable.getAccount(), jid)) {
3771				updateConversationUi();
3772				return true;
3773			} else {
3774				return false;
3775			}
3776		} else {
3777			return false;
3778		}
3779	}
3780
3781	public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
3782		boolean removed = false;
3783		synchronized (this.conversations) {
3784			boolean domainJid = blockedJid.getLocal() == null;
3785			for (Conversation conversation : this.conversations) {
3786				boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
3787						|| blockedJid.equals(conversation.getJid().asBareJid());
3788				if (conversation.getAccount() == account
3789						&& conversation.getMode() == Conversation.MODE_SINGLE
3790						&& jidMatches) {
3791					this.conversations.remove(conversation);
3792					markRead(conversation);
3793					conversation.setStatus(Conversation.STATUS_ARCHIVED);
3794					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
3795					updateConversation(conversation);
3796					removed = true;
3797				}
3798			}
3799		}
3800		return removed;
3801	}
3802
3803	public void sendUnblockRequest(final Blockable blockable) {
3804		if (blockable != null && blockable.getJid() != null) {
3805			final Jid jid = blockable.getBlockedJid();
3806			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3807				@Override
3808				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3809					if (packet.getType() == IqPacket.TYPE.RESULT) {
3810						account.getBlocklist().remove(jid);
3811						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3812					}
3813				}
3814			});
3815		}
3816	}
3817
3818	public void publishDisplayName(Account account) {
3819		String displayName = account.getDisplayName();
3820		if (displayName != null && !displayName.isEmpty()) {
3821			IqPacket publish = mIqGenerator.publishNick(displayName);
3822			sendIqPacket(account, publish, (account1, packet) -> {
3823				if (packet.getType() == IqPacket.TYPE.ERROR) {
3824					Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": could not publish nick");
3825				}
3826			});
3827		}
3828	}
3829
3830	public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
3831		ServiceDiscoveryResult result = discoCache.get(key);
3832		if (result != null) {
3833			return result;
3834		} else {
3835			result = databaseBackend.findDiscoveryResult(key.first, key.second);
3836			if (result != null) {
3837				discoCache.put(key, result);
3838			}
3839			return result;
3840		}
3841	}
3842
3843	public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3844		final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
3845		ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3846		if (disco != null) {
3847			presence.setServiceDiscoveryResult(disco);
3848		} else {
3849			if (!account.inProgressDiscoFetches.contains(key)) {
3850				account.inProgressDiscoFetches.add(key);
3851				IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3852				request.setTo(jid);
3853				final String node = presence.getNode();
3854				final String ver = presence.getVer();
3855				final Element query = request.query("http://jabber.org/protocol/disco#info");
3856				if (node != null && ver != null) {
3857					query.setAttribute("node",node+"#"+ver);
3858				}
3859				Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
3860				sendIqPacket(account, request, (a, response) -> {
3861					if (response.getType() == IqPacket.TYPE.RESULT) {
3862						ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
3863						if (presence.getVer().equals(discoveryResult.getVer())) {
3864							databaseBackend.insertDiscoveryResult(discoveryResult);
3865							injectServiceDiscoveryResult(a.getRoster(), presence.getHash(), presence.getVer(), discoveryResult);
3866						} else {
3867							Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
3868						}
3869					}
3870					a.inProgressDiscoFetches.remove(key);
3871				});
3872			}
3873		}
3874	}
3875
3876	private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3877		for (Contact contact : roster.getContacts()) {
3878			for (Presence presence : contact.getPresences().getPresences().values()) {
3879				if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3880					presence.setServiceDiscoveryResult(disco);
3881				}
3882			}
3883		}
3884	}
3885
3886	public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3887		final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
3888		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3889		request.addChild("prefs", version.namespace);
3890		sendIqPacket(account, request, (account1, packet) -> {
3891			Element prefs = packet.findChild("prefs", version.namespace);
3892			if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3893				callback.onPreferencesFetched(prefs);
3894			} else {
3895				callback.onPreferencesFetchFailed();
3896			}
3897		});
3898	}
3899
3900	public PushManagementService getPushManagementService() {
3901		return mPushManagementService;
3902	}
3903
3904	public void changeStatus(Account account, PresenceTemplate template, String signature) {
3905		if (!template.getStatusMessage().isEmpty()) {
3906			databaseBackend.insertPresenceTemplate(template);
3907		}
3908		account.setPgpSignature(signature);
3909		account.setPresenceStatus(template.getStatus());
3910		account.setPresenceStatusMessage(template.getStatusMessage());
3911		databaseBackend.updateAccount(account);
3912		sendPresence(account);
3913	}
3914
3915	public List<PresenceTemplate> getPresenceTemplates(Account account) {
3916		List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3917		for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3918			if (!templates.contains(template)) {
3919				templates.add(0, template);
3920			}
3921		}
3922		return templates;
3923	}
3924
3925	public void saveConversationAsBookmark(Conversation conversation, String name) {
3926		Account account = conversation.getAccount();
3927		Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
3928		if (!conversation.getJid().isBareJid()) {
3929			bookmark.setNick(conversation.getJid().getResource());
3930		}
3931		if (!TextUtils.isEmpty(name)) {
3932			bookmark.setBookmarkName(name);
3933		}
3934		bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
3935		account.getBookmarks().add(bookmark);
3936		pushBookmarks(account);
3937		bookmark.setConversation(conversation);
3938	}
3939
3940	public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
3941		boolean performedVerification = false;
3942		final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
3943		for (XmppUri.Fingerprint fp : fingerprints) {
3944			if (fp.type == XmppUri.FingerprintType.OMEMO) {
3945				String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
3946				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3947				if (fingerprintStatus != null) {
3948					if (!fingerprintStatus.isVerified()) {
3949						performedVerification = true;
3950						axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
3951					}
3952				} else {
3953					axolotlService.preVerifyFingerprint(contact, fingerprint);
3954				}
3955			}
3956		}
3957		return performedVerification;
3958	}
3959
3960	public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
3961		final AxolotlService axolotlService = account.getAxolotlService();
3962		boolean verifiedSomething = false;
3963		for (XmppUri.Fingerprint fp : fingerprints) {
3964			if (fp.type == XmppUri.FingerprintType.OMEMO) {
3965				String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
3966				Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
3967				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3968				if (fingerprintStatus != null) {
3969					if (!fingerprintStatus.isVerified()) {
3970						axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
3971						verifiedSomething = true;
3972					}
3973				} else {
3974					axolotlService.preVerifyFingerprint(account, fingerprint);
3975					verifiedSomething = true;
3976				}
3977			}
3978		}
3979		return verifiedSomething;
3980	}
3981
3982	public boolean blindTrustBeforeVerification() {
3983		return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
3984	}
3985
3986	public ShortcutService getShortcutService() {
3987		return mShortcutService;
3988	}
3989
3990	public void pushMamPreferences(Account account, Element prefs) {
3991		IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3992		set.addChild(prefs);
3993		sendIqPacket(account, set, null);
3994	}
3995
3996	public interface OnMamPreferencesFetched {
3997		void onPreferencesFetched(Element prefs);
3998
3999		void onPreferencesFetchFailed();
4000	}
4001
4002	public interface OnAccountCreated {
4003		void onAccountCreated(Account account);
4004
4005		void informUser(int r);
4006	}
4007
4008	public interface OnMoreMessagesLoaded {
4009		void onMoreMessagesLoaded(int count, Conversation conversation);
4010
4011		void informUser(int r);
4012	}
4013
4014	public interface OnAccountPasswordChanged {
4015		void onPasswordChangeSucceeded();
4016
4017		void onPasswordChangeFailed();
4018	}
4019
4020	public interface OnAffiliationChanged {
4021		void onAffiliationChangedSuccessful(Jid jid);
4022
4023		void onAffiliationChangeFailed(Jid jid, int resId);
4024	}
4025
4026	public interface OnRoleChanged {
4027		void onRoleChangedSuccessful(String nick);
4028
4029		void onRoleChangeFailed(String nick, int resid);
4030	}
4031
4032	public interface OnConversationUpdate {
4033		void onConversationUpdate();
4034	}
4035
4036	public interface OnAccountUpdate {
4037		void onAccountUpdate();
4038	}
4039
4040	public interface OnCaptchaRequested {
4041		void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
4042	}
4043
4044	public interface OnRosterUpdate {
4045		void onRosterUpdate();
4046	}
4047
4048	public interface OnMucRosterUpdate {
4049		void onMucRosterUpdate();
4050	}
4051
4052	public interface OnConferenceConfigurationFetched {
4053		void onConferenceConfigurationFetched(Conversation conversation);
4054
4055		void onFetchFailed(Conversation conversation, Element error);
4056	}
4057
4058	public interface OnConferenceJoined {
4059		void onConferenceJoined(Conversation conversation);
4060	}
4061
4062	public interface OnConfigurationPushed {
4063		void onPushSucceeded();
4064
4065		void onPushFailed();
4066	}
4067
4068	public interface OnShowErrorToast {
4069		void onShowErrorToast(int resId);
4070	}
4071
4072	public class XmppConnectionBinder extends Binder {
4073		public XmppConnectionService getService() {
4074			return XmppConnectionService.this;
4075		}
4076	}
4077
4078	private class InternalEventReceiver extends BroadcastReceiver {
4079
4080        @Override
4081        public void onReceive(Context context, Intent intent) {
4082            onStartCommand(intent,0,0);
4083        }
4084    }
4085}