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