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