XmppConnectionService.java

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