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				final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
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 (omemoEnabled
2194										&& isNew
2195										&& user.getRealJid() != null
2196										&& (contact == null || !contact.mutualPresenceSubscription())
2197										&& axolotlService.hasEmptyDeviceList(user.getRealJid())) {
2198									axolotlService.fetchDeviceIds(user.getRealJid());
2199								}
2200							}
2201						}
2202					}
2203				} else {
2204					success = false;
2205					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
2206				}
2207				++i;
2208				if (i >= affiliations.length) {
2209					List<Jid> members = conversation.getMucOptions().getMembers();
2210					if (success) {
2211						List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
2212						boolean changed = false;
2213						for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
2214							Jid jid = iterator.next();
2215							if (!members.contains(jid)) {
2216								iterator.remove();
2217								Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
2218								changed = true;
2219							}
2220						}
2221						if (changed) {
2222							conversation.setAcceptedCryptoTargets(cryptoTargets);
2223							updateConversation(conversation);
2224						}
2225					}
2226					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": retrieved members for " + conversation.getJid().asBareJid() + ": " + conversation.getMucOptions().getMembers());
2227					getAvatarService().clear(conversation);
2228					updateMucRosterUi();
2229					updateConversationUi();
2230				}
2231			}
2232		};
2233		for (String affiliation : affiliations) {
2234			sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2235		}
2236		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
2237	}
2238
2239	public void providePasswordForMuc(Conversation conversation, String password) {
2240		if (conversation.getMode() == Conversation.MODE_MULTI) {
2241			conversation.getMucOptions().setPassword(password);
2242			if (conversation.getBookmark() != null) {
2243				if (respectAutojoin()) {
2244					conversation.getBookmark().setAutojoin(true);
2245				}
2246				pushBookmarks(conversation.getAccount());
2247			}
2248			updateConversation(conversation);
2249			joinMuc(conversation);
2250		}
2251	}
2252
2253	private boolean hasEnabledAccounts() {
2254		for (Account account : this.accounts) {
2255			if (account.isEnabled()) {
2256				return true;
2257			}
2258		}
2259		return false;
2260	}
2261
2262	public void persistSelfNick(MucOptions.User self) {
2263		final Conversation conversation = self.getConversation();
2264		Jid full = self.getFullJid();
2265		if (!full.equals(conversation.getJid())) {
2266			Log.d(Config.LOGTAG, "nick changed. updating");
2267			conversation.setContactJid(full);
2268			databaseBackend.updateConversation(conversation);
2269		}
2270
2271		Bookmark bookmark = conversation.getBookmark();
2272		if (bookmark != null && !full.getResource().equals(bookmark.getNick())) {
2273			bookmark.setNick(full.getResource());
2274			pushBookmarks(bookmark.getAccount());
2275		}
2276	}
2277
2278	public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2279		final MucOptions options = conversation.getMucOptions();
2280		final Jid joinJid = options.createJoinJid(nick);
2281		if (joinJid == null) {
2282			return false;
2283		}
2284		if (options.online()) {
2285			Account account = conversation.getAccount();
2286			options.setOnRenameListener(new OnRenameListener() {
2287
2288				@Override
2289				public void onSuccess() {
2290					callback.success(conversation);
2291				}
2292
2293				@Override
2294				public void onFailure() {
2295					callback.error(R.string.nick_in_use, conversation);
2296				}
2297			});
2298
2299			PresencePacket packet = new PresencePacket();
2300			packet.setTo(joinJid);
2301			packet.setFrom(conversation.getAccount().getJid());
2302
2303			String sig = account.getPgpSignature();
2304			if (sig != null) {
2305				packet.addChild("status").setContent("online");
2306				packet.addChild("x", "jabber:x:signed").setContent(sig);
2307			}
2308			sendPresencePacket(account, packet);
2309		} else {
2310			conversation.setContactJid(joinJid);
2311			databaseBackend.updateConversation(conversation);
2312			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2313				Bookmark bookmark = conversation.getBookmark();
2314				if (bookmark != null) {
2315					bookmark.setNick(nick);
2316					pushBookmarks(bookmark.getAccount());
2317				}
2318				joinMuc(conversation);
2319			}
2320		}
2321		return true;
2322	}
2323
2324	public void leaveMuc(Conversation conversation) {
2325		leaveMuc(conversation, false);
2326	}
2327
2328	private void leaveMuc(Conversation conversation, boolean now) {
2329		Account account = conversation.getAccount();
2330		account.pendingConferenceJoins.remove(conversation);
2331		account.pendingConferenceLeaves.remove(conversation);
2332		if (account.getStatus() == Account.State.ONLINE || now) {
2333			sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
2334			conversation.getMucOptions().setOffline();
2335			Bookmark bookmark = conversation.getBookmark();
2336			if (bookmark != null) {
2337				bookmark.setConversation(null);
2338			}
2339			Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
2340		} else {
2341			account.pendingConferenceLeaves.add(conversation);
2342		}
2343	}
2344
2345	public String findConferenceServer(final Account account) {
2346		String server;
2347		if (account.getXmppConnection() != null) {
2348			server = account.getXmppConnection().getMucServer();
2349			if (server != null) {
2350				return server;
2351			}
2352		}
2353		for (Account other : getAccounts()) {
2354			if (other != account && other.getXmppConnection() != null) {
2355				server = other.getXmppConnection().getMucServer();
2356				if (server != null) {
2357					return server;
2358				}
2359			}
2360		}
2361		return null;
2362	}
2363
2364	public boolean createAdhocConference(final Account account,
2365	                                     final String subject,
2366	                                     final Iterable<Jid> jids,
2367	                                     final UiCallback<Conversation> callback) {
2368		Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2369		if (account.getStatus() == Account.State.ONLINE) {
2370			try {
2371				String server = findConferenceServer(account);
2372				if (server == null) {
2373					if (callback != null) {
2374						callback.error(R.string.no_conference_server_found, null);
2375					}
2376					return false;
2377				}
2378				final Jid jid = Jid.of(new BigInteger(64, getRNG()).toString(Character.MAX_RADIX), server, null);
2379				final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
2380				joinMuc(conversation, new OnConferenceJoined() {
2381					@Override
2382					public void onConferenceJoined(final Conversation conversation) {
2383						pushConferenceConfiguration(conversation, IqGenerator.defaultRoomConfiguration(), new OnConfigurationPushed() {
2384							@Override
2385							public void onPushSucceeded() {
2386								if (subject != null && !subject.trim().isEmpty()) {
2387									pushSubjectToConference(conversation, subject.trim());
2388								}
2389								for (Jid invite : jids) {
2390									invite(conversation, invite);
2391								}
2392								if (account.countPresences() > 1) {
2393									directInvite(conversation, account.getJid().asBareJid());
2394								}
2395								saveConversationAsBookmark(conversation, subject);
2396								if (callback != null) {
2397									callback.success(conversation);
2398								}
2399							}
2400
2401							@Override
2402							public void onPushFailed() {
2403								archiveConversation(conversation);
2404								if (callback != null) {
2405									callback.error(R.string.conference_creation_failed, conversation);
2406								}
2407							}
2408						});
2409					}
2410				});
2411				return true;
2412			} catch (IllegalArgumentException e) {
2413				if (callback != null) {
2414					callback.error(R.string.conference_creation_failed, null);
2415				}
2416				return false;
2417			}
2418		} else {
2419			if (callback != null) {
2420				callback.error(R.string.not_connected_try_again, null);
2421			}
2422			return false;
2423		}
2424	}
2425
2426	public void fetchConferenceConfiguration(final Conversation conversation) {
2427		fetchConferenceConfiguration(conversation, null);
2428	}
2429
2430	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2431		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2432		request.setTo(conversation.getJid().asBareJid());
2433		request.query("http://jabber.org/protocol/disco#info");
2434		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2435			@Override
2436			public void onIqPacketReceived(Account account, IqPacket packet) {
2437				Element query = packet.findChild("query", "http://jabber.org/protocol/disco#info");
2438				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2439					ArrayList<String> features = new ArrayList<>();
2440					for (Element child : query.getChildren()) {
2441						if (child != null && child.getName().equals("feature")) {
2442							String var = child.getAttribute("var");
2443							if (var != null) {
2444								features.add(var);
2445							}
2446						}
2447					}
2448					Element form = query.findChild("x", Namespace.DATA);
2449					Data data = form == null ? null : Data.parse(form);
2450					if (conversation.getMucOptions().updateConfiguration(features, data)) {
2451						Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
2452						updateConversation(conversation);
2453					}
2454					if (callback != null) {
2455						callback.onConferenceConfigurationFetched(conversation);
2456					}
2457					updateConversationUi();
2458				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
2459					if (callback != null) {
2460						callback.onFetchFailed(conversation, packet.getError());
2461					}
2462				}
2463			}
2464		});
2465	}
2466
2467	public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
2468		pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
2469	}
2470
2471	public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
2472		sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
2473			@Override
2474			public void onIqPacketReceived(Account account, IqPacket packet) {
2475				if (packet.getType() == IqPacket.TYPE.RESULT) {
2476					Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
2477					Element configuration = pubsub == null ? null : pubsub.findChild("configure");
2478					Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
2479					if (x != null) {
2480						Data data = Data.parse(x);
2481						data.submit(options);
2482						sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
2483							@Override
2484							public void onIqPacketReceived(Account account, IqPacket packet) {
2485								if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
2486									Log.d(Config.LOGTAG,account.getJid().asBareJid()+": successfully changed node configuration for node "+node);
2487									callback.onPushSucceeded();
2488								} else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
2489									callback.onPushFailed();
2490								}
2491							}
2492						});
2493					} else if (callback != null) {
2494						callback.onPushFailed();
2495					}
2496				} else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
2497					callback.onPushFailed();
2498				}
2499			}
2500		});
2501	}
2502
2503	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
2504		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2505		request.setTo(conversation.getJid().asBareJid());
2506		request.query("http://jabber.org/protocol/muc#owner");
2507		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2508			@Override
2509			public void onIqPacketReceived(Account account, IqPacket packet) {
2510				if (packet.getType() == IqPacket.TYPE.RESULT) {
2511					Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
2512					data.submit(options);
2513					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2514					set.setTo(conversation.getJid().asBareJid());
2515					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2516					sendIqPacket(account, set, new OnIqPacketReceived() {
2517						@Override
2518						public void onIqPacketReceived(Account account, IqPacket packet) {
2519							if (callback != null) {
2520								if (packet.getType() == IqPacket.TYPE.RESULT) {
2521									callback.onPushSucceeded();
2522								} else {
2523									callback.onPushFailed();
2524								}
2525							}
2526						}
2527					});
2528				} else {
2529					if (callback != null) {
2530						callback.onPushFailed();
2531					}
2532				}
2533			}
2534		});
2535	}
2536
2537	public void pushSubjectToConference(final Conversation conference, final String subject) {
2538		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2539		this.sendMessagePacket(conference.getAccount(), packet);
2540		final MucOptions mucOptions = conference.getMucOptions();
2541		final MucOptions.User self = mucOptions.getSelf();
2542		if (self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2543			Bundle options = new Bundle();
2544			options.putString("muc#roomconfig_persistentroom", "1");
2545			options.putString("muc#roomconfig_roomname", subject);
2546			this.pushConferenceConfiguration(conference, options, null);
2547		}
2548	}
2549
2550	public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2551		final Jid jid = user.asBareJid();
2552		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2553		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2554			@Override
2555			public void onIqPacketReceived(Account account, IqPacket packet) {
2556				if (packet.getType() == IqPacket.TYPE.RESULT) {
2557					conference.getMucOptions().changeAffiliation(jid, affiliation);
2558					getAvatarService().clear(conference);
2559					callback.onAffiliationChangedSuccessful(jid);
2560				} else {
2561					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2562				}
2563			}
2564		});
2565	}
2566
2567	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2568		List<Jid> jids = new ArrayList<>();
2569		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2570			if (user.getAffiliation() == before && user.getRealJid() != null) {
2571				jids.add(user.getRealJid());
2572			}
2573		}
2574		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2575		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2576	}
2577
2578	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2579		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2580		Log.d(Config.LOGTAG, request.toString());
2581		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2582			@Override
2583			public void onIqPacketReceived(Account account, IqPacket packet) {
2584				Log.d(Config.LOGTAG, packet.toString());
2585				if (packet.getType() == IqPacket.TYPE.RESULT) {
2586					callback.onRoleChangedSuccessful(nick);
2587				} else {
2588					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2589				}
2590			}
2591		});
2592	}
2593
2594	private void disconnect(Account account, boolean force) {
2595		if ((account.getStatus() == Account.State.ONLINE)
2596				|| (account.getStatus() == Account.State.DISABLED)) {
2597			final XmppConnection connection = account.getXmppConnection();
2598			if (!force) {
2599				List<Conversation> conversations = getConversations();
2600				for (Conversation conversation : conversations) {
2601					if (conversation.getAccount() == account) {
2602						if (conversation.getMode() == Conversation.MODE_MULTI) {
2603							leaveMuc(conversation, true);
2604						}
2605					}
2606				}
2607				sendOfflinePresence(account);
2608			}
2609			connection.disconnect(force);
2610		}
2611	}
2612
2613	@Override
2614	public IBinder onBind(Intent intent) {
2615		return mBinder;
2616	}
2617
2618	public void updateMessage(Message message) {
2619		updateMessage(message, true);
2620	}
2621
2622	public void updateMessage(Message message, boolean includeBody) {
2623		databaseBackend.updateMessage(message, includeBody);
2624		updateConversationUi();
2625	}
2626
2627	public void updateMessage(Message message, String uuid) {
2628		databaseBackend.updateMessage(message, uuid);
2629		updateConversationUi();
2630	}
2631
2632	protected void syncDirtyContacts(Account account) {
2633		for (Contact contact : account.getRoster().getContacts()) {
2634			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2635				pushContactToServer(contact);
2636			}
2637			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2638				deleteContactOnServer(contact);
2639			}
2640		}
2641	}
2642
2643	public void createContact(Contact contact, boolean autoGrant) {
2644		if (autoGrant) {
2645			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2646			contact.setOption(Contact.Options.ASKING);
2647		}
2648		pushContactToServer(contact);
2649	}
2650
2651	public void pushContactToServer(final Contact contact) {
2652		contact.resetOption(Contact.Options.DIRTY_DELETE);
2653		contact.setOption(Contact.Options.DIRTY_PUSH);
2654		final Account account = contact.getAccount();
2655		if (account.getStatus() == Account.State.ONLINE) {
2656			final boolean ask = contact.getOption(Contact.Options.ASKING);
2657			final boolean sendUpdates = contact
2658					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2659					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2660			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2661			iq.query(Namespace.ROSTER).addChild(contact.asElement());
2662			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2663			if (sendUpdates) {
2664				sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
2665			}
2666			if (ask) {
2667				sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2668			}
2669		} else {
2670			syncRoster(contact.getAccount());
2671		}
2672	}
2673
2674	public void publishAvatar(final Account account, final Uri image, final UiCallback<Avatar> callback) {
2675		new Thread(() -> {
2676			final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2677			final int size = Config.AVATAR_SIZE;
2678			final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2679			if (avatar != null) {
2680				if (!getFileBackend().save(avatar)) {
2681					callback.error(R.string.error_saving_avatar, avatar);
2682					return;
2683				}
2684				publishAvatar(account, avatar, callback);
2685			} else {
2686				callback.error(R.string.error_publish_avatar_converting, null);
2687			}
2688		}).start();
2689
2690	}
2691
2692	public void publishAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2693		IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2694		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2695
2696			@Override
2697			public void onIqPacketReceived(Account account, IqPacket result) {
2698				if (result.getType() == IqPacket.TYPE.RESULT) {
2699					final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar);
2700					sendIqPacket(account, packet, new OnIqPacketReceived() {
2701						@Override
2702						public void onIqPacketReceived(Account account, IqPacket result) {
2703							if (result.getType() == IqPacket.TYPE.RESULT) {
2704								if (account.setAvatar(avatar.getFilename())) {
2705									getAvatarService().clear(account);
2706									databaseBackend.updateAccount(account);
2707								}
2708								Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
2709								if (callback != null) {
2710									callback.success(avatar);
2711								}
2712							} else {
2713								if (callback != null) {
2714									callback.error(R.string.error_publish_avatar_server_reject, avatar);
2715								}
2716							}
2717						}
2718					});
2719				} else {
2720					Element error = result.findChild("error");
2721					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
2722					if (callback != null) {
2723						callback.error(R.string.error_publish_avatar_server_reject, avatar);
2724					}
2725				}
2726			}
2727		});
2728	}
2729
2730	public void republishAvatarIfNeeded(Account account) {
2731		if (account.getAxolotlService().isPepBroken()) {
2732			Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
2733			return;
2734		}
2735		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2736		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2737
2738			private Avatar parseAvatar(IqPacket packet) {
2739				Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2740				if (pubsub != null) {
2741					Element items = pubsub.findChild("items");
2742					if (items != null) {
2743						return Avatar.parseMetadata(items);
2744					}
2745				}
2746				return null;
2747			}
2748
2749			private boolean errorIsItemNotFound(IqPacket packet) {
2750				Element error = packet.findChild("error");
2751				return packet.getType() == IqPacket.TYPE.ERROR
2752						&& error != null
2753						&& error.hasChild("item-not-found");
2754			}
2755
2756			@Override
2757			public void onIqPacketReceived(Account account, IqPacket packet) {
2758				if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2759					Avatar serverAvatar = parseAvatar(packet);
2760					if (serverAvatar == null && account.getAvatar() != null) {
2761						Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2762						if (avatar != null) {
2763							Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
2764							publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2765						} else {
2766							Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
2767						}
2768					}
2769				}
2770			}
2771		});
2772	}
2773
2774	public void fetchAvatar(Account account, Avatar avatar) {
2775		fetchAvatar(account, avatar, null);
2776	}
2777
2778	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2779		final String KEY = generateFetchKey(account, avatar);
2780		synchronized (this.mInProgressAvatarFetches) {
2781			if (!this.mInProgressAvatarFetches.contains(KEY)) {
2782				switch (avatar.origin) {
2783					case PEP:
2784						this.mInProgressAvatarFetches.add(KEY);
2785						fetchAvatarPep(account, avatar, callback);
2786						break;
2787					case VCARD:
2788						this.mInProgressAvatarFetches.add(KEY);
2789						fetchAvatarVcard(account, avatar, callback);
2790						break;
2791				}
2792			}
2793		}
2794	}
2795
2796	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2797		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2798		sendIqPacket(account, packet, (a, result) -> {
2799			synchronized (mInProgressAvatarFetches) {
2800				mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
2801			}
2802			final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
2803			if (result.getType() == IqPacket.TYPE.RESULT) {
2804				avatar.image = mIqParser.avatarData(result);
2805				if (avatar.image != null) {
2806					if (getFileBackend().save(avatar)) {
2807						if (a.getJid().asBareJid().equals(avatar.owner)) {
2808							if (a.setAvatar(avatar.getFilename())) {
2809								databaseBackend.updateAccount(a);
2810							}
2811							getAvatarService().clear(a);
2812							updateConversationUi();
2813							updateAccountUi();
2814						} else {
2815							Contact contact = a.getRoster().getContact(avatar.owner);
2816							contact.setAvatar(avatar);
2817							getAvatarService().clear(contact);
2818							updateConversationUi();
2819							updateRosterUi();
2820						}
2821						if (callback != null) {
2822							callback.success(avatar);
2823						}
2824						Log.d(Config.LOGTAG, a.getJid().asBareJid()
2825								+ ": successfully fetched pep avatar for " + avatar.owner);
2826						return;
2827					}
2828				} else {
2829
2830					Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2831				}
2832			} else {
2833				Element error = result.findChild("error");
2834				if (error == null) {
2835					Log.d(Config.LOGTAG, ERROR + "(server error)");
2836				} else {
2837					Log.d(Config.LOGTAG, ERROR + error.toString());
2838				}
2839			}
2840			if (callback != null) {
2841				callback.error(0, null);
2842			}
2843
2844		});
2845	}
2846
2847	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2848		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2849		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2850			@Override
2851			public void onIqPacketReceived(Account account, IqPacket packet) {
2852				synchronized (mInProgressAvatarFetches) {
2853					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2854				}
2855				if (packet.getType() == IqPacket.TYPE.RESULT) {
2856					Element vCard = packet.findChild("vCard", "vcard-temp");
2857					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2858					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2859					if (image != null) {
2860						avatar.image = image;
2861						if (getFileBackend().save(avatar)) {
2862							Log.d(Config.LOGTAG, account.getJid().asBareJid()
2863									+ ": successfully fetched vCard avatar for " + avatar.owner);
2864							if (avatar.owner.isBareJid()) {
2865								if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
2866									Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
2867									account.setAvatar(avatar.getFilename());
2868									databaseBackend.updateAccount(account);
2869									getAvatarService().clear(account);
2870									updateAccountUi();
2871								} else {
2872									Contact contact = account.getRoster().getContact(avatar.owner);
2873									contact.setAvatar(avatar);
2874									getAvatarService().clear(contact);
2875									updateRosterUi();
2876								}
2877								updateConversationUi();
2878							} else {
2879								Conversation conversation = find(account, avatar.owner.asBareJid());
2880								if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
2881									MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
2882									if (user != null) {
2883										if (user.setAvatar(avatar)) {
2884											getAvatarService().clear(user);
2885											updateConversationUi();
2886											updateMucRosterUi();
2887										}
2888									}
2889								}
2890							}
2891						}
2892					}
2893				}
2894			}
2895		});
2896	}
2897
2898	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2899		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2900		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2901
2902			@Override
2903			public void onIqPacketReceived(Account account, IqPacket packet) {
2904				if (packet.getType() == IqPacket.TYPE.RESULT) {
2905					Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2906					if (pubsub != null) {
2907						Element items = pubsub.findChild("items");
2908						if (items != null) {
2909							Avatar avatar = Avatar.parseMetadata(items);
2910							if (avatar != null) {
2911								avatar.owner = account.getJid().asBareJid();
2912								if (fileBackend.isAvatarCached(avatar)) {
2913									if (account.setAvatar(avatar.getFilename())) {
2914										databaseBackend.updateAccount(account);
2915									}
2916									getAvatarService().clear(account);
2917									callback.success(avatar);
2918								} else {
2919									fetchAvatarPep(account, avatar, callback);
2920								}
2921								return;
2922							}
2923						}
2924					}
2925				}
2926				callback.error(0, null);
2927			}
2928		});
2929	}
2930
2931	public void deleteContactOnServer(Contact contact) {
2932		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2933		contact.resetOption(Contact.Options.DIRTY_PUSH);
2934		contact.setOption(Contact.Options.DIRTY_DELETE);
2935		Account account = contact.getAccount();
2936		if (account.getStatus() == Account.State.ONLINE) {
2937			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2938			Element item = iq.query(Namespace.ROSTER).addChild("item");
2939			item.setAttribute("jid", contact.getJid().toString());
2940			item.setAttribute("subscription", "remove");
2941			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2942		}
2943	}
2944
2945	public void updateConversation(final Conversation conversation) {
2946		mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
2947	}
2948
2949	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2950		synchronized (account) {
2951			XmppConnection connection = account.getXmppConnection();
2952			if (connection == null) {
2953				connection = createConnection(account);
2954				account.setXmppConnection(connection);
2955			}
2956			boolean hasInternet = hasInternetConnection();
2957			if (account.isEnabled() && hasInternet) {
2958				if (!force) {
2959					disconnect(account, false);
2960				}
2961				Thread thread = new Thread(connection);
2962				connection.setInteractive(interactive);
2963				connection.prepareNewConnection();
2964				connection.interrupt();
2965				thread.start();
2966				scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2967			} else {
2968				disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
2969				account.getRoster().clearPresences();
2970				connection.resetEverything();
2971				final AxolotlService axolotlService = account.getAxolotlService();
2972				if (axolotlService != null) {
2973					axolotlService.resetBrokenness();
2974				}
2975				if (!hasInternet) {
2976					account.setStatus(Account.State.NO_INTERNET);
2977				}
2978			}
2979		}
2980	}
2981
2982	public void reconnectAccountInBackground(final Account account) {
2983		new Thread(() -> reconnectAccount(account, false, true)).start();
2984	}
2985
2986	public void invite(Conversation conversation, Jid contact) {
2987		Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
2988		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2989		sendMessagePacket(conversation.getAccount(), packet);
2990	}
2991
2992	public void directInvite(Conversation conversation, Jid jid) {
2993		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2994		sendMessagePacket(conversation.getAccount(), packet);
2995	}
2996
2997	public void resetSendingToWaiting(Account account) {
2998		for (Conversation conversation : getConversations()) {
2999			if (conversation.getAccount() == account) {
3000				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
3001
3002					@Override
3003					public void onMessageFound(Message message) {
3004						markMessage(message, Message.STATUS_WAITING);
3005					}
3006				});
3007			}
3008		}
3009	}
3010
3011	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
3012		return markMessage(account, recipient, uuid, status, null);
3013	}
3014
3015	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
3016		if (uuid == null) {
3017			return null;
3018		}
3019		for (Conversation conversation : getConversations()) {
3020			if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
3021				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
3022				if (message != null) {
3023					markMessage(message, status, errorMessage);
3024				}
3025				return message;
3026			}
3027		}
3028		return null;
3029	}
3030
3031	public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) {
3032		if (uuid == null) {
3033			return false;
3034		} else {
3035			Message message = conversation.findSentMessageWithUuid(uuid);
3036			if (message != null) {
3037				if (message.getServerMsgId() == null) {
3038					message.setServerMsgId(serverMessageId);
3039				}
3040				markMessage(message, status);
3041				return true;
3042			} else {
3043				return false;
3044			}
3045		}
3046	}
3047
3048	public void markMessage(Message message, int status) {
3049		markMessage(message, status, null);
3050	}
3051
3052
3053	public void markMessage(Message message, int status, String errorMessage) {
3054		final int c = message.getStatus();
3055		if (status == Message.STATUS_SEND_FAILED && (c == Message.STATUS_SEND_RECEIVED || c == Message.STATUS_SEND_DISPLAYED)) {
3056			return;
3057		}
3058		if (status == Message.STATUS_SEND_RECEIVED && c == Message.STATUS_SEND_DISPLAYED) {
3059			return;
3060		}
3061		message.setErrorMessage(errorMessage);
3062		message.setStatus(status);
3063		databaseBackend.updateMessage(message, false);
3064		updateConversationUi();
3065	}
3066
3067	private SharedPreferences getPreferences() {
3068		return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
3069	}
3070
3071	public long getAutomaticMessageDeletionDate() {
3072		final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
3073		return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
3074	}
3075
3076	public long getLongPreference(String name, @IntegerRes int res) {
3077		long defaultValue = getResources().getInteger(res);
3078		try {
3079			return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
3080		} catch (NumberFormatException e) {
3081			return defaultValue;
3082		}
3083	}
3084
3085	public boolean getBooleanPreference(String name, @BoolRes int res) {
3086		return getPreferences().getBoolean(name, getResources().getBoolean(res));
3087	}
3088
3089	public boolean confirmMessages() {
3090		return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
3091	}
3092
3093	public boolean allowMessageCorrection() {
3094		return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
3095	}
3096
3097	public boolean sendChatStates() {
3098		return getBooleanPreference("chat_states", R.bool.chat_states);
3099	}
3100
3101	private boolean respectAutojoin() {
3102		return getBooleanPreference("autojoin", R.bool.autojoin);
3103	}
3104
3105	public boolean indicateReceived() {
3106		return getBooleanPreference("indicate_received", R.bool.indicate_received);
3107	}
3108
3109	public boolean useTorToConnect() {
3110		return Config.FORCE_ORBOT || getBooleanPreference("use_tor", R.bool.use_tor);
3111	}
3112
3113	public boolean showExtendedConnectionOptions() {
3114		return getBooleanPreference("show_connection_options", R.bool.show_connection_options);
3115	}
3116
3117	public boolean broadcastLastActivity() {
3118		return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
3119	}
3120
3121	public int unreadCount() {
3122		int count = 0;
3123		for (Conversation conversation : getConversations()) {
3124			count += conversation.unreadCount();
3125		}
3126		return count;
3127	}
3128
3129
3130	public void showErrorToastInUi(int resId) {
3131		for(OnShowErrorToast listener : this.mOnShowErrorToasts) {
3132			listener.onShowErrorToast(resId);
3133		}
3134	}
3135
3136	public void updateConversationUi() {
3137		for(OnConversationUpdate listener : this.mOnConversationUpdates) {
3138			listener.onConversationUpdate();
3139		}
3140	}
3141
3142	public void updateAccountUi() {
3143		for(OnAccountUpdate listener : this.mOnAccountUpdates) {
3144			listener.onAccountUpdate();
3145		}
3146	}
3147
3148	public void updateRosterUi() {
3149		for(OnRosterUpdate listener : this.mOnRosterUpdates) {
3150			listener.onRosterUpdate();
3151		}
3152	}
3153
3154	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3155		if (mOnCaptchaRequested.size() > 0) {
3156			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3157			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3158					(int) (captcha.getHeight() * metrics.scaledDensity), false);
3159			for(OnCaptchaRequested listener : this.mOnCaptchaRequested) {
3160				listener.onCaptchaRequested(account, id, data, scaled);
3161			}
3162			return true;
3163		}
3164		return false;
3165	}
3166
3167	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3168		for(OnUpdateBlocklist listener : this.mOnUpdateBlocklist) {
3169			listener.OnUpdateBlocklist(status);
3170		}
3171	}
3172
3173	public void updateMucRosterUi() {
3174		for(OnMucRosterUpdate listener : this.mOnMucRosterUpdate) {
3175			listener.onMucRosterUpdate();
3176		}
3177	}
3178
3179	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3180		for(OnKeyStatusUpdated listener : this.mOnKeyStatusUpdated) {
3181			listener.onKeyStatusUpdated(report);
3182		}
3183	}
3184
3185	public Account findAccountByJid(final Jid accountJid) {
3186		for (Account account : this.accounts) {
3187			if (account.getJid().asBareJid().equals(accountJid.asBareJid())) {
3188				return account;
3189			}
3190		}
3191		return null;
3192	}
3193
3194	public Account findAccountByUuid(final String uuid) {
3195		for(Account account : this.accounts) {
3196			if (account.getUuid().equals(uuid)) {
3197				return account;
3198			}
3199		}
3200		return null;
3201	}
3202
3203	public Conversation findConversationByUuid(String uuid) {
3204		for (Conversation conversation : getConversations()) {
3205			if (conversation.getUuid().equals(uuid)) {
3206				return conversation;
3207			}
3208		}
3209		return null;
3210	}
3211
3212	public boolean markRead(final Conversation conversation, boolean dismiss) {
3213		return markRead(conversation, null, dismiss).size() > 0;
3214	}
3215
3216	public void markRead(final Conversation conversation) {
3217		markRead(conversation, null, true);
3218	}
3219
3220	public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
3221		if (dismiss) {
3222			mNotificationService.clear(conversation);
3223		}
3224		final List<Message> readMessages = conversation.markRead(upToUuid);
3225		if (readMessages.size() > 0) {
3226			Runnable runnable = () -> {
3227				for (Message message : readMessages) {
3228					databaseBackend.updateMessage(message, false);
3229				}
3230			};
3231			mDatabaseWriterExecutor.execute(runnable);
3232			updateUnreadCountBadge();
3233			return readMessages;
3234		} else {
3235			return readMessages;
3236		}
3237	}
3238
3239	public synchronized void updateUnreadCountBadge() {
3240		int count = unreadCount();
3241		if (unreadCount != count) {
3242			Log.d(Config.LOGTAG, "update unread count to " + count);
3243			if (count > 0) {
3244				ShortcutBadger.applyCount(getApplicationContext(), count);
3245			} else {
3246				ShortcutBadger.removeCount(getApplicationContext());
3247			}
3248			unreadCount = count;
3249		}
3250	}
3251
3252	public void sendReadMarker(final Conversation conversation, String upToUuid) {
3253		final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
3254		final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
3255		if (readMessages.size() > 0) {
3256			updateConversationUi();
3257		}
3258		final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
3259		if (confirmMessages()
3260				&& markable != null
3261				&& (markable.trusted() || isPrivateAndNonAnonymousMuc)
3262				&& markable.getRemoteMsgId() != null) {
3263			Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
3264			Account account = conversation.getAccount();
3265			final Jid to = markable.getCounterpart();
3266			final boolean groupChat = conversation.getMode() == Conversation.MODE_MULTI;
3267			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId(), markable.getCounterpart(), groupChat);
3268			this.sendMessagePacket(conversation.getAccount(), packet);
3269		}
3270	}
3271
3272	public SecureRandom getRNG() {
3273		return this.mRandom;
3274	}
3275
3276	public MemorizingTrustManager getMemorizingTrustManager() {
3277		return this.mMemorizingTrustManager;
3278	}
3279
3280	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
3281		this.mMemorizingTrustManager = trustManager;
3282	}
3283
3284	public void updateMemorizingTrustmanager() {
3285		final MemorizingTrustManager tm;
3286		final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
3287		if (dontTrustSystemCAs) {
3288			tm = new MemorizingTrustManager(getApplicationContext(), null);
3289		} else {
3290			tm = new MemorizingTrustManager(getApplicationContext());
3291		}
3292		setMemorizingTrustManager(tm);
3293	}
3294
3295	public LruCache<String, Bitmap> getBitmapCache() {
3296		return this.mBitmapCache;
3297	}
3298
3299	public Collection<String> getKnownHosts() {
3300		final Set<String> hosts = new HashSet<>();
3301		for (final Account account : getAccounts()) {
3302			hosts.add(account.getServer());
3303			for (final Contact contact : account.getRoster().getContacts()) {
3304				if (contact.showInRoster()) {
3305					final String server = contact.getServer();
3306					if (server != null && !hosts.contains(server)) {
3307						hosts.add(server);
3308					}
3309				}
3310			}
3311		}
3312		if (Config.DOMAIN_LOCK != null) {
3313			hosts.add(Config.DOMAIN_LOCK);
3314		}
3315		if (Config.MAGIC_CREATE_DOMAIN != null) {
3316			hosts.add(Config.MAGIC_CREATE_DOMAIN);
3317		}
3318		return hosts;
3319	}
3320
3321	public Collection<String> getKnownConferenceHosts() {
3322		final Set<String> mucServers = new HashSet<>();
3323		for (final Account account : accounts) {
3324			if (account.getXmppConnection() != null) {
3325				mucServers.addAll(account.getXmppConnection().getMucServers());
3326				for (Bookmark bookmark : account.getBookmarks()) {
3327					final Jid jid = bookmark.getJid();
3328					final String s = jid == null ? null : jid.getDomain();
3329					if (s != null) {
3330						mucServers.add(s);
3331					}
3332				}
3333			}
3334		}
3335		return mucServers;
3336	}
3337
3338	public void sendMessagePacket(Account account, MessagePacket packet) {
3339		XmppConnection connection = account.getXmppConnection();
3340		if (connection != null) {
3341			connection.sendMessagePacket(packet);
3342		}
3343	}
3344
3345	public void sendPresencePacket(Account account, PresencePacket packet) {
3346		XmppConnection connection = account.getXmppConnection();
3347		if (connection != null) {
3348			connection.sendPresencePacket(packet);
3349		}
3350	}
3351
3352	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3353		final XmppConnection connection = account.getXmppConnection();
3354		if (connection != null) {
3355			IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3356			connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
3357		}
3358	}
3359
3360	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3361		final XmppConnection connection = account.getXmppConnection();
3362		if (connection != null) {
3363			connection.sendIqPacket(packet, callback);
3364		}
3365	}
3366
3367	public void sendPresence(final Account account) {
3368		sendPresence(account, checkListeners() && broadcastLastActivity());
3369	}
3370
3371	private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3372		Presence.Status status;
3373		if (manuallyChangePresence()) {
3374			status = account.getPresenceStatus();
3375		} else {
3376			status = getTargetPresence();
3377		}
3378		PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
3379		String message = account.getPresenceStatusMessage();
3380		if (message != null && !message.isEmpty()) {
3381			packet.addChild(new Element("status").setContent(message));
3382		}
3383		if (mLastActivity > 0 && includeIdleTimestamp) {
3384			long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3385			packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
3386		}
3387		sendPresencePacket(account, packet);
3388	}
3389
3390	private void deactivateGracePeriod() {
3391		for (Account account : getAccounts()) {
3392			account.deactivateGracePeriod();
3393		}
3394	}
3395
3396	public void refreshAllPresences() {
3397		boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3398		for (Account account : getAccounts()) {
3399			if (account.isEnabled()) {
3400				sendPresence(account, includeIdleTimestamp);
3401			}
3402		}
3403	}
3404
3405	private void refreshAllFcmTokens() {
3406		for (Account account : getAccounts()) {
3407			if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3408				mPushManagementService.registerPushTokenOnServer(account);
3409			}
3410		}
3411	}
3412
3413	private void sendOfflinePresence(final Account account) {
3414		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
3415		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3416	}
3417
3418	public MessageGenerator getMessageGenerator() {
3419		return this.mMessageGenerator;
3420	}
3421
3422	public PresenceGenerator getPresenceGenerator() {
3423		return this.mPresenceGenerator;
3424	}
3425
3426	public IqGenerator getIqGenerator() {
3427		return this.mIqGenerator;
3428	}
3429
3430	public IqParser getIqParser() {
3431		return this.mIqParser;
3432	}
3433
3434	public JingleConnectionManager getJingleConnectionManager() {
3435		return this.mJingleConnectionManager;
3436	}
3437
3438	public MessageArchiveService getMessageArchiveService() {
3439		return this.mMessageArchiveService;
3440	}
3441
3442	public List<Contact> findContacts(Jid jid, String accountJid) {
3443		ArrayList<Contact> contacts = new ArrayList<>();
3444		for (Account account : getAccounts()) {
3445			if ((account.isEnabled() || accountJid != null)
3446					&& (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
3447				Contact contact = account.getRoster().getContactFromRoster(jid);
3448				if (contact != null) {
3449					contacts.add(contact);
3450				}
3451			}
3452		}
3453		return contacts;
3454	}
3455
3456	public Conversation findFirstMuc(Jid jid) {
3457		for (Conversation conversation : getConversations()) {
3458			if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
3459				return conversation;
3460			}
3461		}
3462		return null;
3463	}
3464
3465	public NotificationService getNotificationService() {
3466		return this.mNotificationService;
3467	}
3468
3469	public HttpConnectionManager getHttpConnectionManager() {
3470		return this.mHttpConnectionManager;
3471	}
3472
3473	public void resendFailedMessages(final Message message) {
3474		final Collection<Message> messages = new ArrayList<>();
3475		Message current = message;
3476		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3477			messages.add(current);
3478			if (current.mergeable(current.next())) {
3479				current = current.next();
3480			} else {
3481				break;
3482			}
3483		}
3484		for (final Message msg : messages) {
3485			msg.setTime(System.currentTimeMillis());
3486			markMessage(msg, Message.STATUS_WAITING);
3487			this.resendMessage(msg, false);
3488		}
3489		if (message.getConversation() instanceof Conversation) {
3490			((Conversation) message.getConversation()).sort();
3491		}
3492		updateConversationUi();
3493	}
3494
3495	public void clearConversationHistory(final Conversation conversation) {
3496		final long clearDate;
3497		final String reference;
3498		if (conversation.countMessages() > 0) {
3499			Message latestMessage = conversation.getLatestMessage();
3500			clearDate = latestMessage.getTimeSent() + 1000;
3501			reference = latestMessage.getServerMsgId();
3502		} else {
3503			clearDate = System.currentTimeMillis();
3504			reference = null;
3505		}
3506		conversation.clearMessages();
3507		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3508		conversation.setLastClearHistory(clearDate, reference);
3509		Runnable runnable = () -> {
3510			databaseBackend.deleteMessagesInConversation(conversation);
3511			databaseBackend.updateConversation(conversation);
3512		};
3513		mDatabaseWriterExecutor.execute(runnable);
3514	}
3515
3516	public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
3517		if (blockable != null && blockable.getBlockedJid() != null) {
3518			final Jid jid = blockable.getBlockedJid();
3519			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), new OnIqPacketReceived() {
3520
3521				@Override
3522				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3523					if (packet.getType() == IqPacket.TYPE.RESULT) {
3524						account.getBlocklist().add(jid);
3525						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3526					}
3527				}
3528			});
3529			if (removeBlockedConversations(blockable.getAccount(), jid)) {
3530				updateConversationUi();
3531				return true;
3532			} else {
3533				return false;
3534			}
3535		} else {
3536			return false;
3537		}
3538	}
3539
3540	public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
3541		boolean removed = false;
3542		synchronized (this.conversations) {
3543			boolean domainJid = blockedJid.getLocal() == null;
3544			for (Conversation conversation : this.conversations) {
3545				boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
3546						|| blockedJid.equals(conversation.getJid().asBareJid());
3547				if (conversation.getAccount() == account
3548						&& conversation.getMode() == Conversation.MODE_SINGLE
3549						&& jidMatches) {
3550					this.conversations.remove(conversation);
3551					markRead(conversation);
3552					conversation.setStatus(Conversation.STATUS_ARCHIVED);
3553					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
3554					updateConversation(conversation);
3555					removed = true;
3556				}
3557			}
3558		}
3559		return removed;
3560	}
3561
3562	public void sendUnblockRequest(final Blockable blockable) {
3563		if (blockable != null && blockable.getJid() != null) {
3564			final Jid jid = blockable.getBlockedJid();
3565			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3566				@Override
3567				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3568					if (packet.getType() == IqPacket.TYPE.RESULT) {
3569						account.getBlocklist().remove(jid);
3570						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3571					}
3572				}
3573			});
3574		}
3575	}
3576
3577	public void publishDisplayName(Account account) {
3578		String displayName = account.getDisplayName();
3579		if (displayName != null && !displayName.isEmpty()) {
3580			IqPacket publish = mIqGenerator.publishNick(displayName);
3581			sendIqPacket(account, publish, (account1, packet) -> {
3582				if (packet.getType() == IqPacket.TYPE.ERROR) {
3583					Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": could not publish nick");
3584				}
3585			});
3586		}
3587	}
3588
3589	public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
3590		ServiceDiscoveryResult result = discoCache.get(key);
3591		if (result != null) {
3592			return result;
3593		} else {
3594			result = databaseBackend.findDiscoveryResult(key.first, key.second);
3595			if (result != null) {
3596				discoCache.put(key, result);
3597			}
3598			return result;
3599		}
3600	}
3601
3602	public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3603		final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
3604		ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3605		if (disco != null) {
3606			presence.setServiceDiscoveryResult(disco);
3607		} else {
3608			if (!account.inProgressDiscoFetches.contains(key)) {
3609				account.inProgressDiscoFetches.add(key);
3610				IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3611				request.setTo(jid);
3612				final String node = presence.getNode();
3613				final String ver = presence.getVer();
3614				final Element query = request.query("http://jabber.org/protocol/disco#info");
3615				if (node != null && ver != null) {
3616					query.setAttribute("node",node+"#"+ver);
3617				}
3618				Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
3619				sendIqPacket(account, request, (a, response) -> {
3620					if (response.getType() == IqPacket.TYPE.RESULT) {
3621						ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
3622						if (presence.getVer().equals(discoveryResult.getVer())) {
3623							databaseBackend.insertDiscoveryResult(discoveryResult);
3624							injectServiceDiscorveryResult(a.getRoster(), presence.getHash(), presence.getVer(), discoveryResult);
3625						} else {
3626							Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
3627						}
3628					}
3629					a.inProgressDiscoFetches.remove(key);
3630				});
3631			}
3632		}
3633	}
3634
3635	private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3636		for (Contact contact : roster.getContacts()) {
3637			for (Presence presence : contact.getPresences().getPresences().values()) {
3638				if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3639					presence.setServiceDiscoveryResult(disco);
3640				}
3641			}
3642		}
3643	}
3644
3645	public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3646		final boolean legacy = account.getXmppConnection().getFeatures().mamLegacy();
3647		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3648		request.addChild("prefs", legacy ? Namespace.MAM_LEGACY : Namespace.MAM);
3649		sendIqPacket(account, request, (account1, packet) -> {
3650			Element prefs = packet.findChild("prefs", legacy ? Namespace.MAM_LEGACY : Namespace.MAM);
3651			if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3652				callback.onPreferencesFetched(prefs);
3653			} else {
3654				callback.onPreferencesFetchFailed();
3655			}
3656		});
3657	}
3658
3659	public PushManagementService getPushManagementService() {
3660		return mPushManagementService;
3661	}
3662
3663	public Account getPendingAccount() {
3664		Account pending = null;
3665		for (Account account : getAccounts()) {
3666			if (!account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY)) {
3667				pending = account;
3668			} else {
3669				return null;
3670			}
3671		}
3672		return pending;
3673	}
3674
3675	public void changeStatus(Account account, PresenceTemplate template, String signature) {
3676		if (!template.getStatusMessage().isEmpty()) {
3677			databaseBackend.insertPresenceTemplate(template);
3678		}
3679		account.setPgpSignature(signature);
3680		account.setPresenceStatus(template.getStatus());
3681		account.setPresenceStatusMessage(template.getStatusMessage());
3682		databaseBackend.updateAccount(account);
3683		sendPresence(account);
3684	}
3685
3686	public List<PresenceTemplate> getPresenceTemplates(Account account) {
3687		List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3688		for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3689			if (!templates.contains(template)) {
3690				templates.add(0, template);
3691			}
3692		}
3693		return templates;
3694	}
3695
3696	public void saveConversationAsBookmark(Conversation conversation, String name) {
3697		Account account = conversation.getAccount();
3698		Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
3699		if (!conversation.getJid().isBareJid()) {
3700			bookmark.setNick(conversation.getJid().getResource());
3701		}
3702		if (name != null && !name.trim().isEmpty()) {
3703			bookmark.setBookmarkName(name.trim());
3704		}
3705		bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
3706		account.getBookmarks().add(bookmark);
3707		pushBookmarks(account);
3708		bookmark.setConversation(conversation);
3709	}
3710
3711	public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
3712		boolean performedVerification = false;
3713		final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
3714		for (XmppUri.Fingerprint fp : fingerprints) {
3715			if (fp.type == XmppUri.FingerprintType.OMEMO) {
3716				String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
3717				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3718				if (fingerprintStatus != null) {
3719					if (!fingerprintStatus.isVerified()) {
3720						performedVerification = true;
3721						axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
3722					}
3723				} else {
3724					axolotlService.preVerifyFingerprint(contact, fingerprint);
3725				}
3726			}
3727		}
3728		return performedVerification;
3729	}
3730
3731	public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
3732		final AxolotlService axolotlService = account.getAxolotlService();
3733		boolean verifiedSomething = false;
3734		for (XmppUri.Fingerprint fp : fingerprints) {
3735			if (fp.type == XmppUri.FingerprintType.OMEMO) {
3736				String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
3737				Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
3738				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3739				if (fingerprintStatus != null) {
3740					if (!fingerprintStatus.isVerified()) {
3741						axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
3742						verifiedSomething = true;
3743					}
3744				} else {
3745					axolotlService.preVerifyFingerprint(account, fingerprint);
3746					verifiedSomething = true;
3747				}
3748			}
3749		}
3750		return verifiedSomething;
3751	}
3752
3753	public boolean blindTrustBeforeVerification() {
3754		return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
3755	}
3756
3757	public ShortcutService getShortcutService() {
3758		return mShortcutService;
3759	}
3760
3761	public void pushMamPreferences(Account account, Element prefs) {
3762		IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3763		set.addChild(prefs);
3764		sendIqPacket(account, set, null);
3765	}
3766
3767	public interface OnMamPreferencesFetched {
3768		void onPreferencesFetched(Element prefs);
3769
3770		void onPreferencesFetchFailed();
3771	}
3772
3773	public interface OnAccountCreated {
3774		void onAccountCreated(Account account);
3775
3776		void informUser(int r);
3777	}
3778
3779	public interface OnMoreMessagesLoaded {
3780		void onMoreMessagesLoaded(int count, Conversation conversation);
3781
3782		void informUser(int r);
3783	}
3784
3785	public interface OnAccountPasswordChanged {
3786		void onPasswordChangeSucceeded();
3787
3788		void onPasswordChangeFailed();
3789	}
3790
3791	public interface OnAffiliationChanged {
3792		void onAffiliationChangedSuccessful(Jid jid);
3793
3794		void onAffiliationChangeFailed(Jid jid, int resId);
3795	}
3796
3797	public interface OnRoleChanged {
3798		void onRoleChangedSuccessful(String nick);
3799
3800		void onRoleChangeFailed(String nick, int resid);
3801	}
3802
3803	public interface OnConversationUpdate {
3804		void onConversationUpdate();
3805	}
3806
3807	public interface OnAccountUpdate {
3808		void onAccountUpdate();
3809	}
3810
3811	public interface OnCaptchaRequested {
3812		void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
3813	}
3814
3815	public interface OnRosterUpdate {
3816		void onRosterUpdate();
3817	}
3818
3819	public interface OnMucRosterUpdate {
3820		void onMucRosterUpdate();
3821	}
3822
3823	public interface OnConferenceConfigurationFetched {
3824		void onConferenceConfigurationFetched(Conversation conversation);
3825
3826		void onFetchFailed(Conversation conversation, Element error);
3827	}
3828
3829	public interface OnConferenceJoined {
3830		void onConferenceJoined(Conversation conversation);
3831	}
3832
3833	public interface OnConfigurationPushed {
3834		void onPushSucceeded();
3835
3836		void onPushFailed();
3837	}
3838
3839	public interface OnShowErrorToast {
3840		void onShowErrorToast(int resId);
3841	}
3842
3843	public class XmppConnectionBinder extends Binder {
3844		public XmppConnectionService getService() {
3845			return XmppConnectionService.this;
3846		}
3847	}
3848}