XmppConnectionService.java

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