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