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