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