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