XmppConnectionService.java

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