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, false);
2051	}
2052
2053	public void joinMuc(Conversation conversation, boolean followedInvite) {
2054		joinMuc(conversation, null, followedInvite);
2055	}
2056
2057	private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2058		joinMuc(conversation,onConferenceJoined,false);
2059	}
2060
2061	private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2062		Account account = conversation.getAccount();
2063		account.pendingConferenceJoins.remove(conversation);
2064		account.pendingConferenceLeaves.remove(conversation);
2065		if (account.getStatus() == Account.State.ONLINE) {
2066			conversation.resetMucOptions();
2067			if (onConferenceJoined != null) {
2068				conversation.getMucOptions().flagNoAutoPushConfiguration();
2069			}
2070			conversation.setHasMessagesLeftOnServer(false);
2071			fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2072
2073				private void join(Conversation conversation) {
2074					Account account = conversation.getAccount();
2075					final MucOptions mucOptions = conversation.getMucOptions();
2076					final Jid joinJid = mucOptions.getSelf().getFullJid();
2077					Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
2078					PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous());
2079					packet.setTo(joinJid);
2080					Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2081					if (conversation.getMucOptions().getPassword() != null) {
2082						x.addChild("password").setContent(mucOptions.getPassword());
2083					}
2084
2085					if (mucOptions.mamSupport()) {
2086						// Use MAM instead of the limited muc history to get history
2087						x.addChild("history").setAttribute("maxchars", "0");
2088					} else {
2089						// Fallback to muc history
2090						x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
2091					}
2092					sendPresencePacket(account, packet);
2093					if (onConferenceJoined != null) {
2094						onConferenceJoined.onConferenceJoined(conversation);
2095					}
2096					if (!joinJid.equals(conversation.getJid())) {
2097						conversation.setContactJid(joinJid);
2098						databaseBackend.updateConversation(conversation);
2099					}
2100
2101					if (mucOptions.mamSupport()) {
2102						getMessageArchiveService().catchupMUC(conversation);
2103					}
2104					if (mucOptions.membersOnly() && mucOptions.nonanonymous()) {
2105						fetchConferenceMembers(conversation);
2106						if (followedInvite && conversation.getBookmark() == null) {
2107							saveConversationAsBookmark(conversation,null);
2108						}
2109					}
2110					sendUnsentMessages(conversation);
2111				}
2112
2113				@Override
2114				public void onConferenceConfigurationFetched(Conversation conversation) {
2115					join(conversation);
2116				}
2117
2118				@Override
2119				public void onFetchFailed(final Conversation conversation, Element error) {
2120					if (error != null && "remote-server-not-found".equals(error.getName())) {
2121						conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2122					} else {
2123						join(conversation);
2124						fetchConferenceConfiguration(conversation);
2125					}
2126				}
2127			});
2128			updateConversationUi();
2129		} else {
2130			account.pendingConferenceJoins.add(conversation);
2131			conversation.resetMucOptions();
2132			conversation.setHasMessagesLeftOnServer(false);
2133			updateConversationUi();
2134		}
2135	}
2136
2137	private void fetchConferenceMembers(final Conversation conversation) {
2138		final Account account = conversation.getAccount();
2139		final String[] affiliations = {"member","admin","owner"};
2140		OnIqPacketReceived callback = new OnIqPacketReceived() {
2141
2142			private int i = 0;
2143
2144			@Override
2145			public void onIqPacketReceived(Account account, IqPacket packet) {
2146
2147				Element query = packet.query("http://jabber.org/protocol/muc#admin");
2148				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2149					for(Element child : query.getChildren()) {
2150						if ("item".equals(child.getName())) {
2151							MucOptions.User user = AbstractParser.parseItem(conversation,child);
2152							if (!user.realJidMatchesAccount()) {
2153								conversation.getMucOptions().updateUser(user);
2154							}
2155						}
2156					}
2157				} else {
2158					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not request affiliation "+affiliations[i]+" in "+conversation.getJid().toBareJid());
2159				}
2160				++i;
2161				if (i >= affiliations.length) {
2162					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": retrieved members for "+conversation.getJid().toBareJid()+": "+conversation.getMucOptions().getMembers());
2163					getAvatarService().clear(conversation);
2164					updateMucRosterUi();
2165					updateConversationUi();
2166				}
2167			}
2168		};
2169		for(String affiliation : affiliations) {
2170			sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2171		}
2172		Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetching members for "+conversation.getName());
2173	}
2174
2175	public void providePasswordForMuc(Conversation conversation, String password) {
2176		if (conversation.getMode() == Conversation.MODE_MULTI) {
2177			conversation.getMucOptions().setPassword(password);
2178			if (conversation.getBookmark() != null) {
2179				if (respectAutojoin()) {
2180					conversation.getBookmark().setAutojoin(true);
2181				}
2182				pushBookmarks(conversation.getAccount());
2183			}
2184			updateConversation(conversation);
2185			joinMuc(conversation);
2186		}
2187	}
2188
2189	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2190		final MucOptions options = conversation.getMucOptions();
2191		final Jid joinJid = options.createJoinJid(nick);
2192		if (options.online()) {
2193			Account account = conversation.getAccount();
2194			options.setOnRenameListener(new OnRenameListener() {
2195
2196				@Override
2197				public void onSuccess() {
2198					conversation.setContactJid(joinJid);
2199					databaseBackend.updateConversation(conversation);
2200					Bookmark bookmark = conversation.getBookmark();
2201					if (bookmark != null) {
2202						bookmark.setNick(nick);
2203						pushBookmarks(bookmark.getAccount());
2204					}
2205					callback.success(conversation);
2206				}
2207
2208				@Override
2209				public void onFailure() {
2210					callback.error(R.string.nick_in_use, conversation);
2211				}
2212			});
2213
2214			PresencePacket packet = new PresencePacket();
2215			packet.setTo(joinJid);
2216			packet.setFrom(conversation.getAccount().getJid());
2217
2218			String sig = account.getPgpSignature();
2219			if (sig != null) {
2220				packet.addChild("status").setContent("online");
2221				packet.addChild("x", "jabber:x:signed").setContent(sig);
2222			}
2223			sendPresencePacket(account, packet);
2224		} else {
2225			conversation.setContactJid(joinJid);
2226			databaseBackend.updateConversation(conversation);
2227			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2228				Bookmark bookmark = conversation.getBookmark();
2229				if (bookmark != null) {
2230					bookmark.setNick(nick);
2231					pushBookmarks(bookmark.getAccount());
2232				}
2233				joinMuc(conversation);
2234			}
2235		}
2236	}
2237
2238	public void leaveMuc(Conversation conversation) {
2239		leaveMuc(conversation, false);
2240	}
2241
2242	private void leaveMuc(Conversation conversation, boolean now) {
2243		Account account = conversation.getAccount();
2244		account.pendingConferenceJoins.remove(conversation);
2245		account.pendingConferenceLeaves.remove(conversation);
2246		if (account.getStatus() == Account.State.ONLINE || now) {
2247			PresencePacket packet = new PresencePacket();
2248			packet.setTo(conversation.getMucOptions().getSelf().getFullJid());
2249			packet.setFrom(conversation.getAccount().getJid());
2250			packet.setAttribute("type", "unavailable");
2251			sendPresencePacket(conversation.getAccount(), packet);
2252			conversation.getMucOptions().setOffline();
2253			conversation.deregisterWithBookmark();
2254			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
2255					+ ": leaving muc " + conversation.getJid());
2256		} else {
2257			account.pendingConferenceLeaves.add(conversation);
2258		}
2259	}
2260
2261	private String findConferenceServer(final Account account) {
2262		String server;
2263		if (account.getXmppConnection() != null) {
2264			server = account.getXmppConnection().getMucServer();
2265			if (server != null) {
2266				return server;
2267			}
2268		}
2269		for (Account other : getAccounts()) {
2270			if (other != account && other.getXmppConnection() != null) {
2271				server = other.getXmppConnection().getMucServer();
2272				if (server != null) {
2273					return server;
2274				}
2275			}
2276		}
2277		return null;
2278	}
2279
2280	public void createAdhocConference(final Account account,
2281									  final String subject,
2282									  final Iterable<Jid> jids,
2283									  final UiCallback<Conversation> callback) {
2284		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2285		if (account.getStatus() == Account.State.ONLINE) {
2286			try {
2287				String server = findConferenceServer(account);
2288				if (server == null) {
2289					if (callback != null) {
2290						callback.error(R.string.no_conference_server_found, null);
2291					}
2292					return;
2293				}
2294				final Jid jid = Jid.fromParts(new BigInteger(64, getRNG()).toString(Character.MAX_RADIX), server, null);
2295				final Conversation conversation = findOrCreateConversation(account, jid, true);
2296				joinMuc(conversation, new OnConferenceJoined() {
2297					@Override
2298					public void onConferenceJoined(final Conversation conversation) {
2299						pushConferenceConfiguration(conversation, IqGenerator.defaultRoomConfiguration(), new OnConferenceOptionsPushed() {
2300							@Override
2301							public void onPushSucceeded() {
2302								if (subject != null && !subject.trim().isEmpty()) {
2303									pushSubjectToConference(conversation, subject.trim());
2304								}
2305								for (Jid invite : jids) {
2306									invite(conversation, invite);
2307								}
2308								if (account.countPresences() > 1) {
2309									directInvite(conversation, account.getJid().toBareJid());
2310								}
2311								saveConversationAsBookmark(conversation, subject);
2312								if (callback != null) {
2313									callback.success(conversation);
2314								}
2315							}
2316
2317							@Override
2318							public void onPushFailed() {
2319								archiveConversation(conversation);
2320								if (callback != null) {
2321									callback.error(R.string.conference_creation_failed, conversation);
2322								}
2323							}
2324						});
2325					}
2326				});
2327			} catch (InvalidJidException e) {
2328				if (callback != null) {
2329					callback.error(R.string.conference_creation_failed, null);
2330				}
2331			}
2332		} else {
2333			if (callback != null) {
2334				callback.error(R.string.not_connected_try_again, null);
2335			}
2336		}
2337	}
2338
2339	public void fetchConferenceConfiguration(final Conversation conversation) {
2340		fetchConferenceConfiguration(conversation, null);
2341	}
2342
2343	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2344		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2345		request.setTo(conversation.getJid().toBareJid());
2346		request.query("http://jabber.org/protocol/disco#info");
2347		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2348			@Override
2349			public void onIqPacketReceived(Account account, IqPacket packet) {
2350				Element query = packet.findChild("query","http://jabber.org/protocol/disco#info");
2351				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2352					ArrayList<String> features = new ArrayList<>();
2353					for (Element child : query.getChildren()) {
2354						if (child != null && child.getName().equals("feature")) {
2355							String var = child.getAttribute("var");
2356							if (var != null) {
2357								features.add(var);
2358							}
2359						}
2360					}
2361					Element form = query.findChild("x", "jabber:x:data");
2362					if (form != null) {
2363						conversation.getMucOptions().updateFormData(Data.parse(form));
2364					}
2365					conversation.getMucOptions().updateFeatures(features);
2366					if (callback != null) {
2367						callback.onConferenceConfigurationFetched(conversation);
2368					}
2369					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetched muc configuration for "+conversation.getJid().toBareJid()+" - "+features.toString());
2370					updateConversationUi();
2371				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
2372					if (callback != null) {
2373						callback.onFetchFailed(conversation, packet.getError());
2374					}
2375				}
2376			}
2377		});
2378	}
2379
2380	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
2381		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2382		request.setTo(conversation.getJid().toBareJid());
2383		request.query("http://jabber.org/protocol/muc#owner");
2384		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2385			@Override
2386			public void onIqPacketReceived(Account account, IqPacket packet) {
2387				if (packet.getType() == IqPacket.TYPE.RESULT) {
2388					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
2389					for (Field field : data.getFields()) {
2390						if (options.containsKey(field.getFieldName())) {
2391							field.setValue(options.getString(field.getFieldName()));
2392						}
2393					}
2394					data.submit();
2395					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2396					set.setTo(conversation.getJid().toBareJid());
2397					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2398					sendIqPacket(account, set, new OnIqPacketReceived() {
2399						@Override
2400						public void onIqPacketReceived(Account account, IqPacket packet) {
2401							if (callback != null) {
2402								if (packet.getType() == IqPacket.TYPE.RESULT) {
2403									callback.onPushSucceeded();
2404								} else {
2405									callback.onPushFailed();
2406								}
2407							}
2408						}
2409					});
2410				} else {
2411					if (callback != null) {
2412						callback.onPushFailed();
2413					}
2414				}
2415			}
2416		});
2417	}
2418
2419	public void pushSubjectToConference(final Conversation conference, final String subject) {
2420		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2421		this.sendMessagePacket(conference.getAccount(), packet);
2422		final MucOptions mucOptions = conference.getMucOptions();
2423		final MucOptions.User self = mucOptions.getSelf();
2424		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2425			Bundle options = new Bundle();
2426			options.putString("muc#roomconfig_persistentroom", "1");
2427			this.pushConferenceConfiguration(conference, options, null);
2428		}
2429	}
2430
2431	public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2432		final Jid jid = user.toBareJid();
2433		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2434		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2435			@Override
2436			public void onIqPacketReceived(Account account, IqPacket packet) {
2437				if (packet.getType() == IqPacket.TYPE.RESULT) {
2438					conference.getMucOptions().changeAffiliation(jid, affiliation);
2439					getAvatarService().clear(conference);
2440					callback.onAffiliationChangedSuccessful(jid);
2441				} else {
2442					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2443				}
2444			}
2445		});
2446	}
2447
2448	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2449		List<Jid> jids = new ArrayList<>();
2450		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2451			if (user.getAffiliation() == before && user.getRealJid() != null) {
2452				jids.add(user.getRealJid());
2453			}
2454		}
2455		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2456		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2457	}
2458
2459	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2460		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2461		Log.d(Config.LOGTAG, request.toString());
2462		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2463			@Override
2464			public void onIqPacketReceived(Account account, IqPacket packet) {
2465				Log.d(Config.LOGTAG, packet.toString());
2466				if (packet.getType() == IqPacket.TYPE.RESULT) {
2467					callback.onRoleChangedSuccessful(nick);
2468				} else {
2469					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2470				}
2471			}
2472		});
2473	}
2474
2475	private void disconnect(Account account, boolean force) {
2476		if ((account.getStatus() == Account.State.ONLINE)
2477				|| (account.getStatus() == Account.State.DISABLED)) {
2478			final XmppConnection connection = account.getXmppConnection();
2479			if (!force) {
2480				List<Conversation> conversations = getConversations();
2481				for (Conversation conversation : conversations) {
2482					if (conversation.getAccount() == account) {
2483						if (conversation.getMode() == Conversation.MODE_MULTI) {
2484							leaveMuc(conversation, true);
2485						} else {
2486							if (conversation.endOtrIfNeeded()) {
2487								Log.d(Config.LOGTAG, account.getJid().toBareJid()
2488										+ ": ended otr session with "
2489										+ conversation.getJid());
2490							}
2491						}
2492					}
2493				}
2494				sendOfflinePresence(account);
2495			}
2496			connection.disconnect(force);
2497		}
2498	}
2499
2500	@Override
2501	public IBinder onBind(Intent intent) {
2502		return mBinder;
2503	}
2504
2505	public void updateMessage(Message message) {
2506		databaseBackend.updateMessage(message);
2507		updateConversationUi();
2508	}
2509
2510	public void updateMessage(Message message, String uuid) {
2511		databaseBackend.updateMessage(message, uuid);
2512		updateConversationUi();
2513	}
2514
2515	protected void syncDirtyContacts(Account account) {
2516		for (Contact contact : account.getRoster().getContacts()) {
2517			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2518				pushContactToServer(contact);
2519			}
2520			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2521				deleteContactOnServer(contact);
2522			}
2523		}
2524	}
2525
2526	public void createContact(Contact contact) {
2527		boolean autoGrant = getPreferences().getBoolean("grant_new_contacts", true);
2528		if (autoGrant) {
2529			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2530			contact.setOption(Contact.Options.ASKING);
2531		}
2532		pushContactToServer(contact);
2533	}
2534
2535	public void onOtrSessionEstablished(Conversation conversation) {
2536		final Account account = conversation.getAccount();
2537		final Session otrSession = conversation.getOtrSession();
2538		Log.d(Config.LOGTAG,
2539				account.getJid().toBareJid() + " otr session established with "
2540						+ conversation.getJid() + "/"
2541						+ otrSession.getSessionID().getUserID());
2542		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2543
2544			@Override
2545			public void onMessageFound(Message message) {
2546				SessionID id = otrSession.getSessionID();
2547				try {
2548					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2549				} catch (InvalidJidException e) {
2550					return;
2551				}
2552				if (message.needsUploading()) {
2553					mJingleConnectionManager.createNewConnection(message);
2554				} else {
2555					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2556					if (outPacket != null) {
2557						mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2558						message.setStatus(Message.STATUS_SEND);
2559						databaseBackend.updateMessage(message);
2560						sendMessagePacket(account, outPacket);
2561					}
2562				}
2563				updateConversationUi();
2564			}
2565		});
2566	}
2567
2568	public boolean renewSymmetricKey(Conversation conversation) {
2569		Account account = conversation.getAccount();
2570		byte[] symmetricKey = new byte[32];
2571		this.mRandom.nextBytes(symmetricKey);
2572		Session otrSession = conversation.getOtrSession();
2573		if (otrSession != null) {
2574			MessagePacket packet = new MessagePacket();
2575			packet.setType(MessagePacket.TYPE_CHAT);
2576			packet.setFrom(account.getJid());
2577			MessageGenerator.addMessageHints(packet);
2578			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2579					+ otrSession.getSessionID().getUserID());
2580			try {
2581				packet.setBody(otrSession
2582						.transformSending(CryptoHelper.FILETRANSFER
2583								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
2584				sendMessagePacket(account, packet);
2585				conversation.setSymmetricKey(symmetricKey);
2586				return true;
2587			} catch (OtrException e) {
2588				return false;
2589			}
2590		}
2591		return false;
2592	}
2593
2594	public void pushContactToServer(final Contact contact) {
2595		contact.resetOption(Contact.Options.DIRTY_DELETE);
2596		contact.setOption(Contact.Options.DIRTY_PUSH);
2597		final Account account = contact.getAccount();
2598		if (account.getStatus() == Account.State.ONLINE) {
2599			final boolean ask = contact.getOption(Contact.Options.ASKING);
2600			final boolean sendUpdates = contact
2601					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2602					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2603			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2604			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
2605			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2606			if (sendUpdates) {
2607				sendPresencePacket(account,
2608						mPresenceGenerator.sendPresenceUpdatesTo(contact));
2609			}
2610			if (ask) {
2611				sendPresencePacket(account,
2612						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2613			}
2614		}
2615	}
2616
2617	public void publishAvatar(Account account, Uri image, UiCallback<Avatar> callback) {
2618		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2619		final int size = Config.AVATAR_SIZE;
2620		final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2621		if (avatar != null) {
2622			avatar.height = size;
2623			avatar.width = size;
2624			if (format.equals(Bitmap.CompressFormat.WEBP)) {
2625				avatar.type = "image/webp";
2626			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2627				avatar.type = "image/jpeg";
2628			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
2629				avatar.type = "image/png";
2630			}
2631			if (!getFileBackend().save(avatar)) {
2632				callback.error(R.string.error_saving_avatar, avatar);
2633				return;
2634			}
2635			publishAvatar(account, avatar, callback);
2636		} else {
2637			callback.error(R.string.error_publish_avatar_converting, null);
2638		}
2639	}
2640
2641	public void publishAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2642		final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2643		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2644
2645			@Override
2646			public void onIqPacketReceived(Account account, IqPacket result) {
2647				if (result.getType() == IqPacket.TYPE.RESULT) {
2648					final IqPacket packet = XmppConnectionService.this.mIqGenerator
2649							.publishAvatarMetadata(avatar);
2650					sendIqPacket(account, packet, new OnIqPacketReceived() {
2651						@Override
2652						public void onIqPacketReceived(Account account, IqPacket result) {
2653							if (result.getType() == IqPacket.TYPE.RESULT) {
2654								if (account.setAvatar(avatar.getFilename())) {
2655									getAvatarService().clear(account);
2656									databaseBackend.updateAccount(account);
2657								}
2658								if (callback != null) {
2659									callback.success(avatar);
2660								} else {
2661									Log.d(Config.LOGTAG,account.getJid().toBareJid()+": published avatar");
2662								}
2663							} else {
2664								if (callback != null) {
2665									callback.error(
2666											R.string.error_publish_avatar_server_reject,
2667											avatar);
2668								}
2669							}
2670						}
2671					});
2672				} else {
2673					if (callback != null) {
2674						callback.error(
2675								R.string.error_publish_avatar_server_reject,
2676								avatar);
2677					}
2678				}
2679			}
2680		});
2681	}
2682
2683	public void republishAvatarIfNeeded(Account account) {
2684		if (account.getAxolotlService().isPepBroken()) {
2685			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": skipping republication of avatar because pep is broken");
2686			return;
2687		}
2688		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2689		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2690
2691			private Avatar parseAvatar(IqPacket packet) {
2692				Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2693				if (pubsub != null) {
2694					Element items = pubsub.findChild("items");
2695					if (items != null) {
2696						return Avatar.parseMetadata(items);
2697					}
2698				}
2699				return null;
2700			}
2701
2702			private boolean errorIsItemNotFound(IqPacket packet) {
2703				Element error = packet.findChild("error");
2704				return packet.getType() == IqPacket.TYPE.ERROR
2705						&& error != null
2706						&& error.hasChild("item-not-found");
2707			}
2708
2709			@Override
2710			public void onIqPacketReceived(Account account, IqPacket packet) {
2711				if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2712					Avatar serverAvatar = parseAvatar(packet);
2713					if (serverAvatar == null && account.getAvatar() != null) {
2714						Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2715						if (avatar != null) {
2716							Log.d(Config.LOGTAG,account.getJid().toBareJid()+": avatar on server was null. republishing");
2717							publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2718						} else {
2719							Log.e(Config.LOGTAG, account.getJid().toBareJid()+": error rereading avatar");
2720						}
2721					}
2722				}
2723			}
2724		});
2725	}
2726
2727	public void fetchAvatar(Account account, Avatar avatar) {
2728		fetchAvatar(account, avatar, null);
2729	}
2730
2731	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2732		final String KEY = generateFetchKey(account, avatar);
2733		synchronized (this.mInProgressAvatarFetches) {
2734			if (!this.mInProgressAvatarFetches.contains(KEY)) {
2735				switch (avatar.origin) {
2736					case PEP:
2737						this.mInProgressAvatarFetches.add(KEY);
2738						fetchAvatarPep(account, avatar, callback);
2739						break;
2740					case VCARD:
2741						this.mInProgressAvatarFetches.add(KEY);
2742						fetchAvatarVcard(account, avatar, callback);
2743						break;
2744				}
2745			}
2746		}
2747	}
2748
2749	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2750		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2751		sendIqPacket(account, packet, new OnIqPacketReceived() {
2752
2753			@Override
2754			public void onIqPacketReceived(Account account, IqPacket result) {
2755				synchronized (mInProgressAvatarFetches) {
2756					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2757				}
2758				final String ERROR = account.getJid().toBareJid()
2759						+ ": fetching avatar for " + avatar.owner + " failed ";
2760				if (result.getType() == IqPacket.TYPE.RESULT) {
2761					avatar.image = mIqParser.avatarData(result);
2762					if (avatar.image != null) {
2763						if (getFileBackend().save(avatar)) {
2764							if (account.getJid().toBareJid().equals(avatar.owner)) {
2765								if (account.setAvatar(avatar.getFilename())) {
2766									databaseBackend.updateAccount(account);
2767								}
2768								getAvatarService().clear(account);
2769								updateConversationUi();
2770								updateAccountUi();
2771							} else {
2772								Contact contact = account.getRoster()
2773										.getContact(avatar.owner);
2774								contact.setAvatar(avatar);
2775								getAvatarService().clear(contact);
2776								updateConversationUi();
2777								updateRosterUi();
2778							}
2779							if (callback != null) {
2780								callback.success(avatar);
2781							}
2782							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2783									+ ": successfully fetched pep avatar for " + avatar.owner);
2784							return;
2785						}
2786					} else {
2787
2788						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2789					}
2790				} else {
2791					Element error = result.findChild("error");
2792					if (error == null) {
2793						Log.d(Config.LOGTAG, ERROR + "(server error)");
2794					} else {
2795						Log.d(Config.LOGTAG, ERROR + error.toString());
2796					}
2797				}
2798				if (callback != null) {
2799					callback.error(0, null);
2800				}
2801
2802			}
2803		});
2804	}
2805
2806	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2807		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2808		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2809			@Override
2810			public void onIqPacketReceived(Account account, IqPacket packet) {
2811				synchronized (mInProgressAvatarFetches) {
2812					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2813				}
2814				if (packet.getType() == IqPacket.TYPE.RESULT) {
2815					Element vCard = packet.findChild("vCard", "vcard-temp");
2816					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2817					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2818					if (image != null) {
2819						avatar.image = image;
2820						if (getFileBackend().save(avatar)) {
2821							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2822									+ ": successfully fetched vCard avatar for " + avatar.owner);
2823							if (avatar.owner.isBareJid()) {
2824								if (account.getJid().toBareJid().equals(avatar.owner) && account.getAvatar() == null) {
2825									Log.d(Config.LOGTAG,account.getJid().toBareJid()+": had no avatar. replacing with vcard");
2826									account.setAvatar(avatar.getFilename());
2827									databaseBackend.updateAccount(account);
2828									getAvatarService().clear(account);
2829									updateAccountUi();
2830								} else {
2831									Contact contact = account.getRoster().getContact(avatar.owner);
2832									contact.setAvatar(avatar);
2833									getAvatarService().clear(contact);
2834									updateRosterUi();
2835								}
2836								updateConversationUi();
2837							} else {
2838								Conversation conversation = find(account, avatar.owner.toBareJid());
2839								if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
2840									MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
2841									if (user != null) {
2842										if (user.setAvatar(avatar)) {
2843											getAvatarService().clear(user);
2844											updateConversationUi();
2845											updateMucRosterUi();
2846										}
2847									}
2848								}
2849							}
2850						}
2851					}
2852				}
2853			}
2854		});
2855	}
2856
2857	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2858		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2859		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2860
2861			@Override
2862			public void onIqPacketReceived(Account account, IqPacket packet) {
2863				if (packet.getType() == IqPacket.TYPE.RESULT) {
2864					Element pubsub = packet.findChild("pubsub","http://jabber.org/protocol/pubsub");
2865					if (pubsub != null) {
2866						Element items = pubsub.findChild("items");
2867						if (items != null) {
2868							Avatar avatar = Avatar.parseMetadata(items);
2869							if (avatar != null) {
2870								avatar.owner = account.getJid().toBareJid();
2871								if (fileBackend.isAvatarCached(avatar)) {
2872									if (account.setAvatar(avatar.getFilename())) {
2873										databaseBackend.updateAccount(account);
2874									}
2875									getAvatarService().clear(account);
2876									callback.success(avatar);
2877								} else {
2878									fetchAvatarPep(account, avatar, callback);
2879								}
2880								return;
2881							}
2882						}
2883					}
2884				}
2885				callback.error(0, null);
2886			}
2887		});
2888	}
2889
2890	public void deleteContactOnServer(Contact contact) {
2891		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2892		contact.resetOption(Contact.Options.DIRTY_PUSH);
2893		contact.setOption(Contact.Options.DIRTY_DELETE);
2894		Account account = contact.getAccount();
2895		if (account.getStatus() == Account.State.ONLINE) {
2896			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2897			Element item = iq.query(Xmlns.ROSTER).addChild("item");
2898			item.setAttribute("jid", contact.getJid().toString());
2899			item.setAttribute("subscription", "remove");
2900			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2901		}
2902	}
2903
2904	public void updateConversation(final Conversation conversation) {
2905		mDatabaseExecutor.execute(new Runnable() {
2906			@Override
2907			public void run() {
2908				databaseBackend.updateConversation(conversation);
2909			}
2910		});
2911	}
2912
2913	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2914		synchronized (account) {
2915			XmppConnection connection = account.getXmppConnection();
2916			if (connection == null) {
2917				connection = createConnection(account);
2918				account.setXmppConnection(connection);
2919			}
2920			boolean hasInternet = hasInternetConnection();
2921			if (!account.isOptionSet(Account.OPTION_DISABLED) && hasInternet) {
2922				if (!force) {
2923					disconnect(account, false);
2924				}
2925				Thread thread = new Thread(connection);
2926				connection.setInteractive(interactive);
2927				connection.prepareNewConnection();
2928				connection.interrupt();
2929				thread.start();
2930				scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2931			} else {
2932				disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
2933				account.getRoster().clearPresences();
2934				connection.resetEverything();
2935				account.getAxolotlService().resetBrokenness();
2936				if (!hasInternet) {
2937					account.setStatus(Account.State.NO_INTERNET);
2938				}
2939			}
2940		}
2941	}
2942
2943	public void reconnectAccountInBackground(final Account account) {
2944		new Thread(new Runnable() {
2945			@Override
2946			public void run() {
2947				reconnectAccount(account, false, true);
2948			}
2949		}).start();
2950	}
2951
2952	public void invite(Conversation conversation, Jid contact) {
2953		Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
2954		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2955		sendMessagePacket(conversation.getAccount(), packet);
2956	}
2957
2958	public void directInvite(Conversation conversation, Jid jid) {
2959		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2960		sendMessagePacket(conversation.getAccount(), packet);
2961	}
2962
2963	public void resetSendingToWaiting(Account account) {
2964		for (Conversation conversation : getConversations()) {
2965			if (conversation.getAccount() == account) {
2966				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2967
2968					@Override
2969					public void onMessageFound(Message message) {
2970						markMessage(message, Message.STATUS_WAITING);
2971					}
2972				});
2973			}
2974		}
2975	}
2976
2977	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2978		return markMessage(account, recipient, uuid, status, null);
2979	}
2980
2981	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
2982		if (uuid == null) {
2983			return null;
2984		}
2985		for (Conversation conversation : getConversations()) {
2986			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2987				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
2988				if (message != null) {
2989					markMessage(message, status, errorMessage);
2990				}
2991				return message;
2992			}
2993		}
2994		return null;
2995	}
2996
2997	public boolean markMessage(Conversation conversation, String uuid, int status) {
2998		if (uuid == null) {
2999			return false;
3000		} else {
3001			Message message = conversation.findSentMessageWithUuid(uuid);
3002			if (message != null) {
3003				markMessage(message, status);
3004				return true;
3005			} else {
3006				return false;
3007			}
3008		}
3009	}
3010
3011	public void markMessage(Message message, int status) {
3012		markMessage(message, status, null);
3013	}
3014
3015
3016	public void markMessage(Message message, int status, String errorMessage) {
3017		if (status == Message.STATUS_SEND_FAILED
3018				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
3019				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
3020			return;
3021		}
3022		message.setErrorMessage(errorMessage);
3023		message.setStatus(status);
3024		databaseBackend.updateMessage(message);
3025		updateConversationUi();
3026	}
3027
3028	public SharedPreferences getPreferences() {
3029		return PreferenceManager
3030				.getDefaultSharedPreferences(getApplicationContext());
3031	}
3032
3033	public boolean confirmMessages() {
3034		return getPreferences().getBoolean("confirm_messages", true);
3035	}
3036
3037	public boolean allowMessageCorrection() {
3038		return getPreferences().getBoolean("allow_message_correction", true);
3039	}
3040
3041	public boolean sendChatStates() {
3042		return getPreferences().getBoolean("chat_states", false);
3043	}
3044
3045	public boolean saveEncryptedMessages() {
3046		return !getPreferences().getBoolean("dont_save_encrypted", false);
3047	}
3048
3049	private boolean respectAutojoin() {
3050		return getPreferences().getBoolean("autojoin", true);
3051	}
3052
3053	public boolean indicateReceived() {
3054		return getPreferences().getBoolean("indicate_received", false);
3055	}
3056
3057	public boolean useTorToConnect() {
3058		return Config.FORCE_ORBOT || getPreferences().getBoolean("use_tor", false);
3059	}
3060
3061	public boolean showExtendedConnectionOptions() {
3062		return getPreferences().getBoolean("show_connection_options", false);
3063	}
3064
3065	public boolean broadcastLastActivity() {
3066		return getPreferences().getBoolean("last_activity", false);
3067	}
3068
3069	public int unreadCount() {
3070		int count = 0;
3071		for (Conversation conversation : getConversations()) {
3072			count += conversation.unreadCount();
3073		}
3074		return count;
3075	}
3076
3077
3078	public void showErrorToastInUi(int resId) {
3079		if (mOnShowErrorToast != null) {
3080			mOnShowErrorToast.onShowErrorToast(resId);
3081		}
3082	}
3083
3084	public void updateConversationUi() {
3085		if (mOnConversationUpdate != null) {
3086			mOnConversationUpdate.onConversationUpdate();
3087		}
3088	}
3089
3090	public void updateAccountUi() {
3091		if (mOnAccountUpdate != null) {
3092			mOnAccountUpdate.onAccountUpdate();
3093		}
3094	}
3095
3096	public void updateRosterUi() {
3097		if (mOnRosterUpdate != null) {
3098			mOnRosterUpdate.onRosterUpdate();
3099		}
3100	}
3101
3102	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3103		if (mOnCaptchaRequested != null) {
3104			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3105			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3106					(int) (captcha.getHeight() * metrics.scaledDensity), false);
3107
3108			mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
3109			return true;
3110		}
3111		return false;
3112	}
3113
3114	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3115		if (mOnUpdateBlocklist != null) {
3116			mOnUpdateBlocklist.OnUpdateBlocklist(status);
3117		}
3118	}
3119
3120	public void updateMucRosterUi() {
3121		if (mOnMucRosterUpdate != null) {
3122			mOnMucRosterUpdate.onMucRosterUpdate();
3123		}
3124	}
3125
3126	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3127		if (mOnKeyStatusUpdated != null) {
3128			mOnKeyStatusUpdated.onKeyStatusUpdated(report);
3129		}
3130	}
3131
3132	public Account findAccountByJid(final Jid accountJid) {
3133		for (Account account : this.accounts) {
3134			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
3135				return account;
3136			}
3137		}
3138		return null;
3139	}
3140
3141	public Conversation findConversationByUuid(String uuid) {
3142		for (Conversation conversation : getConversations()) {
3143			if (conversation.getUuid().equals(uuid)) {
3144				return conversation;
3145			}
3146		}
3147		return null;
3148	}
3149
3150	public boolean markRead(final Conversation conversation) {
3151		return markRead(conversation,true);
3152	}
3153
3154	public boolean markRead(final Conversation conversation, boolean clear) {
3155		if (clear) {
3156			mNotificationService.clear(conversation);
3157		}
3158		final List<Message> readMessages = conversation.markRead();
3159		if (readMessages.size() > 0) {
3160			Runnable runnable = new Runnable() {
3161				@Override
3162				public void run() {
3163					for (Message message : readMessages) {
3164						databaseBackend.updateMessage(message);
3165					}
3166				}
3167			};
3168			mDatabaseExecutor.execute(runnable);
3169			updateUnreadCountBadge();
3170			return true;
3171		} else {
3172			return false;
3173		}
3174	}
3175
3176	public synchronized void updateUnreadCountBadge() {
3177		int count = unreadCount();
3178		if (unreadCount != count) {
3179			Log.d(Config.LOGTAG, "update unread count to " + count);
3180			if (count > 0) {
3181				ShortcutBadger.applyCount(getApplicationContext(), count);
3182			} else {
3183				ShortcutBadger.removeCount(getApplicationContext());
3184			}
3185			unreadCount = count;
3186		}
3187	}
3188
3189	public void sendReadMarker(final Conversation conversation) {
3190		final Message markable = conversation.getLatestMarkableMessage();
3191		if (this.markRead(conversation)) {
3192			updateConversationUi();
3193		}
3194		if (confirmMessages()
3195				&& markable != null
3196				&& markable.trusted()
3197				&& markable.getRemoteMsgId() != null) {
3198			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
3199			Account account = conversation.getAccount();
3200			final Jid to = markable.getCounterpart();
3201			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
3202			this.sendMessagePacket(conversation.getAccount(), packet);
3203		}
3204	}
3205
3206	public SecureRandom getRNG() {
3207		return this.mRandom;
3208	}
3209
3210	public MemorizingTrustManager getMemorizingTrustManager() {
3211		return this.mMemorizingTrustManager;
3212	}
3213
3214	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
3215		this.mMemorizingTrustManager = trustManager;
3216	}
3217
3218	public void updateMemorizingTrustmanager() {
3219		final MemorizingTrustManager tm;
3220		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
3221		if (dontTrustSystemCAs) {
3222			tm = new MemorizingTrustManager(getApplicationContext(), null);
3223		} else {
3224			tm = new MemorizingTrustManager(getApplicationContext());
3225		}
3226		setMemorizingTrustManager(tm);
3227	}
3228
3229	public PowerManager getPowerManager() {
3230		return this.pm;
3231	}
3232
3233	public LruCache<String, Bitmap> getBitmapCache() {
3234		return this.mBitmapCache;
3235	}
3236
3237	public void syncRosterToDisk(final Account account) {
3238		Runnable runnable = new Runnable() {
3239
3240			@Override
3241			public void run() {
3242				databaseBackend.writeRoster(account.getRoster());
3243			}
3244		};
3245		mDatabaseExecutor.execute(runnable);
3246
3247	}
3248
3249	public List<String> getKnownHosts() {
3250		final List<String> hosts = new ArrayList<>();
3251		for (final Account account : getAccounts()) {
3252			if (!hosts.contains(account.getServer().toString())) {
3253				hosts.add(account.getServer().toString());
3254			}
3255			for (final Contact contact : account.getRoster().getContacts()) {
3256				if (contact.showInRoster()) {
3257					final String server = contact.getServer().toString();
3258					if (server != null && !hosts.contains(server)) {
3259						hosts.add(server);
3260					}
3261				}
3262			}
3263		}
3264		if(Config.DOMAIN_LOCK != null && !hosts.contains(Config.DOMAIN_LOCK)) {
3265			hosts.add(Config.DOMAIN_LOCK);
3266		}
3267		if(Config.MAGIC_CREATE_DOMAIN != null && !hosts.contains(Config.MAGIC_CREATE_DOMAIN)) {
3268			hosts.add(Config.MAGIC_CREATE_DOMAIN);
3269		}
3270		return hosts;
3271	}
3272
3273	public List<String> getKnownConferenceHosts() {
3274		final ArrayList<String> mucServers = new ArrayList<>();
3275		for (final Account account : accounts) {
3276			if (account.getXmppConnection() != null) {
3277				final String server = account.getXmppConnection().getMucServer();
3278				if (server != null && !mucServers.contains(server)) {
3279					mucServers.add(server);
3280				}
3281			}
3282		}
3283		return mucServers;
3284	}
3285
3286	public void sendMessagePacket(Account account, MessagePacket packet) {
3287		XmppConnection connection = account.getXmppConnection();
3288		if (connection != null) {
3289			connection.sendMessagePacket(packet);
3290		}
3291	}
3292
3293	public void sendPresencePacket(Account account, PresencePacket packet) {
3294		XmppConnection connection = account.getXmppConnection();
3295		if (connection != null) {
3296			connection.sendPresencePacket(packet);
3297		}
3298	}
3299
3300	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3301		final XmppConnection connection = account.getXmppConnection();
3302		if (connection != null) {
3303			IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3304			connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener);
3305		}
3306	}
3307
3308	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3309		final XmppConnection connection = account.getXmppConnection();
3310		if (connection != null) {
3311			connection.sendIqPacket(packet, callback);
3312		}
3313	}
3314
3315	public void sendPresence(final Account account) {
3316		sendPresence(account, checkListeners() && broadcastLastActivity());
3317	}
3318
3319	private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3320		PresencePacket packet;
3321		if (manuallyChangePresence()) {
3322			packet =  mPresenceGenerator.selfPresence(account, account.getPresenceStatus());
3323			String message = account.getPresenceStatusMessage();
3324			if (message != null && !message.isEmpty()) {
3325				packet.addChild(new Element("status").setContent(message));
3326			}
3327		} else {
3328			packet = mPresenceGenerator.selfPresence(account, getTargetPresence());
3329		}
3330		if (mLastActivity > 0 && includeIdleTimestamp) {
3331			long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3332			packet.addChild("idle","urn:xmpp:idle:1").setAttribute("since", AbstractGenerator.getTimestamp(since));
3333		}
3334		sendPresencePacket(account, packet);
3335	}
3336
3337	private void deactivateGracePeriod() {
3338		for(Account account : getAccounts()) {
3339			account.deactivateGracePeriod();
3340		}
3341	}
3342
3343	public void refreshAllPresences() {
3344		boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3345		for (Account account : getAccounts()) {
3346			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3347				sendPresence(account, includeIdleTimestamp);
3348			}
3349		}
3350	}
3351
3352	private void refreshAllGcmTokens() {
3353		for(Account account : getAccounts()) {
3354			if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3355				mPushManagementService.registerPushTokenOnServer(account);
3356			}
3357		}
3358	}
3359
3360	private void sendOfflinePresence(final Account account) {
3361		Log.d(Config.LOGTAG,account.getJid().toBareJid()+": sending offline presence");
3362		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3363	}
3364
3365	public MessageGenerator getMessageGenerator() {
3366		return this.mMessageGenerator;
3367	}
3368
3369	public PresenceGenerator getPresenceGenerator() {
3370		return this.mPresenceGenerator;
3371	}
3372
3373	public IqGenerator getIqGenerator() {
3374		return this.mIqGenerator;
3375	}
3376
3377	public IqParser getIqParser() {
3378		return this.mIqParser;
3379	}
3380
3381	public JingleConnectionManager getJingleConnectionManager() {
3382		return this.mJingleConnectionManager;
3383	}
3384
3385	public MessageArchiveService getMessageArchiveService() {
3386		return this.mMessageArchiveService;
3387	}
3388
3389	public List<Contact> findContacts(Jid jid) {
3390		ArrayList<Contact> contacts = new ArrayList<>();
3391		for (Account account : getAccounts()) {
3392			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3393				Contact contact = account.getRoster().getContactFromRoster(jid);
3394				if (contact != null) {
3395					contacts.add(contact);
3396				}
3397			}
3398		}
3399		return contacts;
3400	}
3401
3402	public Conversation findFirstMuc(Jid jid) {
3403		for(Conversation conversation : getConversations()) {
3404			if (conversation.getJid().toBareJid().equals(jid.toBareJid())
3405					&& conversation.getMode() == Conversation.MODE_MULTI) {
3406				return conversation;
3407			}
3408		}
3409		return null;
3410	}
3411
3412	public NotificationService getNotificationService() {
3413		return this.mNotificationService;
3414	}
3415
3416	public HttpConnectionManager getHttpConnectionManager() {
3417		return this.mHttpConnectionManager;
3418	}
3419
3420	public void resendFailedMessages(final Message message) {
3421		final Collection<Message> messages = new ArrayList<>();
3422		Message current = message;
3423		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3424			messages.add(current);
3425			if (current.mergeable(current.next())) {
3426				current = current.next();
3427			} else {
3428				break;
3429			}
3430		}
3431		for (final Message msg : messages) {
3432			msg.setTime(System.currentTimeMillis());
3433			markMessage(msg, Message.STATUS_WAITING);
3434			this.resendMessage(msg, false);
3435		}
3436	}
3437
3438	public void clearConversationHistory(final Conversation conversation) {
3439		conversation.clearMessages();
3440		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3441		conversation.setLastClearHistory(System.currentTimeMillis());
3442		Runnable runnable = new Runnable() {
3443			@Override
3444			public void run() {
3445				databaseBackend.deleteMessagesInConversation(conversation);
3446				databaseBackend.updateConversation(conversation);
3447			}
3448		};
3449		mDatabaseExecutor.execute(runnable);
3450	}
3451
3452	public void sendBlockRequest(final Blockable blockable, boolean reportSpam) {
3453		if (blockable != null && blockable.getBlockedJid() != null) {
3454			final Jid jid = blockable.getBlockedJid();
3455			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), new OnIqPacketReceived() {
3456
3457				@Override
3458				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3459					if (packet.getType() == IqPacket.TYPE.RESULT) {
3460						account.getBlocklist().add(jid);
3461						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3462					}
3463				}
3464			});
3465		}
3466	}
3467
3468	public void sendUnblockRequest(final Blockable blockable) {
3469		if (blockable != null && blockable.getJid() != null) {
3470			final Jid jid = blockable.getBlockedJid();
3471			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3472				@Override
3473				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3474					if (packet.getType() == IqPacket.TYPE.RESULT) {
3475						account.getBlocklist().remove(jid);
3476						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3477					}
3478				}
3479			});
3480		}
3481	}
3482
3483	public void publishDisplayName(Account account) {
3484		String displayName = account.getDisplayName();
3485		if (displayName != null && !displayName.isEmpty()) {
3486			IqPacket publish = mIqGenerator.publishNick(displayName);
3487			sendIqPacket(account, publish, new OnIqPacketReceived() {
3488				@Override
3489				public void onIqPacketReceived(Account account, IqPacket packet) {
3490					if (packet.getType() == IqPacket.TYPE.ERROR) {
3491						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not publish nick");
3492					}
3493				}
3494			});
3495		}
3496	}
3497
3498	public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
3499		ServiceDiscoveryResult result = discoCache.get(key);
3500		if (result != null) {
3501			return result;
3502		} else {
3503			result = databaseBackend.findDiscoveryResult(key.first, key.second);
3504			if (result != null) {
3505				discoCache.put(key, result);
3506			}
3507			return result;
3508		}
3509	}
3510
3511	public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3512		final Pair<String,String> key = new Pair<>(presence.getHash(), presence.getVer());
3513		ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3514		if (disco != null) {
3515			presence.setServiceDiscoveryResult(disco);
3516		} else {
3517			if (!account.inProgressDiscoFetches.contains(key)) {
3518				account.inProgressDiscoFetches.add(key);
3519				IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3520				request.setTo(jid);
3521				request.query("http://jabber.org/protocol/disco#info");
3522				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": making disco request for "+key.second+" to "+jid);
3523				sendIqPacket(account, request, new OnIqPacketReceived() {
3524					@Override
3525					public void onIqPacketReceived(Account account, IqPacket discoPacket) {
3526						if (discoPacket.getType() == IqPacket.TYPE.RESULT) {
3527							ServiceDiscoveryResult disco = new ServiceDiscoveryResult(discoPacket);
3528							if (presence.getVer().equals(disco.getVer())) {
3529								databaseBackend.insertDiscoveryResult(disco);
3530								injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco);
3531							} else {
3532								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco.getVer());
3533							}
3534						}
3535						account.inProgressDiscoFetches.remove(key);
3536					}
3537				});
3538			}
3539		}
3540	}
3541
3542	private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3543		for(Contact contact : roster.getContacts()) {
3544			for(Presence presence : contact.getPresences().getPresences().values()) {
3545				if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3546					presence.setServiceDiscoveryResult(disco);
3547				}
3548			}
3549		}
3550	}
3551
3552	public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3553		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3554		request.addChild("prefs","urn:xmpp:mam:0");
3555		sendIqPacket(account, request, new OnIqPacketReceived() {
3556			@Override
3557			public void onIqPacketReceived(Account account, IqPacket packet) {
3558				Element prefs = packet.findChild("prefs","urn:xmpp:mam:0");
3559				if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3560					callback.onPreferencesFetched(prefs);
3561				} else {
3562					callback.onPreferencesFetchFailed();
3563				}
3564			}
3565		});
3566	}
3567
3568	public PushManagementService getPushManagementService() {
3569		return mPushManagementService;
3570	}
3571
3572	public Account getPendingAccount() {
3573		Account pending = null;
3574		for(Account account : getAccounts()) {
3575			if (account.isOptionSet(Account.OPTION_REGISTER)) {
3576				pending = account;
3577			} else {
3578				return null;
3579			}
3580		}
3581		return pending;
3582	}
3583
3584	public void changeStatus(Account account, Presence.Status status, String statusMessage, boolean send) {
3585		if (!statusMessage.isEmpty()) {
3586			databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3587		}
3588		changeStatusReal(account, status, statusMessage, send);
3589	}
3590
3591	private void changeStatusReal(Account account, Presence.Status status, String statusMessage, boolean send) {
3592		account.setPresenceStatus(status);
3593		account.setPresenceStatusMessage(statusMessage);
3594		databaseBackend.updateAccount(account);
3595		if (!account.isOptionSet(Account.OPTION_DISABLED) && send) {
3596			sendPresence(account);
3597		}
3598	}
3599
3600	public void changeStatus(Presence.Status status, String statusMessage) {
3601		if (!statusMessage.isEmpty()) {
3602			databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3603		}
3604		for(Account account : getAccounts()) {
3605			changeStatusReal(account, status, statusMessage, true);
3606		}
3607	}
3608
3609	public List<PresenceTemplate> getPresenceTemplates(Account account) {
3610		List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3611		for(PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3612			if (!templates.contains(template)) {
3613				templates.add(0, template);
3614			}
3615		}
3616		return templates;
3617	}
3618
3619	public void saveConversationAsBookmark(Conversation conversation, String name) {
3620		Account account = conversation.getAccount();
3621		Bookmark bookmark = new Bookmark(account, conversation.getJid().toBareJid());
3622		if (!conversation.getJid().isBareJid()) {
3623			bookmark.setNick(conversation.getJid().getResourcepart());
3624		}
3625		if (name != null && !name.trim().isEmpty()) {
3626			bookmark.setBookmarkName(name.trim());
3627		}
3628		bookmark.setAutojoin(getPreferences().getBoolean("autojoin",true));
3629		account.getBookmarks().add(bookmark);
3630		pushBookmarks(account);
3631		conversation.setBookmark(bookmark);
3632	}
3633
3634	public void clearStartTimeCounter() {
3635		mDatabaseExecutor.execute(new Runnable() {
3636			@Override
3637			public void run() {
3638				databaseBackend.clearStartTimeCounter(false);
3639			}
3640		});
3641	}
3642
3643	public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
3644		boolean needsRosterWrite = false;
3645		boolean performedVerification = false;
3646		final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
3647		for(XmppUri.Fingerprint fp : fingerprints) {
3648			if (fp.type == XmppUri.FingerprintType.OTR) {
3649				performedVerification |= contact.addOtrFingerprint(fp.fingerprint);
3650				needsRosterWrite |= performedVerification;
3651			} else if (fp.type == XmppUri.FingerprintType.OMEMO) {
3652				String fingerprint = "05"+fp.fingerprint.replaceAll("\\s","");
3653				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3654				if (fingerprintStatus != null) {
3655					if (!fingerprintStatus.isVerified()) {
3656						performedVerification = true;
3657						axolotlService.setFingerprintTrust(fingerprint,fingerprintStatus.toVerified());
3658					}
3659				} else {
3660					axolotlService.preVerifyFingerprint(contact,fingerprint);
3661				}
3662			}
3663		}
3664		if (needsRosterWrite) {
3665			syncRosterToDisk(contact.getAccount());
3666		}
3667		return performedVerification;
3668	}
3669
3670	public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
3671		final AxolotlService axolotlService = account.getAxolotlService();
3672		boolean verifiedSomething = false;
3673		for(XmppUri.Fingerprint fp : fingerprints) {
3674			if (fp.type == XmppUri.FingerprintType.OMEMO) {
3675				String fingerprint = "05"+fp.fingerprint.replaceAll("\\s","");
3676				Log.d(Config.LOGTAG,"trying to verify own fp="+fingerprint);
3677				FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3678				if (fingerprintStatus != null) {
3679					if (!fingerprintStatus.isVerified()) {
3680						axolotlService.setFingerprintTrust(fingerprint,fingerprintStatus.toVerified());
3681						verifiedSomething = true;
3682					}
3683				} else {
3684					axolotlService.preVerifyFingerprint(account,fingerprint);
3685					verifiedSomething = true;
3686				}
3687			}
3688		}
3689		return verifiedSomething;
3690	}
3691
3692	public boolean blindTrustBeforeVerification() {
3693		return getPreferences().getBoolean(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, true);
3694	}
3695
3696	public interface OnMamPreferencesFetched {
3697		void onPreferencesFetched(Element prefs);
3698		void onPreferencesFetchFailed();
3699	}
3700
3701	public void pushMamPreferences(Account account, Element prefs) {
3702		IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3703		set.addChild(prefs);
3704		sendIqPacket(account, set, null);
3705	}
3706
3707	public interface OnAccountCreated {
3708		void onAccountCreated(Account account);
3709
3710		void informUser(int r);
3711	}
3712
3713	public interface OnMoreMessagesLoaded {
3714		void onMoreMessagesLoaded(int count, Conversation conversation);
3715
3716		void informUser(int r);
3717	}
3718
3719	public interface OnAccountPasswordChanged {
3720		void onPasswordChangeSucceeded();
3721
3722		void onPasswordChangeFailed();
3723	}
3724
3725	public interface OnAffiliationChanged {
3726		void onAffiliationChangedSuccessful(Jid jid);
3727
3728		void onAffiliationChangeFailed(Jid jid, int resId);
3729	}
3730
3731	public interface OnRoleChanged {
3732		void onRoleChangedSuccessful(String nick);
3733
3734		void onRoleChangeFailed(String nick, int resid);
3735	}
3736
3737	public interface OnConversationUpdate {
3738		void onConversationUpdate();
3739	}
3740
3741	public interface OnAccountUpdate {
3742		void onAccountUpdate();
3743	}
3744
3745	public interface OnCaptchaRequested {
3746		void onCaptchaRequested(Account account,
3747								String id,
3748								Data data,
3749								Bitmap captcha);
3750	}
3751
3752	public interface OnRosterUpdate {
3753		void onRosterUpdate();
3754	}
3755
3756	public interface OnMucRosterUpdate {
3757		void onMucRosterUpdate();
3758	}
3759
3760	public interface OnConferenceConfigurationFetched {
3761		void onConferenceConfigurationFetched(Conversation conversation);
3762
3763		void onFetchFailed(Conversation conversation, Element error);
3764	}
3765
3766	public interface OnConferenceJoined {
3767		void onConferenceJoined(Conversation conversation);
3768	}
3769
3770	public interface OnConferenceOptionsPushed {
3771		void onPushSucceeded();
3772
3773		void onPushFailed();
3774	}
3775
3776	public interface OnShowErrorToast {
3777		void onShowErrorToast(int resId);
3778	}
3779
3780	public class XmppConnectionBinder extends Binder {
3781		public XmppConnectionService getService() {
3782			return XmppConnectionService.this;
3783		}
3784	}
3785}