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