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