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