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	}
2542
2543	public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2544		final Jid jid = user.asBareJid();
2545		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2546		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2547			@Override
2548			public void onIqPacketReceived(Account account, IqPacket packet) {
2549				if (packet.getType() == IqPacket.TYPE.RESULT) {
2550					conference.getMucOptions().changeAffiliation(jid, affiliation);
2551					getAvatarService().clear(conference);
2552					callback.onAffiliationChangedSuccessful(jid);
2553				} else {
2554					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2555				}
2556			}
2557		});
2558	}
2559
2560	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2561		List<Jid> jids = new ArrayList<>();
2562		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2563			if (user.getAffiliation() == before && user.getRealJid() != null) {
2564				jids.add(user.getRealJid());
2565			}
2566		}
2567		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2568		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2569	}
2570
2571	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2572		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2573		Log.d(Config.LOGTAG, request.toString());
2574		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2575			@Override
2576			public void onIqPacketReceived(Account account, IqPacket packet) {
2577				Log.d(Config.LOGTAG, packet.toString());
2578				if (packet.getType() == IqPacket.TYPE.RESULT) {
2579					callback.onRoleChangedSuccessful(nick);
2580				} else {
2581					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2582				}
2583			}
2584		});
2585	}
2586
2587	private void disconnect(Account account, boolean force) {
2588		if ((account.getStatus() == Account.State.ONLINE)
2589				|| (account.getStatus() == Account.State.DISABLED)) {
2590			final XmppConnection connection = account.getXmppConnection();
2591			if (!force) {
2592				List<Conversation> conversations = getConversations();
2593				for (Conversation conversation : conversations) {
2594					if (conversation.getAccount() == account) {
2595						if (conversation.getMode() == Conversation.MODE_MULTI) {
2596							leaveMuc(conversation, true);
2597						}
2598					}
2599				}
2600				sendOfflinePresence(account);
2601			}
2602			connection.disconnect(force);
2603		}
2604	}
2605
2606	@Override
2607	public IBinder onBind(Intent intent) {
2608		return mBinder;
2609	}
2610
2611	public void updateMessage(Message message) {
2612		updateMessage(message, true);
2613	}
2614
2615	public void updateMessage(Message message, boolean includeBody) {
2616		databaseBackend.updateMessage(message, includeBody);
2617		updateConversationUi();
2618	}
2619
2620	public void updateMessage(Message message, String uuid) {
2621		databaseBackend.updateMessage(message, uuid);
2622		updateConversationUi();
2623	}
2624
2625	protected void syncDirtyContacts(Account account) {
2626		for (Contact contact : account.getRoster().getContacts()) {
2627			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2628				pushContactToServer(contact);
2629			}
2630			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2631				deleteContactOnServer(contact);
2632			}
2633		}
2634	}
2635
2636	public void createContact(Contact contact, boolean autoGrant) {
2637		if (autoGrant) {
2638			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2639			contact.setOption(Contact.Options.ASKING);
2640		}
2641		pushContactToServer(contact);
2642	}
2643
2644	public void pushContactToServer(final Contact contact) {
2645		contact.resetOption(Contact.Options.DIRTY_DELETE);
2646		contact.setOption(Contact.Options.DIRTY_PUSH);
2647		final Account account = contact.getAccount();
2648		if (account.getStatus() == Account.State.ONLINE) {
2649			final boolean ask = contact.getOption(Contact.Options.ASKING);
2650			final boolean sendUpdates = contact
2651					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2652					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2653			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2654			iq.query(Namespace.ROSTER).addChild(contact.asElement());
2655			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2656			if (sendUpdates) {
2657				sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
2658			}
2659			if (ask) {
2660				sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2661			}
2662		} else {
2663			syncRoster(contact.getAccount());
2664		}
2665	}
2666
2667	public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
2668		new Thread(() -> {
2669			final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2670			final int size = Config.AVATAR_SIZE;
2671			final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2672			if (avatar != null) {
2673				if (!getFileBackend().save(avatar)) {
2674					callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
2675					return;
2676				}
2677				avatar.owner = conversation.getJid().asBareJid();
2678				publishMucAvatar(conversation, avatar, callback);
2679			} else {
2680				callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
2681			}
2682		}).start();
2683	}
2684
2685	public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
2686		new Thread(() -> {
2687			final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2688			final int size = Config.AVATAR_SIZE;
2689			final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2690			if (avatar != null) {
2691				if (!getFileBackend().save(avatar)) {
2692					Log.d(Config.LOGTAG,"unable to save vcard");
2693					callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
2694					return;
2695				}
2696				publishAvatar(account, avatar, callback);
2697			} else {
2698				callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
2699			}
2700		}).start();
2701
2702	}
2703
2704	private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
2705		final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
2706		sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
2707			boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
2708			if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
2709				Element vcard = response.findChild("vCard", "vcard-temp");
2710				if (vcard == null) {
2711					vcard = new Element("vCard", "vcard-temp");
2712				}
2713				Element photo = vcard.findChild("PHOTO");
2714				if (photo == null) {
2715					photo = vcard.addChild("PHOTO");
2716				}
2717				photo.clearChildren();
2718				photo.addChild("TYPE").setContent(avatar.type);
2719				photo.addChild("BINVAL").setContent(avatar.image);
2720				IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
2721				publication.setTo(conversation.getJid().asBareJid());
2722				publication.addChild(vcard);
2723				sendIqPacket(account, publication, (a1, publicationResponse) -> {
2724					if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
2725						callback.onAvatarPublicationSucceeded();
2726					} else {
2727						Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getError());
2728						callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
2729					}
2730				});
2731			} else {
2732				Log.d(Config.LOGTAG, "failed to request vcard " + response.toString());
2733				callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
2734			}
2735		});
2736	}
2737
2738	public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
2739		IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2740		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2741
2742			@Override
2743			public void onIqPacketReceived(Account account, IqPacket result) {
2744				if (result.getType() == IqPacket.TYPE.RESULT) {
2745					final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar);
2746					sendIqPacket(account, packet, new OnIqPacketReceived() {
2747						@Override
2748						public void onIqPacketReceived(Account account, IqPacket result) {
2749							if (result.getType() == IqPacket.TYPE.RESULT) {
2750								if (account.setAvatar(avatar.getFilename())) {
2751									getAvatarService().clear(account);
2752									databaseBackend.updateAccount(account);
2753								}
2754								Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
2755								if (callback != null) {
2756									callback.onAvatarPublicationSucceeded();
2757								}
2758							} else {
2759								if (callback != null) {
2760									callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
2761								}
2762							}
2763						}
2764					});
2765				} else {
2766					Element error = result.findChild("error");
2767					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
2768					if (callback != null) {
2769						callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
2770					}
2771				}
2772			}
2773		});
2774	}
2775
2776	public void republishAvatarIfNeeded(Account account) {
2777		if (account.getAxolotlService().isPepBroken()) {
2778			Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
2779			return;
2780		}
2781		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2782		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2783
2784			private Avatar parseAvatar(IqPacket packet) {
2785				Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2786				if (pubsub != null) {
2787					Element items = pubsub.findChild("items");
2788					if (items != null) {
2789						return Avatar.parseMetadata(items);
2790					}
2791				}
2792				return null;
2793			}
2794
2795			private boolean errorIsItemNotFound(IqPacket packet) {
2796				Element error = packet.findChild("error");
2797				return packet.getType() == IqPacket.TYPE.ERROR
2798						&& error != null
2799						&& error.hasChild("item-not-found");
2800			}
2801
2802			@Override
2803			public void onIqPacketReceived(Account account, IqPacket packet) {
2804				if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2805					Avatar serverAvatar = parseAvatar(packet);
2806					if (serverAvatar == null && account.getAvatar() != null) {
2807						Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2808						if (avatar != null) {
2809							Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
2810							publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2811						} else {
2812							Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
2813						}
2814					}
2815				}
2816			}
2817		});
2818	}
2819
2820	public void fetchAvatar(Account account, Avatar avatar) {
2821		fetchAvatar(account, avatar, null);
2822	}
2823
2824	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2825		final String KEY = generateFetchKey(account, avatar);
2826		synchronized (this.mInProgressAvatarFetches) {
2827			if (!this.mInProgressAvatarFetches.contains(KEY)) {
2828				switch (avatar.origin) {
2829					case PEP:
2830						this.mInProgressAvatarFetches.add(KEY);
2831						fetchAvatarPep(account, avatar, callback);
2832						break;
2833					case VCARD:
2834						this.mInProgressAvatarFetches.add(KEY);
2835						fetchAvatarVcard(account, avatar, callback);
2836						break;
2837				}
2838			}
2839		}
2840	}
2841
2842	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2843		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2844		sendIqPacket(account, packet, (a, result) -> {
2845			synchronized (mInProgressAvatarFetches) {
2846				mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
2847			}
2848			final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
2849			if (result.getType() == IqPacket.TYPE.RESULT) {
2850				avatar.image = mIqParser.avatarData(result);
2851				if (avatar.image != null) {
2852					if (getFileBackend().save(avatar)) {
2853						if (a.getJid().asBareJid().equals(avatar.owner)) {
2854							if (a.setAvatar(avatar.getFilename())) {
2855								databaseBackend.updateAccount(a);
2856							}
2857							getAvatarService().clear(a);
2858							updateConversationUi();
2859							updateAccountUi();
2860						} else {
2861							Contact contact = a.getRoster().getContact(avatar.owner);
2862							contact.setAvatar(avatar);
2863							getAvatarService().clear(contact);
2864							updateConversationUi();
2865							updateRosterUi();
2866						}
2867						if (callback != null) {
2868							callback.success(avatar);
2869						}
2870						Log.d(Config.LOGTAG, a.getJid().asBareJid()
2871								+ ": successfully fetched pep avatar for " + avatar.owner);
2872						return;
2873					}
2874				} else {
2875
2876					Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2877				}
2878			} else {
2879				Element error = result.findChild("error");
2880				if (error == null) {
2881					Log.d(Config.LOGTAG, ERROR + "(server error)");
2882				} else {
2883					Log.d(Config.LOGTAG, ERROR + error.toString());
2884				}
2885			}
2886			if (callback != null) {
2887				callback.error(0, null);
2888			}
2889
2890		});
2891	}
2892
2893	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2894		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2895		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2896			@Override
2897			public void onIqPacketReceived(Account account, IqPacket packet) {
2898				synchronized (mInProgressAvatarFetches) {
2899					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2900				}
2901				if (packet.getType() == IqPacket.TYPE.RESULT) {
2902					Element vCard = packet.findChild("vCard", "vcard-temp");
2903					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2904					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2905					if (image != null) {
2906						avatar.image = image;
2907						if (getFileBackend().save(avatar)) {
2908							Log.d(Config.LOGTAG, account.getJid().asBareJid()
2909									+ ": successfully fetched vCard avatar for " + avatar.owner);
2910							if (avatar.owner.isBareJid()) {
2911								if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
2912									Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
2913									account.setAvatar(avatar.getFilename());
2914									databaseBackend.updateAccount(account);
2915									getAvatarService().clear(account);
2916									updateAccountUi();
2917								} else {
2918									Contact contact = account.getRoster().getContact(avatar.owner);
2919									contact.setAvatar(avatar);
2920									getAvatarService().clear(contact);
2921									updateRosterUi();
2922								}
2923								updateConversationUi();
2924							} else {
2925								Conversation conversation = find(account, avatar.owner.asBareJid());
2926								if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
2927									MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
2928									if (user != null) {
2929										if (user.setAvatar(avatar)) {
2930											getAvatarService().clear(user);
2931											updateConversationUi();
2932											updateMucRosterUi();
2933										}
2934									}
2935								}
2936							}
2937						}
2938					}
2939				}
2940			}
2941		});
2942	}
2943
2944	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2945		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2946		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2947
2948			@Override
2949			public void onIqPacketReceived(Account account, IqPacket packet) {
2950				if (packet.getType() == IqPacket.TYPE.RESULT) {
2951					Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2952					if (pubsub != null) {
2953						Element items = pubsub.findChild("items");
2954						if (items != null) {
2955							Avatar avatar = Avatar.parseMetadata(items);
2956							if (avatar != null) {
2957								avatar.owner = account.getJid().asBareJid();
2958								if (fileBackend.isAvatarCached(avatar)) {
2959									if (account.setAvatar(avatar.getFilename())) {
2960										databaseBackend.updateAccount(account);
2961									}
2962									getAvatarService().clear(account);
2963									callback.success(avatar);
2964								} else {
2965									fetchAvatarPep(account, avatar, callback);
2966								}
2967								return;
2968							}
2969						}
2970					}
2971				}
2972				callback.error(0, null);
2973			}
2974		});
2975	}
2976
2977	public void deleteContactOnServer(Contact contact) {
2978		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2979		contact.resetOption(Contact.Options.DIRTY_PUSH);
2980		contact.setOption(Contact.Options.DIRTY_DELETE);
2981		Account account = contact.getAccount();
2982		if (account.getStatus() == Account.State.ONLINE) {
2983			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2984			Element item = iq.query(Namespace.ROSTER).addChild("item");
2985			item.setAttribute("jid", contact.getJid().toString());
2986			item.setAttribute("subscription", "remove");
2987			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2988		}
2989	}
2990
2991	public void updateConversation(final Conversation conversation) {
2992		mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
2993	}
2994
2995	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2996		synchronized (account) {
2997			XmppConnection connection = account.getXmppConnection();
2998			if (connection == null) {
2999				connection = createConnection(account);
3000				account.setXmppConnection(connection);
3001			}
3002			boolean hasInternet = hasInternetConnection();
3003			if (account.isEnabled() && hasInternet) {
3004				if (!force) {
3005					disconnect(account, false);
3006				}
3007				Thread thread = new Thread(connection);
3008				connection.setInteractive(interactive);
3009				connection.prepareNewConnection();
3010				connection.interrupt();
3011				thread.start();
3012				scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
3013			} else {
3014				disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
3015				account.getRoster().clearPresences();
3016				connection.resetEverything();
3017				final AxolotlService axolotlService = account.getAxolotlService();
3018				if (axolotlService != null) {
3019					axolotlService.resetBrokenness();
3020				}
3021				if (!hasInternet) {
3022					account.setStatus(Account.State.NO_INTERNET);
3023				}
3024			}
3025		}
3026	}
3027
3028	public void reconnectAccountInBackground(final Account account) {
3029		new Thread(() -> reconnectAccount(account, false, true)).start();
3030	}
3031
3032	public void invite(Conversation conversation, Jid contact) {
3033		Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
3034		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
3035		sendMessagePacket(conversation.getAccount(), packet);
3036	}
3037
3038	public void directInvite(Conversation conversation, Jid jid) {
3039		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
3040		sendMessagePacket(conversation.getAccount(), packet);
3041	}
3042
3043	public void resetSendingToWaiting(Account account) {
3044		for (Conversation conversation : getConversations()) {
3045			if (conversation.getAccount() == account) {
3046				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
3047
3048					@Override
3049					public void onMessageFound(Message message) {
3050						markMessage(message, Message.STATUS_WAITING);
3051					}
3052				});
3053			}
3054		}
3055	}
3056
3057	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
3058		return markMessage(account, recipient, uuid, status, null);
3059	}
3060
3061	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
3062		if (uuid == null) {
3063			return null;
3064		}
3065		for (Conversation conversation : getConversations()) {
3066			if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
3067				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
3068				if (message != null) {
3069					markMessage(message, status, errorMessage);
3070				}
3071				return message;
3072			}
3073		}
3074		return null;
3075	}
3076
3077	public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) {
3078		if (uuid == null) {
3079			return false;
3080		} else {
3081			Message message = conversation.findSentMessageWithUuid(uuid);
3082			if (message != null) {
3083				if (message.getServerMsgId() == null) {
3084					message.setServerMsgId(serverMessageId);
3085				}
3086				markMessage(message, status);
3087				return true;
3088			} else {
3089				return false;
3090			}
3091		}
3092	}
3093
3094	public void markMessage(Message message, int status) {
3095		markMessage(message, status, null);
3096	}
3097
3098
3099	public void markMessage(Message message, int status, String errorMessage) {
3100		final int c = message.getStatus();
3101		if (status == Message.STATUS_SEND_FAILED && (c == Message.STATUS_SEND_RECEIVED || c == Message.STATUS_SEND_DISPLAYED)) {
3102			return;
3103		}
3104		if (status == Message.STATUS_SEND_RECEIVED && c == Message.STATUS_SEND_DISPLAYED) {
3105			return;
3106		}
3107		message.setErrorMessage(errorMessage);
3108		message.setStatus(status);
3109		databaseBackend.updateMessage(message, false);
3110		updateConversationUi();
3111	}
3112
3113	private SharedPreferences getPreferences() {
3114		return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
3115	}
3116
3117	public long getAutomaticMessageDeletionDate() {
3118		final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
3119		return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
3120	}
3121
3122	public long getLongPreference(String name, @IntegerRes int res) {
3123		long defaultValue = getResources().getInteger(res);
3124		try {
3125			return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
3126		} catch (NumberFormatException e) {
3127			return defaultValue;
3128		}
3129	}
3130
3131	public boolean getBooleanPreference(String name, @BoolRes int res) {
3132		return getPreferences().getBoolean(name, getResources().getBoolean(res));
3133	}
3134
3135	public boolean confirmMessages() {
3136		return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
3137	}
3138
3139	public boolean allowMessageCorrection() {
3140		return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
3141	}
3142
3143	public boolean sendChatStates() {
3144		return getBooleanPreference("chat_states", R.bool.chat_states);
3145	}
3146
3147	private boolean respectAutojoin() {
3148		return getBooleanPreference("autojoin", R.bool.autojoin);
3149	}
3150
3151	public boolean indicateReceived() {
3152		return getBooleanPreference("indicate_received", R.bool.indicate_received);
3153	}
3154
3155	public boolean useTorToConnect() {
3156		return Config.FORCE_ORBOT || getBooleanPreference("use_tor", R.bool.use_tor);
3157	}
3158
3159	public boolean showExtendedConnectionOptions() {
3160		return getBooleanPreference("show_connection_options", R.bool.show_connection_options);
3161	}
3162
3163	public boolean broadcastLastActivity() {
3164		return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
3165	}
3166
3167	public int unreadCount() {
3168		int count = 0;
3169		for (Conversation conversation : getConversations()) {
3170			count += conversation.unreadCount();
3171		}
3172		return count;
3173	}
3174
3175
3176	public void showErrorToastInUi(int resId) {
3177		for(OnShowErrorToast listener : this.mOnShowErrorToasts) {
3178			listener.onShowErrorToast(resId);
3179		}
3180	}
3181
3182	public void updateConversationUi() {
3183		for(OnConversationUpdate listener : this.mOnConversationUpdates) {
3184			listener.onConversationUpdate();
3185		}
3186	}
3187
3188	public void updateAccountUi() {
3189		for(OnAccountUpdate listener : this.mOnAccountUpdates) {
3190			listener.onAccountUpdate();
3191		}
3192	}
3193
3194	public void updateRosterUi() {
3195		for(OnRosterUpdate listener : this.mOnRosterUpdates) {
3196			listener.onRosterUpdate();
3197		}
3198	}
3199
3200	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3201		if (mOnCaptchaRequested.size() > 0) {
3202			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3203			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3204					(int) (captcha.getHeight() * metrics.scaledDensity), false);
3205			for(OnCaptchaRequested listener : this.mOnCaptchaRequested) {
3206				listener.onCaptchaRequested(account, id, data, scaled);
3207			}
3208			return true;
3209		}
3210		return false;
3211	}
3212
3213	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3214		for(OnUpdateBlocklist listener : this.mOnUpdateBlocklist) {
3215			listener.OnUpdateBlocklist(status);
3216		}
3217	}
3218
3219	public void updateMucRosterUi() {
3220		for(OnMucRosterUpdate listener : this.mOnMucRosterUpdate) {
3221			listener.onMucRosterUpdate();
3222		}
3223	}
3224
3225	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3226		for(OnKeyStatusUpdated listener : this.mOnKeyStatusUpdated) {
3227			listener.onKeyStatusUpdated(report);
3228		}
3229	}
3230
3231	public Account findAccountByJid(final Jid accountJid) {
3232		for (Account account : this.accounts) {
3233			if (account.getJid().asBareJid().equals(accountJid.asBareJid())) {
3234				return account;
3235			}
3236		}
3237		return null;
3238	}
3239
3240	public Account findAccountByUuid(final String uuid) {
3241		for(Account account : this.accounts) {
3242			if (account.getUuid().equals(uuid)) {
3243				return account;
3244			}
3245		}
3246		return null;
3247	}
3248
3249	public Conversation findConversationByUuid(String uuid) {
3250		for (Conversation conversation : getConversations()) {
3251			if (conversation.getUuid().equals(uuid)) {
3252				return conversation;
3253			}
3254		}
3255		return null;
3256	}
3257
3258	public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
3259		List<Conversation> findings = new ArrayList<>();
3260		for (Conversation c : getConversations()) {
3261			if (c.getJid().asBareJid().equals(xmppUri.getJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
3262				findings.add(c);
3263			}
3264		}
3265		return findings.size() == 1 ? findings.get(0) : null;
3266	}
3267
3268	public boolean markRead(final Conversation conversation, boolean dismiss) {
3269		return markRead(conversation, null, dismiss).size() > 0;
3270	}
3271
3272	public void markRead(final Conversation conversation) {
3273		markRead(conversation, null, true);
3274	}
3275
3276	public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
3277		if (dismiss) {
3278			mNotificationService.clear(conversation);
3279		}
3280		final List<Message> readMessages = conversation.markRead(upToUuid);
3281		if (readMessages.size() > 0) {
3282			Runnable runnable = () -> {
3283				for (Message message : readMessages) {
3284					databaseBackend.updateMessage(message, false);
3285				}
3286			};
3287			mDatabaseWriterExecutor.execute(runnable);
3288			updateUnreadCountBadge();
3289			return readMessages;
3290		} else {
3291			return readMessages;
3292		}
3293	}
3294
3295	public synchronized void updateUnreadCountBadge() {
3296		int count = unreadCount();
3297		if (unreadCount != count) {
3298			Log.d(Config.LOGTAG, "update unread count to " + count);
3299			if (count > 0) {
3300				ShortcutBadger.applyCount(getApplicationContext(), count);
3301			} else {
3302				ShortcutBadger.removeCount(getApplicationContext());
3303			}
3304			unreadCount = count;
3305		}
3306	}
3307
3308	public void sendReadMarker(final Conversation conversation, String upToUuid) {
3309		final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
3310		final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
3311		if (readMessages.size() > 0) {
3312			updateConversationUi();
3313		}
3314		final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
3315		if (confirmMessages()
3316				&& markable != null
3317				&& (markable.trusted() || isPrivateAndNonAnonymousMuc)
3318				&& markable.getRemoteMsgId() != null) {
3319			Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
3320			Account account = conversation.getAccount();
3321			final Jid to = markable.getCounterpart();
3322			final boolean groupChat = conversation.getMode() == Conversation.MODE_MULTI;
3323			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId(), markable.getCounterpart(), groupChat);
3324			this.sendMessagePacket(conversation.getAccount(), packet);
3325		}
3326	}
3327
3328	public SecureRandom getRNG() {
3329		return this.mRandom;
3330	}
3331
3332	public MemorizingTrustManager getMemorizingTrustManager() {
3333		return this.mMemorizingTrustManager;
3334	}
3335
3336	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
3337		this.mMemorizingTrustManager = trustManager;
3338	}
3339
3340	public void updateMemorizingTrustmanager() {
3341		final MemorizingTrustManager tm;
3342		final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
3343		if (dontTrustSystemCAs) {
3344			tm = new MemorizingTrustManager(getApplicationContext(), null);
3345		} else {
3346			tm = new MemorizingTrustManager(getApplicationContext());
3347		}
3348		setMemorizingTrustManager(tm);
3349	}
3350
3351	public LruCache<String, Bitmap> getBitmapCache() {
3352		return this.mBitmapCache;
3353	}
3354
3355	public Collection<String> getKnownHosts() {
3356		final Set<String> hosts = new HashSet<>();
3357		for (final Account account : getAccounts()) {
3358			hosts.add(account.getServer());
3359			for (final Contact contact : account.getRoster().getContacts()) {
3360				if (contact.showInRoster()) {
3361					final String server = contact.getServer();
3362					if (server != null && !hosts.contains(server)) {
3363						hosts.add(server);
3364					}
3365				}
3366			}
3367		}
3368		if (Config.DOMAIN_LOCK != null) {
3369			hosts.add(Config.DOMAIN_LOCK);
3370		}
3371		if (Config.MAGIC_CREATE_DOMAIN != null) {
3372			hosts.add(Config.MAGIC_CREATE_DOMAIN);
3373		}
3374		return hosts;
3375	}
3376
3377	public Collection<String> getKnownConferenceHosts() {
3378		final Set<String> mucServers = new HashSet<>();
3379		for (final Account account : accounts) {
3380			if (account.getXmppConnection() != null) {
3381				mucServers.addAll(account.getXmppConnection().getMucServers());
3382				for (Bookmark bookmark : account.getBookmarks()) {
3383					final Jid jid = bookmark.getJid();
3384					final String s = jid == null ? null : jid.getDomain();
3385					if (s != null) {
3386						mucServers.add(s);
3387					}
3388				}
3389			}
3390		}
3391		return mucServers;
3392	}
3393
3394	public void sendMessagePacket(Account account, MessagePacket packet) {
3395		XmppConnection connection = account.getXmppConnection();
3396		if (connection != null) {
3397			connection.sendMessagePacket(packet);
3398		}
3399	}
3400
3401	public void sendPresencePacket(Account account, PresencePacket packet) {
3402		XmppConnection connection = account.getXmppConnection();
3403		if (connection != null) {
3404			connection.sendPresencePacket(packet);
3405		}
3406	}
3407
3408	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3409		final XmppConnection connection = account.getXmppConnection();
3410		if (connection != null) {
3411			IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3412			connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
3413		}
3414	}
3415
3416	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3417		final XmppConnection connection = account.getXmppConnection();
3418		if (connection != null) {
3419			connection.sendIqPacket(packet, callback);
3420		}
3421	}
3422
3423	public void sendPresence(final Account account) {
3424		sendPresence(account, checkListeners() && broadcastLastActivity());
3425	}
3426
3427	private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3428		Presence.Status status;
3429		if (manuallyChangePresence()) {
3430			status = account.getPresenceStatus();
3431		} else {
3432			status = getTargetPresence();
3433		}
3434		PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
3435		String message = account.getPresenceStatusMessage();
3436		if (message != null && !message.isEmpty()) {
3437			packet.addChild(new Element("status").setContent(message));
3438		}
3439		if (mLastActivity > 0 && includeIdleTimestamp) {
3440			long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3441			packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
3442		}
3443		sendPresencePacket(account, packet);
3444	}
3445
3446	private void deactivateGracePeriod() {
3447		for (Account account : getAccounts()) {
3448			account.deactivateGracePeriod();
3449		}
3450	}
3451
3452	public void refreshAllPresences() {
3453		boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3454		for (Account account : getAccounts()) {
3455			if (account.isEnabled()) {
3456				sendPresence(account, includeIdleTimestamp);
3457			}
3458		}
3459	}
3460
3461	private void refreshAllFcmTokens() {
3462		for (Account account : getAccounts()) {
3463			if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3464				mPushManagementService.registerPushTokenOnServer(account);
3465			}
3466		}
3467	}
3468
3469	private void sendOfflinePresence(final Account account) {
3470		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
3471		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3472	}
3473
3474	public MessageGenerator getMessageGenerator() {
3475		return this.mMessageGenerator;
3476	}
3477
3478	public PresenceGenerator getPresenceGenerator() {
3479		return this.mPresenceGenerator;
3480	}
3481
3482	public IqGenerator getIqGenerator() {
3483		return this.mIqGenerator;
3484	}
3485
3486	public IqParser getIqParser() {
3487		return this.mIqParser;
3488	}
3489
3490	public JingleConnectionManager getJingleConnectionManager() {
3491		return this.mJingleConnectionManager;
3492	}
3493
3494	public MessageArchiveService getMessageArchiveService() {
3495		return this.mMessageArchiveService;
3496	}
3497
3498	public List<Contact> findContacts(Jid jid, String accountJid) {
3499		ArrayList<Contact> contacts = new ArrayList<>();
3500		for (Account account : getAccounts()) {
3501			if ((account.isEnabled() || accountJid != null)
3502					&& (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
3503				Contact contact = account.getRoster().getContactFromRoster(jid);
3504				if (contact != null) {
3505					contacts.add(contact);
3506				}
3507			}
3508		}
3509		return contacts;
3510	}
3511
3512	public Conversation findFirstMuc(Jid jid) {
3513		for (Conversation conversation : getConversations()) {
3514			if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
3515				return conversation;
3516			}
3517		}
3518		return null;
3519	}
3520
3521	public NotificationService getNotificationService() {
3522		return this.mNotificationService;
3523	}
3524
3525	public HttpConnectionManager getHttpConnectionManager() {
3526		return this.mHttpConnectionManager;
3527	}
3528
3529	public void resendFailedMessages(final Message message) {
3530		final Collection<Message> messages = new ArrayList<>();
3531		Message current = message;
3532		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3533			messages.add(current);
3534			if (current.mergeable(current.next())) {
3535				current = current.next();
3536			} else {
3537				break;
3538			}
3539		}
3540		for (final Message msg : messages) {
3541			msg.setTime(System.currentTimeMillis());
3542			markMessage(msg, Message.STATUS_WAITING);
3543			this.resendMessage(msg, false);
3544		}
3545		if (message.getConversation() instanceof Conversation) {
3546			((Conversation) message.getConversation()).sort();
3547		}
3548		updateConversationUi();
3549	}
3550
3551	public void clearConversationHistory(final Conversation conversation) {
3552		final long clearDate;
3553		final String reference;
3554		if (conversation.countMessages() > 0) {
3555			Message latestMessage = conversation.getLatestMessage();
3556			clearDate = latestMessage.getTimeSent() + 1000;
3557			reference = latestMessage.getServerMsgId();
3558		} else {
3559			clearDate = System.currentTimeMillis();
3560			reference = null;
3561		}
3562		conversation.clearMessages();
3563		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3564		conversation.setLastClearHistory(clearDate, reference);
3565		Runnable runnable = () -> {
3566			databaseBackend.deleteMessagesInConversation(conversation);
3567			databaseBackend.updateConversation(conversation);
3568		};
3569		mDatabaseWriterExecutor.execute(runnable);
3570	}
3571
3572	public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
3573		if (blockable != null && blockable.getBlockedJid() != null) {
3574			final Jid jid = blockable.getBlockedJid();
3575			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), new OnIqPacketReceived() {
3576
3577				@Override
3578				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3579					if (packet.getType() == IqPacket.TYPE.RESULT) {
3580						account.getBlocklist().add(jid);
3581						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3582					}
3583				}
3584			});
3585			if (removeBlockedConversations(blockable.getAccount(), jid)) {
3586				updateConversationUi();
3587				return true;
3588			} else {
3589				return false;
3590			}
3591		} else {
3592			return false;
3593		}
3594	}
3595
3596	public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
3597		boolean removed = false;
3598		synchronized (this.conversations) {
3599			boolean domainJid = blockedJid.getLocal() == null;
3600			for (Conversation conversation : this.conversations) {
3601				boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
3602						|| blockedJid.equals(conversation.getJid().asBareJid());
3603				if (conversation.getAccount() == account
3604						&& conversation.getMode() == Conversation.MODE_SINGLE
3605						&& jidMatches) {
3606					this.conversations.remove(conversation);
3607					markRead(conversation);
3608					conversation.setStatus(Conversation.STATUS_ARCHIVED);
3609					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
3610					updateConversation(conversation);
3611					removed = true;
3612				}
3613			}
3614		}
3615		return removed;
3616	}
3617
3618	public void sendUnblockRequest(final Blockable blockable) {
3619		if (blockable != null && blockable.getJid() != null) {
3620			final Jid jid = blockable.getBlockedJid();
3621			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3622				@Override
3623				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3624					if (packet.getType() == IqPacket.TYPE.RESULT) {
3625						account.getBlocklist().remove(jid);
3626						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3627					}
3628				}
3629			});
3630		}
3631	}
3632
3633	public void publishDisplayName(Account account) {
3634		String displayName = account.getDisplayName();
3635		if (displayName != null && !displayName.isEmpty()) {
3636			IqPacket publish = mIqGenerator.publishNick(displayName);
3637			sendIqPacket(account, publish, (account1, packet) -> {
3638				if (packet.getType() == IqPacket.TYPE.ERROR) {
3639					Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": could not publish nick");
3640				}
3641			});
3642		}
3643	}
3644
3645	public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
3646		ServiceDiscoveryResult result = discoCache.get(key);
3647		if (result != null) {
3648			return result;
3649		} else {
3650			result = databaseBackend.findDiscoveryResult(key.first, key.second);
3651			if (result != null) {
3652				discoCache.put(key, result);
3653			}
3654			return result;
3655		}
3656	}
3657
3658	public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3659		final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
3660		ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3661		if (disco != null) {
3662			presence.setServiceDiscoveryResult(disco);
3663		} else {
3664			if (!account.inProgressDiscoFetches.contains(key)) {
3665				account.inProgressDiscoFetches.add(key);
3666				IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3667				request.setTo(jid);
3668				final String node = presence.getNode();
3669				final String ver = presence.getVer();
3670				final Element query = request.query("http://jabber.org/protocol/disco#info");
3671				if (node != null && ver != null) {
3672					query.setAttribute("node",node+"#"+ver);
3673				}
3674				Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
3675				sendIqPacket(account, request, (a, response) -> {
3676					if (response.getType() == IqPacket.TYPE.RESULT) {
3677						ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
3678						if (presence.getVer().equals(discoveryResult.getVer())) {
3679							databaseBackend.insertDiscoveryResult(discoveryResult);
3680							injectServiceDiscorveryResult(a.getRoster(), presence.getHash(), presence.getVer(), discoveryResult);
3681						} else {
3682							Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
3683						}
3684					}
3685					a.inProgressDiscoFetches.remove(key);
3686				});
3687			}
3688		}
3689	}
3690
3691	private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3692		for (Contact contact : roster.getContacts()) {
3693			for (Presence presence : contact.getPresences().getPresences().values()) {
3694				if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3695					presence.setServiceDiscoveryResult(disco);
3696				}
3697			}
3698		}
3699	}
3700
3701	public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3702		final boolean legacy = account.getXmppConnection().getFeatures().mamLegacy();
3703		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3704		request.addChild("prefs", legacy ? Namespace.MAM_LEGACY : Namespace.MAM);
3705		sendIqPacket(account, request, (account1, packet) -> {
3706			Element prefs = packet.findChild("prefs", legacy ? Namespace.MAM_LEGACY : Namespace.MAM);
3707			if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3708				callback.onPreferencesFetched(prefs);
3709			} else {
3710				callback.onPreferencesFetchFailed();
3711			}
3712		});
3713	}
3714
3715	public PushManagementService getPushManagementService() {
3716		return mPushManagementService;
3717	}
3718
3719	public Account getPendingAccount() {
3720		Account pending = null;
3721		for (Account account : getAccounts()) {
3722			if (!account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY)) {
3723				pending = account;
3724			} else {
3725				return null;
3726			}
3727		}
3728		return pending;
3729	}
3730
3731	public void changeStatus(Account account, PresenceTemplate template, String signature) {
3732		if (!template.getStatusMessage().isEmpty()) {
3733			databaseBackend.insertPresenceTemplate(template);
3734		}
3735		account.setPgpSignature(signature);
3736		account.setPresenceStatus(template.getStatus());
3737		account.setPresenceStatusMessage(template.getStatusMessage());
3738		databaseBackend.updateAccount(account);
3739		sendPresence(account);
3740	}
3741
3742	public List<PresenceTemplate> getPresenceTemplates(Account account) {
3743		List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3744		for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3745			if (!templates.contains(template)) {
3746				templates.add(0, template);
3747			}
3748		}
3749		return templates;
3750	}
3751
3752	public void saveConversationAsBookmark(Conversation conversation, String name) {
3753		Account account = conversation.getAccount();
3754		Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
3755		if (!conversation.getJid().isBareJid()) {
3756			bookmark.setNick(conversation.getJid().getResource());
3757		}
3758		if (name != null && !name.trim().isEmpty()) {
3759			bookmark.setBookmarkName(name.trim());
3760		}
3761		bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
3762		account.getBookmarks().add(bookmark);
3763		pushBookmarks(account);
3764		bookmark.setConversation(conversation);
3765	}
3766
3767	public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
3768		boolean performedVerification = false;
3769		final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
3770		for (XmppUri.Fingerprint fp : fingerprints) {
3771			if (fp.type == XmppUri.FingerprintType.OMEMO) {
3772				String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
3773				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3774				if (fingerprintStatus != null) {
3775					if (!fingerprintStatus.isVerified()) {
3776						performedVerification = true;
3777						axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
3778					}
3779				} else {
3780					axolotlService.preVerifyFingerprint(contact, fingerprint);
3781				}
3782			}
3783		}
3784		return performedVerification;
3785	}
3786
3787	public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
3788		final AxolotlService axolotlService = account.getAxolotlService();
3789		boolean verifiedSomething = false;
3790		for (XmppUri.Fingerprint fp : fingerprints) {
3791			if (fp.type == XmppUri.FingerprintType.OMEMO) {
3792				String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
3793				Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
3794				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3795				if (fingerprintStatus != null) {
3796					if (!fingerprintStatus.isVerified()) {
3797						axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
3798						verifiedSomething = true;
3799					}
3800				} else {
3801					axolotlService.preVerifyFingerprint(account, fingerprint);
3802					verifiedSomething = true;
3803				}
3804			}
3805		}
3806		return verifiedSomething;
3807	}
3808
3809	public boolean blindTrustBeforeVerification() {
3810		return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
3811	}
3812
3813	public ShortcutService getShortcutService() {
3814		return mShortcutService;
3815	}
3816
3817	public void pushMamPreferences(Account account, Element prefs) {
3818		IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3819		set.addChild(prefs);
3820		sendIqPacket(account, set, null);
3821	}
3822
3823	public interface OnMamPreferencesFetched {
3824		void onPreferencesFetched(Element prefs);
3825
3826		void onPreferencesFetchFailed();
3827	}
3828
3829	public interface OnAccountCreated {
3830		void onAccountCreated(Account account);
3831
3832		void informUser(int r);
3833	}
3834
3835	public interface OnMoreMessagesLoaded {
3836		void onMoreMessagesLoaded(int count, Conversation conversation);
3837
3838		void informUser(int r);
3839	}
3840
3841	public interface OnAccountPasswordChanged {
3842		void onPasswordChangeSucceeded();
3843
3844		void onPasswordChangeFailed();
3845	}
3846
3847	public interface OnAffiliationChanged {
3848		void onAffiliationChangedSuccessful(Jid jid);
3849
3850		void onAffiliationChangeFailed(Jid jid, int resId);
3851	}
3852
3853	public interface OnRoleChanged {
3854		void onRoleChangedSuccessful(String nick);
3855
3856		void onRoleChangeFailed(String nick, int resid);
3857	}
3858
3859	public interface OnConversationUpdate {
3860		void onConversationUpdate();
3861	}
3862
3863	public interface OnAccountUpdate {
3864		void onAccountUpdate();
3865	}
3866
3867	public interface OnCaptchaRequested {
3868		void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
3869	}
3870
3871	public interface OnRosterUpdate {
3872		void onRosterUpdate();
3873	}
3874
3875	public interface OnMucRosterUpdate {
3876		void onMucRosterUpdate();
3877	}
3878
3879	public interface OnConferenceConfigurationFetched {
3880		void onConferenceConfigurationFetched(Conversation conversation);
3881
3882		void onFetchFailed(Conversation conversation, Element error);
3883	}
3884
3885	public interface OnConferenceJoined {
3886		void onConferenceJoined(Conversation conversation);
3887	}
3888
3889	public interface OnConfigurationPushed {
3890		void onPushSucceeded();
3891
3892		void onPushFailed();
3893	}
3894
3895	public interface OnShowErrorToast {
3896		void onShowErrorToast(int resId);
3897	}
3898
3899	public class XmppConnectionBinder extends Binder {
3900		public XmppConnectionService getService() {
3901			return XmppConnectionService.this;
3902		}
3903	}
3904}