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