XmppConnectionService.java

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