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