XmppConnectionService.java

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