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