XmppConnectionService.java

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