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