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