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