XmppConnectionService.java

   1package eu.siacs.conversations.services;
   2
   3import android.annotation.SuppressLint;
   4import android.app.AlarmManager;
   5import android.app.PendingIntent;
   6import android.app.Service;
   7import android.content.Context;
   8import android.content.Intent;
   9import android.content.SharedPreferences;
  10import android.database.ContentObserver;
  11import android.graphics.Bitmap;
  12import android.net.ConnectivityManager;
  13import android.net.NetworkInfo;
  14import android.net.Uri;
  15import android.os.Binder;
  16import android.os.Bundle;
  17import android.os.FileObserver;
  18import android.os.IBinder;
  19import android.os.Looper;
  20import android.os.PowerManager;
  21import android.os.PowerManager.WakeLock;
  22import android.os.SystemClock;
  23import android.preference.PreferenceManager;
  24import android.provider.ContactsContract;
  25import android.util.Log;
  26import android.util.LruCache;
  27
  28import net.java.otr4j.OtrException;
  29import net.java.otr4j.session.Session;
  30import net.java.otr4j.session.SessionID;
  31import net.java.otr4j.session.SessionImpl;
  32import net.java.otr4j.session.SessionStatus;
  33
  34import org.openintents.openpgp.util.OpenPgpApi;
  35import org.openintents.openpgp.util.OpenPgpServiceConnection;
  36
  37import java.math.BigInteger;
  38import java.security.SecureRandom;
  39import java.util.ArrayList;
  40import java.util.Arrays;
  41import java.util.Collection;
  42import java.util.Collections;
  43import java.util.Comparator;
  44import java.util.Hashtable;
  45import java.util.Iterator;
  46import java.util.List;
  47import java.util.Locale;
  48import java.util.Map;
  49import java.util.concurrent.CopyOnWriteArrayList;
  50
  51import de.duenndns.ssl.MemorizingTrustManager;
  52import eu.siacs.conversations.Config;
  53import eu.siacs.conversations.R;
  54import eu.siacs.conversations.crypto.PgpEngine;
  55import eu.siacs.conversations.entities.Account;
  56import eu.siacs.conversations.entities.Blockable;
  57import eu.siacs.conversations.entities.Bookmark;
  58import eu.siacs.conversations.entities.Contact;
  59import eu.siacs.conversations.entities.Conversation;
  60import eu.siacs.conversations.entities.Transferable;
  61import eu.siacs.conversations.entities.TransferablePlaceholder;
  62import eu.siacs.conversations.entities.Message;
  63import eu.siacs.conversations.entities.MucOptions;
  64import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
  65import eu.siacs.conversations.generator.IqGenerator;
  66import eu.siacs.conversations.generator.MessageGenerator;
  67import eu.siacs.conversations.generator.PresenceGenerator;
  68import eu.siacs.conversations.http.HttpConnectionManager;
  69import eu.siacs.conversations.parser.IqParser;
  70import eu.siacs.conversations.parser.MessageParser;
  71import eu.siacs.conversations.parser.PresenceParser;
  72import eu.siacs.conversations.persistance.DatabaseBackend;
  73import eu.siacs.conversations.persistance.FileBackend;
  74import eu.siacs.conversations.ui.UiCallback;
  75import eu.siacs.conversations.utils.CryptoHelper;
  76import eu.siacs.conversations.utils.ExceptionHelper;
  77import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
  78import eu.siacs.conversations.utils.PRNGFixes;
  79import eu.siacs.conversations.utils.PhoneHelper;
  80import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
  81import eu.siacs.conversations.utils.Xmlns;
  82import eu.siacs.conversations.xml.Element;
  83import eu.siacs.conversations.xmpp.OnBindListener;
  84import eu.siacs.conversations.xmpp.OnContactStatusChanged;
  85import eu.siacs.conversations.xmpp.OnIqPacketReceived;
  86import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
  87import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
  88import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
  89import eu.siacs.conversations.xmpp.OnStatusChanged;
  90import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  91import eu.siacs.conversations.xmpp.XmppConnection;
  92import eu.siacs.conversations.xmpp.chatstate.ChatState;
  93import eu.siacs.conversations.xmpp.forms.Data;
  94import eu.siacs.conversations.xmpp.forms.Field;
  95import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  96import eu.siacs.conversations.xmpp.jid.Jid;
  97import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
  98import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
  99import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
 100import eu.siacs.conversations.xmpp.pep.Avatar;
 101import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 102import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 103import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
 104import me.leolin.shortcutbadger.ShortcutBadger;
 105
 106public class XmppConnectionService extends Service implements OnPhoneContactsLoadedListener {
 107
 108	public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification";
 109	public static final String ACTION_DISABLE_FOREGROUND = "disable_foreground";
 110	private static final String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
 111	public static final String ACTION_TRY_AGAIN = "try_again";
 112	public static final String ACTION_DISABLE_ACCOUNT = "disable_account";
 113	private ContentObserver contactObserver = new ContentObserver(null) {
 114		@Override
 115		public void onChange(boolean selfChange) {
 116			super.onChange(selfChange);
 117			Intent intent = new Intent(getApplicationContext(),
 118					XmppConnectionService.class);
 119			intent.setAction(ACTION_MERGE_PHONE_CONTACTS);
 120			startService(intent);
 121		}
 122	};
 123
 124	private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor();
 125	private final SerialSingleThreadExecutor mDatabaseExecutor = new SerialSingleThreadExecutor();
 126
 127	private final IBinder mBinder = new XmppConnectionBinder();
 128	private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
 129	private final FileObserver fileObserver = new FileObserver(
 130			FileBackend.getConversationsImageDirectory()) {
 131
 132		@Override
 133		public void onEvent(int event, String path) {
 134			if (event == FileObserver.DELETE) {
 135				markFileDeleted(path.split("\\.")[0]);
 136			}
 137		}
 138	};
 139	private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
 140
 141		@Override
 142		public void onJinglePacketReceived(Account account, JinglePacket packet) {
 143			mJingleConnectionManager.deliverPacket(account, packet);
 144		}
 145	};
 146	private final OnBindListener mOnBindListener = new OnBindListener() {
 147
 148		@Override
 149		public void onBind(final Account account) {
 150			account.getRoster().clearPresences();
 151			account.pendingConferenceJoins.clear();
 152			account.pendingConferenceLeaves.clear();
 153			fetchRosterFromServer(account);
 154			fetchBookmarks(account);
 155			sendPresence(account);
 156			connectMultiModeConversations(account);
 157			updateConversationUi();
 158		}
 159	};
 160	private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
 161
 162		@Override
 163		public void onMessageAcknowledged(Account account, String uuid) {
 164			for (final Conversation conversation : getConversations()) {
 165				if (conversation.getAccount() == account) {
 166					Message message = conversation.findUnsentMessageWithUuid(uuid);
 167					if (message != null) {
 168						markMessage(message, Message.STATUS_SEND);
 169						if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
 170							databaseBackend.updateConversation(conversation);
 171						}
 172					}
 173				}
 174			}
 175		}
 176	};
 177	private final IqGenerator mIqGenerator = new IqGenerator(this);
 178	public DatabaseBackend databaseBackend;
 179	public OnContactStatusChanged onContactStatusChanged = new OnContactStatusChanged() {
 180
 181		@Override
 182		public void onContactStatusChanged(Contact contact, boolean online) {
 183			Conversation conversation = find(getConversations(), contact);
 184			if (conversation != null) {
 185				if (online) {
 186					conversation.endOtrIfNeeded();
 187					if (contact.getPresences().size() == 1) {
 188						sendUnsentMessages(conversation);
 189					}
 190				} else {
 191					if (contact.getPresences().size() >= 1) {
 192						if (conversation.hasValidOtrSession()) {
 193							String otrResource = conversation.getOtrSession().getSessionID().getUserID();
 194							if (!(Arrays.asList(contact.getPresences().asStringArray()).contains(otrResource))) {
 195								conversation.endOtrIfNeeded();
 196							}
 197						}
 198					} else {
 199						conversation.endOtrIfNeeded();
 200					}
 201				}
 202			}
 203		}
 204	};
 205	private FileBackend fileBackend = new FileBackend(this);
 206	private MemorizingTrustManager mMemorizingTrustManager;
 207	private NotificationService mNotificationService = new NotificationService(
 208			this);
 209	private OnMessagePacketReceived mMessageParser = new MessageParser(this);
 210	private OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
 211	private IqParser mIqParser = new IqParser(this);
 212	private OnIqPacketReceived mDefaultIqHandler = new OnIqPacketReceived() {
 213		@Override
 214		public void onIqPacketReceived(Account account, IqPacket packet) {
 215			if (packet.getType() == IqPacket.TYPE.ERROR) {
 216				Element error = packet.findChild("error");
 217				String text = error != null ? error.findChildContent("text") : null;
 218				if (text != null) {
 219					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received iq error - "+text);
 220				}
 221			}
 222		}
 223	};
 224	private MessageGenerator mMessageGenerator = new MessageGenerator(this);
 225	private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
 226	private List<Account> accounts;
 227	private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
 228			this);
 229	private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(
 230			this);
 231	private AvatarService mAvatarService = new AvatarService(this);
 232	private final List<String> mInProgressAvatarFetches = new ArrayList<>();
 233	private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
 234	private OnConversationUpdate mOnConversationUpdate = null;
 235	private int convChangedListenerCount = 0;
 236	private OnShowErrorToast mOnShowErrorToast = null;
 237	private int showErrorToastListenerCount = 0;
 238	private int unreadCount = -1;
 239	private OnAccountUpdate mOnAccountUpdate = null;
 240	private OnStatusChanged statusListener = new OnStatusChanged() {
 241
 242		@Override
 243		public void onStatusChanged(Account account) {
 244			XmppConnection connection = account.getXmppConnection();
 245			if (mOnAccountUpdate != null) {
 246				mOnAccountUpdate.onAccountUpdate();
 247			}
 248			if (account.getStatus() == Account.State.ONLINE) {
 249				for (Conversation conversation : account.pendingConferenceLeaves) {
 250					leaveMuc(conversation);
 251				}
 252				for (Conversation conversation : account.pendingConferenceJoins) {
 253					joinMuc(conversation);
 254				}
 255				mMessageArchiveService.executePendingQueries(account);
 256				mJingleConnectionManager.cancelInTransmission();
 257				List<Conversation> conversations = getConversations();
 258				for (Conversation conversation : conversations) {
 259					if (conversation.getAccount() == account) {
 260						conversation.startOtrIfNeeded();
 261						sendUnsentMessages(conversation);
 262					}
 263				}
 264				if (connection != null && connection.getFeatures().csi()) {
 265					if (checkListeners()) {
 266						Log.d(Config.LOGTAG, account.getJid().toBareJid()
 267								+ " sending csi//inactive");
 268						connection.sendInactive();
 269					} else {
 270						Log.d(Config.LOGTAG, account.getJid().toBareJid()
 271								+ " sending csi//active");
 272						connection.sendActive();
 273					}
 274				}
 275				syncDirtyContacts(account);
 276				scheduleWakeUpCall(Config.PING_MAX_INTERVAL,account.getUuid().hashCode());
 277			} else if (account.getStatus() == Account.State.OFFLINE) {
 278				resetSendingToWaiting(account);
 279				if (!account.isOptionSet(Account.OPTION_DISABLED)) {
 280					int timeToReconnect = mRandom.nextInt(50) + 10;
 281					scheduleWakeUpCall(timeToReconnect,account.getUuid().hashCode());
 282				}
 283			} else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
 284				databaseBackend.updateAccount(account);
 285				reconnectAccount(account, true);
 286			} else if ((account.getStatus() != Account.State.CONNECTING)
 287					&& (account.getStatus() != Account.State.NO_INTERNET)) {
 288				if (connection != null) {
 289					int next = connection.getTimeToNextAttempt();
 290					Log.d(Config.LOGTAG, account.getJid().toBareJid()
 291							+ ": error connecting account. try again in "
 292							+ next + "s for the "
 293							+ (connection.getAttempt() + 1) + " time");
 294					scheduleWakeUpCall(next,account.getUuid().hashCode());
 295				}
 296					}
 297			getNotificationService().updateErrorNotification();
 298		}
 299	};
 300	private int accountChangedListenerCount = 0;
 301	private OnRosterUpdate mOnRosterUpdate = null;
 302	private OnUpdateBlocklist mOnUpdateBlocklist = null;
 303	private int updateBlocklistListenerCount = 0;
 304	private int rosterChangedListenerCount = 0;
 305	private OnMucRosterUpdate mOnMucRosterUpdate = null;
 306	private int mucRosterChangedListenerCount = 0;
 307	private SecureRandom mRandom;
 308	private OpenPgpServiceConnection pgpServiceConnection;
 309	private PgpEngine mPgpEngine = null;
 310	private WakeLock wakeLock;
 311	private PowerManager pm;
 312	private LruCache<String, Bitmap> mBitmapCache;
 313	private Thread mPhoneContactMergerThread;
 314
 315	private boolean mRestoredFromDatabase = false;
 316	public boolean areMessagesInitialized() {
 317		return this.mRestoredFromDatabase;
 318	}
 319
 320	public PgpEngine getPgpEngine() {
 321		if (pgpServiceConnection.isBound()) {
 322			if (this.mPgpEngine == null) {
 323				this.mPgpEngine = new PgpEngine(new OpenPgpApi(
 324							getApplicationContext(),
 325							pgpServiceConnection.getService()), this);
 326			}
 327			return mPgpEngine;
 328		} else {
 329			return null;
 330		}
 331
 332	}
 333
 334	public FileBackend getFileBackend() {
 335		return this.fileBackend;
 336	}
 337
 338	public AvatarService getAvatarService() {
 339		return this.mAvatarService;
 340	}
 341
 342	public void attachLocationToConversation(final Conversation conversation,
 343											 final Uri uri,
 344											 final UiCallback<Message> callback) {
 345		int encryption = conversation.getNextEncryption(forceEncryption());
 346		if (encryption == Message.ENCRYPTION_PGP) {
 347			encryption = Message.ENCRYPTION_DECRYPTED;
 348		}
 349		Message message = new Message(conversation,uri.toString(),encryption);
 350		if (conversation.getNextCounterpart() != null) {
 351			message.setCounterpart(conversation.getNextCounterpart());
 352		}
 353		if (encryption == Message.ENCRYPTION_DECRYPTED) {
 354			getPgpEngine().encrypt(message, callback);
 355		} else {
 356			callback.success(message);
 357		}
 358	}
 359
 360	public void attachFileToConversation(final Conversation conversation,
 361			final Uri uri,
 362			final UiCallback<Message> callback) {
 363		final Message message;
 364		if (conversation.getNextEncryption(forceEncryption()) == Message.ENCRYPTION_PGP) {
 365			message = new Message(conversation, "",
 366					Message.ENCRYPTION_DECRYPTED);
 367		} else {
 368			message = new Message(conversation, "",
 369					conversation.getNextEncryption(forceEncryption()));
 370		}
 371		message.setCounterpart(conversation.getNextCounterpart());
 372		message.setType(Message.TYPE_FILE);
 373		String path = getFileBackend().getOriginalPath(uri);
 374		if (path!=null) {
 375			message.setRelativeFilePath(path);
 376			getFileBackend().updateFileParams(message);
 377			if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 378				getPgpEngine().encrypt(message, callback);
 379			} else {
 380				callback.success(message);
 381			}
 382		} else {
 383			mFileAddingExecutor.execute(new Runnable() {
 384				@Override
 385				public void run() {
 386					try {
 387						getFileBackend().copyFileToPrivateStorage(message, uri);
 388						getFileBackend().updateFileParams(message);
 389						if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 390							getPgpEngine().encrypt(message, callback);
 391						} else {
 392							callback.success(message);
 393						}
 394					} catch (FileBackend.FileCopyException e) {
 395						callback.error(e.getResId(), message);
 396					}
 397				}
 398			});
 399		}
 400	}
 401
 402	public void attachImageToConversation(final Conversation conversation,
 403			final Uri uri, final UiCallback<Message> callback) {
 404		final Message message;
 405		if (conversation.getNextEncryption(forceEncryption()) == Message.ENCRYPTION_PGP) {
 406			message = new Message(conversation, "",
 407					Message.ENCRYPTION_DECRYPTED);
 408		} else {
 409			message = new Message(conversation, "",
 410					conversation.getNextEncryption(forceEncryption()));
 411		}
 412		message.setCounterpart(conversation.getNextCounterpart());
 413		message.setType(Message.TYPE_IMAGE);
 414		mFileAddingExecutor.execute(new Runnable() {
 415
 416			@Override
 417			public void run() {
 418				try {
 419					getFileBackend().copyImageToPrivateStorage(message, uri);
 420					if (conversation.getNextEncryption(forceEncryption()) == Message.ENCRYPTION_PGP) {
 421						getPgpEngine().encrypt(message, callback);
 422					} else {
 423						callback.success(message);
 424					}
 425				} catch (final FileBackend.FileCopyException e) {
 426					callback.error(e.getResId(), message);
 427				}
 428			}
 429		});
 430	}
 431
 432	public Conversation find(Bookmark bookmark) {
 433		return find(bookmark.getAccount(), bookmark.getJid());
 434	}
 435
 436	public Conversation find(final Account account, final Jid jid) {
 437		return find(getConversations(), account, jid);
 438	}
 439
 440	@Override
 441	public int onStartCommand(Intent intent, int flags, int startId) {
 442		final String action = intent == null ? null : intent.getAction();
 443		if (action != null) {
 444			switch (action) {
 445				case ConnectivityManager.CONNECTIVITY_ACTION:
 446					if (hasInternetConnection() && Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
 447						resetAllAttemptCounts(true);
 448					}
 449					break;
 450				case ACTION_MERGE_PHONE_CONTACTS:
 451					if (mRestoredFromDatabase) {
 452						PhoneHelper.loadPhoneContacts(getApplicationContext(),
 453								new CopyOnWriteArrayList<Bundle>(),
 454								this);
 455					}
 456					return START_STICKY;
 457				case Intent.ACTION_SHUTDOWN:
 458					logoutAndSave();
 459					return START_NOT_STICKY;
 460				case ACTION_CLEAR_NOTIFICATION:
 461					mNotificationService.clear();
 462					break;
 463				case ACTION_DISABLE_FOREGROUND:
 464					getPreferences().edit().putBoolean("keep_foreground_service",false).commit();
 465					toggleForegroundService();
 466					break;
 467				case ACTION_TRY_AGAIN:
 468					resetAllAttemptCounts(false);
 469					break;
 470				case ACTION_DISABLE_ACCOUNT:
 471					try {
 472						String jid = intent.getStringExtra("account");
 473						Account account = jid == null ? null : findAccountByJid(Jid.fromString(jid));
 474						if (account != null) {
 475							account.setOption(Account.OPTION_DISABLED,true);
 476							updateAccount(account);
 477						}
 478					} catch (final InvalidJidException ignored) {
 479						break;
 480					}
 481					break;
 482			}
 483		}
 484		this.wakeLock.acquire();
 485
 486		for (Account account : accounts) {
 487			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
 488				if (!hasInternetConnection()) {
 489					account.setStatus(Account.State.NO_INTERNET);
 490					if (statusListener != null) {
 491						statusListener.onStatusChanged(account);
 492					}
 493				} else {
 494					if (account.getStatus() == Account.State.NO_INTERNET) {
 495						account.setStatus(Account.State.OFFLINE);
 496						if (statusListener != null) {
 497							statusListener.onStatusChanged(account);
 498						}
 499					}
 500					if (account.getStatus() == Account.State.ONLINE) {
 501						long lastReceived = account.getXmppConnection().getLastPacketReceived();
 502						long lastSent = account.getXmppConnection().getLastPingSent();
 503						long pingInterval = "ui".equals(action) ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
 504						long msToNextPing = (Math.max(lastReceived,lastSent) + pingInterval) - SystemClock.elapsedRealtime();
 505						long pingTimeoutIn = (lastSent + Config.PING_TIMEOUT * 1000) - SystemClock.elapsedRealtime();
 506						if (lastSent > lastReceived) {
 507							if (pingTimeoutIn < 0) {
 508								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": ping timeout");
 509								this.reconnectAccount(account, true);
 510							} else {
 511								int secs = (int) (pingTimeoutIn / 1000);
 512								this.scheduleWakeUpCall(secs,account.getUuid().hashCode());
 513							}
 514						} else if (msToNextPing <= 0) {
 515							account.getXmppConnection().sendPing();
 516							Log.d(Config.LOGTAG, account.getJid().toBareJid()+" send ping");
 517							this.scheduleWakeUpCall(Config.PING_TIMEOUT,account.getUuid().hashCode());
 518						} else {
 519							this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
 520						}
 521					} else if (account.getStatus() == Account.State.OFFLINE) {
 522						reconnectAccount(account,true);
 523					} else if (account.getStatus() == Account.State.CONNECTING) {
 524						long timeout = Config.CONNECT_TIMEOUT - ((SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000);
 525						if (timeout < 0) {
 526							Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting");
 527							reconnectAccount(account, true);
 528						} else {
 529							scheduleWakeUpCall((int) timeout,account.getUuid().hashCode());
 530						}
 531					} else {
 532						if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
 533							reconnectAccount(account, true);
 534						}
 535					}
 536
 537				}
 538				if (mOnAccountUpdate != null) {
 539					mOnAccountUpdate.onAccountUpdate();
 540				}
 541			}
 542		}
 543		/*PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
 544			if (!pm.isScreenOn()) {
 545			removeStaleListeners();
 546			}*/
 547		if (wakeLock.isHeld()) {
 548			try {
 549				wakeLock.release();
 550			} catch (final RuntimeException ignored) {
 551			}
 552		}
 553		return START_STICKY;
 554	}
 555
 556	private void resetAllAttemptCounts(boolean reallyAll) {
 557		Log.d(Config.LOGTAG,"resetting all attepmt counts");
 558		for(Account account : accounts) {
 559			if (account.hasErrorStatus() || reallyAll) {
 560				final XmppConnection connection = account.getXmppConnection();
 561				if (connection != null) {
 562					connection.resetAttemptCount();
 563				}
 564			}
 565		}
 566	}
 567
 568	public boolean hasInternetConnection() {
 569		ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
 570			.getSystemService(Context.CONNECTIVITY_SERVICE);
 571		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
 572		return activeNetwork != null && activeNetwork.isConnected();
 573	}
 574
 575	@SuppressLint("TrulyRandom")
 576	@Override
 577	public void onCreate() {
 578		ExceptionHelper.init(getApplicationContext());
 579		PRNGFixes.apply();
 580		this.mRandom = new SecureRandom();
 581		updateMemorizingTrustmanager();
 582		final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
 583		final int cacheSize = maxMemory / 8;
 584		this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
 585			@Override
 586			protected int sizeOf(final String key, final Bitmap bitmap) {
 587				return bitmap.getByteCount() / 1024;
 588			}
 589		};
 590
 591		this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
 592		this.accounts = databaseBackend.getAccounts();
 593
 594		for (final Account account : this.accounts) {
 595			account.initAccountServices(this);
 596		}
 597		restoreFromDatabase();
 598
 599		getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
 600		this.fileObserver.startWatching();
 601		this.pgpServiceConnection = new OpenPgpServiceConnection(getApplicationContext(), "org.sufficientlysecure.keychain");
 602		this.pgpServiceConnection.bindToService();
 603
 604		this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 605		this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"XmppConnectionService");
 606		toggleForegroundService();
 607		updateUnreadCountBadge();
 608	}
 609
 610	public void toggleForegroundService() {
 611		if (getPreferences().getBoolean("keep_foreground_service",false)) {
 612			startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
 613		} else {
 614			stopForeground(true);
 615		}
 616	}
 617
 618	@Override
 619	public void onTaskRemoved(final Intent rootIntent) {
 620		super.onTaskRemoved(rootIntent);
 621		if (!getPreferences().getBoolean("keep_foreground_service",false)) {
 622			this.logoutAndSave();
 623		}
 624	}
 625
 626	private void logoutAndSave() {
 627		for (final Account account : accounts) {
 628			databaseBackend.writeRoster(account.getRoster());
 629			if (account.getXmppConnection() != null) {
 630				disconnect(account, false);
 631			}
 632		}
 633		Context context = getApplicationContext();
 634		AlarmManager alarmManager = (AlarmManager) context
 635				.getSystemService(Context.ALARM_SERVICE);
 636		Intent intent = new Intent(context, EventReceiver.class);
 637		alarmManager.cancel(PendingIntent.getBroadcast(context, 0, intent, 0));
 638		Log.d(Config.LOGTAG, "good bye");
 639		stopSelf();
 640	}
 641
 642	protected void scheduleWakeUpCall(int seconds, int requestCode) {
 643		final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
 644
 645		Context context = getApplicationContext();
 646		AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
 647
 648		Intent intent = new Intent(context, EventReceiver.class);
 649		intent.setAction("ping");
 650		PendingIntent alarmIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0);
 651		alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, alarmIntent);
 652	}
 653
 654	public XmppConnection createConnection(final Account account) {
 655		final SharedPreferences sharedPref = getPreferences();
 656		account.setResource(sharedPref.getString("resource", "mobile")
 657				.toLowerCase(Locale.getDefault()));
 658		final XmppConnection connection = new XmppConnection(account, this);
 659		connection.setOnMessagePacketReceivedListener(this.mMessageParser);
 660		connection.setOnStatusChangedListener(this.statusListener);
 661		connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
 662		connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
 663		connection.setOnJinglePacketReceivedListener(this.jingleListener);
 664		connection.setOnBindListener(this.mOnBindListener);
 665		connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
 666		connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
 667		return connection;
 668	}
 669
 670	public void sendChatState(Conversation conversation) {
 671		if (sendChatStates()) {
 672			MessagePacket packet = mMessageGenerator.generateChatState(conversation);
 673			sendMessagePacket(conversation.getAccount(), packet);
 674		}
 675	}
 676
 677	private void sendFileMessage(final Message message) {
 678		Log.d(Config.LOGTAG, "send file message");
 679		final Account account = message.getConversation().getAccount();
 680		final XmppConnection connection = account.getXmppConnection();
 681		if (connection != null && connection.getFeatures().httpUpload()) {
 682			mHttpConnectionManager.createNewUploadConnection(message);
 683		} else {
 684			mJingleConnectionManager.createNewConnection(message);
 685		}
 686	}
 687
 688	public void sendMessage(final Message message) {
 689		sendMessage(message, false);
 690	}
 691
 692	private void sendMessage(final Message message, final boolean resend) {
 693		final Account account = message.getConversation().getAccount();
 694		final Conversation conversation = message.getConversation();
 695		account.deactivateGracePeriod();
 696		MessagePacket packet = null;
 697		boolean saveInDb = true;
 698		message.setStatus(Message.STATUS_WAITING);
 699
 700		if (!resend && message.getEncryption() != Message.ENCRYPTION_OTR) {
 701			message.getConversation().endOtrIfNeeded();
 702			message.getConversation().findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
 703				@Override
 704				public void onMessageFound(Message message) {
 705					markMessage(message,Message.STATUS_SEND_FAILED);
 706				}
 707			});
 708		}
 709
 710		if (account.isOnlineAndConnected()) {
 711			switch (message.getEncryption()) {
 712				case Message.ENCRYPTION_NONE:
 713					if (message.needsUploading()) {
 714						if (account.httpUploadAvailable() || message.fixCounterpart()) {
 715							this.sendFileMessage(message);
 716						} else {
 717							break;
 718						}
 719					} else {
 720						packet = mMessageGenerator.generateChat(message,resend);
 721					}
 722					break;
 723				case Message.ENCRYPTION_PGP:
 724				case Message.ENCRYPTION_DECRYPTED:
 725					if (message.needsUploading()) {
 726						if (account.httpUploadAvailable() || message.fixCounterpart()) {
 727							this.sendFileMessage(message);
 728						} else {
 729							break;
 730						}
 731					} else {
 732						packet = mMessageGenerator.generatePgpChat(message,resend);
 733					}
 734					break;
 735				case Message.ENCRYPTION_OTR:
 736					SessionImpl otrSession = conversation.getOtrSession();
 737					if (otrSession != null && otrSession.getSessionStatus() == SessionStatus.ENCRYPTED) {
 738						try {
 739							message.setCounterpart(Jid.fromSessionID(otrSession.getSessionID()));
 740						} catch (InvalidJidException e) {
 741							break;
 742						}
 743						if (message.needsUploading()) {
 744							mJingleConnectionManager.createNewConnection(message);
 745						} else {
 746							packet = mMessageGenerator.generateOtrChat(message,resend);
 747						}
 748					} else if (otrSession == null) {
 749						if (message.fixCounterpart()) {
 750							conversation.startOtrSession(message.getCounterpart().getResourcepart(), true);
 751						} else {
 752							break;
 753						}
 754					}
 755					break;
 756			}
 757			if (packet != null) {
 758				if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
 759					message.setStatus(Message.STATUS_UNSEND);
 760				} else {
 761					message.setStatus(Message.STATUS_SEND);
 762				}
 763			}
 764		} else {
 765			switch(message.getEncryption()) {
 766				case Message.ENCRYPTION_DECRYPTED:
 767					if (!message.needsUploading()) {
 768						String pgpBody = message.getEncryptedBody();
 769						String decryptedBody = message.getBody();
 770						message.setBody(pgpBody);
 771						message.setEncryption(Message.ENCRYPTION_PGP);
 772						databaseBackend.createMessage(message);
 773						saveInDb = false;
 774						message.setBody(decryptedBody);
 775						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 776					}
 777					break;
 778				case Message.ENCRYPTION_OTR:
 779					if (!conversation.hasValidOtrSession() && message.getCounterpart() != null) {
 780						conversation.startOtrSession(message.getCounterpart().getResourcepart(), false);
 781					}
 782					break;
 783			}
 784		}
 785
 786		if (resend) {
 787			if (packet != null) {
 788				if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
 789					markMessage(message,Message.STATUS_UNSEND);
 790				} else {
 791					markMessage(message,Message.STATUS_SEND);
 792				}
 793			}
 794		} else {
 795			conversation.add(message);
 796			if (saveInDb && (message.getEncryption() == Message.ENCRYPTION_NONE || saveEncryptedMessages())) {
 797				databaseBackend.createMessage(message);
 798			}
 799			updateConversationUi();
 800		}
 801		if (packet != null) {
 802			if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
 803				if (this.sendChatStates()) {
 804					packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
 805				}
 806			}
 807			sendMessagePacket(account, packet);
 808		}
 809	}
 810
 811	private void sendUnsentMessages(final Conversation conversation) {
 812		conversation.findWaitingMessages(new Conversation.OnMessageFound() {
 813
 814			@Override
 815			public void onMessageFound(Message message) {
 816				resendMessage(message);
 817			}
 818		});
 819	}
 820
 821	public void resendMessage(final Message message) {
 822		sendMessage(message, true);
 823	}
 824
 825	public void fetchRosterFromServer(final Account account) {
 826		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
 827		if (!"".equals(account.getRosterVersion())) {
 828			Log.d(Config.LOGTAG, account.getJid().toBareJid()
 829					+ ": fetching roster version " + account.getRosterVersion());
 830		} else {
 831			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
 832		}
 833		iqPacket.query(Xmlns.ROSTER).setAttribute("ver",account.getRosterVersion());
 834		sendIqPacket(account,iqPacket,mIqParser);
 835	}
 836
 837	public void fetchBookmarks(final Account account) {
 838		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
 839		final Element query = iqPacket.query("jabber:iq:private");
 840		query.addChild("storage", "storage:bookmarks");
 841		final OnIqPacketReceived callback = new OnIqPacketReceived() {
 842
 843			@Override
 844			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 845				final Element query = packet.query();
 846				final List<Bookmark> bookmarks = new CopyOnWriteArrayList<>();
 847				final Element storage = query.findChild("storage",
 848						"storage:bookmarks");
 849				if (storage != null) {
 850					for (final Element item : storage.getChildren()) {
 851						if (item.getName().equals("conference")) {
 852							final Bookmark bookmark = Bookmark.parse(item, account);
 853							bookmarks.add(bookmark);
 854							Conversation conversation = find(bookmark);
 855							if (conversation != null) {
 856								conversation.setBookmark(bookmark);
 857							} else if (bookmark.autojoin() && bookmark.getJid() != null) {
 858								conversation = findOrCreateConversation(
 859										account, bookmark.getJid(), true);
 860								conversation.setBookmark(bookmark);
 861								joinMuc(conversation);
 862							}
 863						}
 864					}
 865				}
 866				account.setBookmarks(bookmarks);
 867			}
 868		};
 869		sendIqPacket(account, iqPacket, callback);
 870	}
 871
 872	public void pushBookmarks(Account account) {
 873		IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
 874		Element query = iqPacket.query("jabber:iq:private");
 875		Element storage = query.addChild("storage", "storage:bookmarks");
 876		for (Bookmark bookmark : account.getBookmarks()) {
 877			storage.addChild(bookmark);
 878		}
 879		sendIqPacket(account, iqPacket, mDefaultIqHandler);
 880	}
 881
 882	public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
 883		if (mPhoneContactMergerThread != null) {
 884			mPhoneContactMergerThread.interrupt();
 885		}
 886		mPhoneContactMergerThread = new Thread(new Runnable() {
 887			@Override
 888			public void run() {
 889				Log.d(Config.LOGTAG,"start merging phone contacts with roster");
 890				for (Account account : accounts) {
 891					List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
 892					for (Bundle phoneContact : phoneContacts) {
 893						if (Thread.interrupted()) {
 894							Log.d(Config.LOGTAG,"interrupted merging phone contacts");
 895							return;
 896						}
 897						Jid jid;
 898						try {
 899							jid = Jid.fromString(phoneContact.getString("jid"));
 900						} catch (final InvalidJidException e) {
 901							continue;
 902						}
 903						final Contact contact = account.getRoster().getContact(jid);
 904						String systemAccount = phoneContact.getInt("phoneid")
 905							+ "#"
 906							+ phoneContact.getString("lookup");
 907						contact.setSystemAccount(systemAccount);
 908						if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
 909							getAvatarService().clear(contact);
 910						}
 911						contact.setSystemName(phoneContact.getString("displayname"));
 912						withSystemAccounts.remove(contact);
 913					}
 914					for(Contact contact : withSystemAccounts) {
 915						contact.setSystemAccount(null);
 916						contact.setSystemName(null);
 917						if (contact.setPhotoUri(null)) {
 918							getAvatarService().clear(contact);
 919						}
 920					}
 921				}
 922				Log.d(Config.LOGTAG,"finished merging phone contacts");
 923				updateAccountUi();
 924			}
 925		});
 926		mPhoneContactMergerThread.start();
 927	}
 928
 929	private void restoreFromDatabase() {
 930		synchronized (this.conversations) {
 931			final Map<String, Account> accountLookupTable = new Hashtable<>();
 932			for (Account account : this.accounts) {
 933				accountLookupTable.put(account.getUuid(), account);
 934			}
 935			this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
 936			for (Conversation conversation : this.conversations) {
 937				Account account = accountLookupTable.get(conversation.getAccountUuid());
 938				conversation.setAccount(account);
 939			}
 940			Runnable runnable =new Runnable() {
 941				@Override
 942				public void run() {
 943					Log.d(Config.LOGTAG,"restoring roster");
 944					for(Account account : accounts) {
 945						databaseBackend.readRoster(account.getRoster());
 946					}
 947					getBitmapCache().evictAll();
 948					Looper.prepare();
 949					PhoneHelper.loadPhoneContacts(getApplicationContext(),
 950							new CopyOnWriteArrayList<Bundle>(),
 951							XmppConnectionService.this);
 952					Log.d(Config.LOGTAG,"restoring messages");
 953					for (Conversation conversation : conversations) {
 954						conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
 955						checkDeletedFiles(conversation);
 956					}
 957					mRestoredFromDatabase = true;
 958					Log.d(Config.LOGTAG,"restored all messages");
 959					updateConversationUi();
 960				}
 961			};
 962			mDatabaseExecutor.execute(runnable);
 963		}
 964	}
 965
 966	public List<Conversation> getConversations() {
 967		return this.conversations;
 968	}
 969
 970	private void checkDeletedFiles(Conversation conversation) {
 971		conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
 972
 973			@Override
 974			public void onMessageFound(Message message) {
 975				if (!getFileBackend().isFileAvailable(message)) {
 976					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
 977				}
 978			}
 979		});
 980	}
 981
 982	private void markFileDeleted(String uuid) {
 983		for (Conversation conversation : getConversations()) {
 984			Message message = conversation.findMessageWithFileAndUuid(uuid);
 985			if (message != null) {
 986				if (!getFileBackend().isFileAvailable(message)) {
 987					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
 988					updateConversationUi();
 989				}
 990				return;
 991			}
 992		}
 993	}
 994
 995	public void populateWithOrderedConversations(final List<Conversation> list) {
 996		populateWithOrderedConversations(list, true);
 997	}
 998
 999	public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1000		list.clear();
1001		if (includeNoFileUpload) {
1002			list.addAll(getConversations());
1003		} else {
1004			for (Conversation conversation : getConversations()) {
1005				if (conversation.getMode() == Conversation.MODE_SINGLE
1006						|| conversation.getAccount().httpUploadAvailable()) {
1007					list.add(conversation);
1008				}
1009			}
1010		}
1011		Collections.sort(list, new Comparator<Conversation>() {
1012			@Override
1013			public int compare(Conversation lhs, Conversation rhs) {
1014				Message left = lhs.getLatestMessage();
1015				Message right = rhs.getLatestMessage();
1016				if (left.getTimeSent() > right.getTimeSent()) {
1017					return -1;
1018				} else if (left.getTimeSent() < right.getTimeSent()) {
1019					return 1;
1020				} else {
1021					return 0;
1022				}
1023			}
1024		});
1025	}
1026
1027	public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1028		Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1029		if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation,callback)) {
1030			return;
1031		}
1032		Runnable runnable = new Runnable() {
1033			@Override
1034			public void run() {
1035				final Account account = conversation.getAccount();
1036				List<Message> messages = databaseBackend.getMessages(conversation, 50,timestamp);
1037				if (messages.size() > 0) {
1038					conversation.addAll(0, messages);
1039					checkDeletedFiles(conversation);
1040					callback.onMoreMessagesLoaded(messages.size(), conversation);
1041				} else if (conversation.hasMessagesLeftOnServer()
1042						&& account.isOnlineAndConnected()
1043						&& account.getXmppConnection().getFeatures().mam()) {
1044					MessageArchiveService.Query query = getMessageArchiveService().query(conversation,0,timestamp - 1);
1045					if (query != null) {
1046						query.setCallback(callback);
1047					}
1048					callback.informUser(R.string.fetching_history_from_server);
1049				}
1050			}
1051		};
1052		mDatabaseExecutor.execute(runnable);
1053	}
1054
1055	public List<Account> getAccounts() {
1056		return this.accounts;
1057	}
1058
1059	public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1060		for (final Conversation conversation : haystack) {
1061			if (conversation.getContact() == contact) {
1062				return conversation;
1063			}
1064		}
1065		return null;
1066	}
1067
1068	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1069		if (jid == null) {
1070			return null;
1071		}
1072		for (final Conversation conversation : haystack) {
1073			if ((account == null || conversation.getAccount() == account)
1074					&& (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1075				return conversation;
1076			}
1077		}
1078		return null;
1079	}
1080
1081	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1082		return this.findOrCreateConversation(account, jid, muc, null);
1083	}
1084
1085	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1086		synchronized (this.conversations) {
1087			Conversation conversation = find(account, jid);
1088			if (conversation != null) {
1089				return conversation;
1090			}
1091			conversation = databaseBackend.findConversation(account, jid);
1092			if (conversation != null) {
1093				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1094				conversation.setAccount(account);
1095				if (muc) {
1096					conversation.setMode(Conversation.MODE_MULTI);
1097					conversation.setContactJid(jid);
1098				} else {
1099					conversation.setMode(Conversation.MODE_SINGLE);
1100					conversation.setContactJid(jid.toBareJid());
1101				}
1102				conversation.setNextEncryption(-1);
1103				conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1104				this.databaseBackend.updateConversation(conversation);
1105			} else {
1106				String conversationName;
1107				Contact contact = account.getRoster().getContact(jid);
1108				if (contact != null) {
1109					conversationName = contact.getDisplayName();
1110				} else {
1111					conversationName = jid.getLocalpart();
1112				}
1113				if (muc) {
1114					conversation = new Conversation(conversationName, account, jid,
1115							Conversation.MODE_MULTI);
1116				} else {
1117					conversation = new Conversation(conversationName, account, jid.toBareJid(),
1118							Conversation.MODE_SINGLE);
1119				}
1120				this.databaseBackend.createConversation(conversation);
1121			}
1122			if (account.getXmppConnection() != null
1123					&& account.getXmppConnection().getFeatures().mam()
1124					&& !muc) {
1125				if (query == null) {
1126					this.mMessageArchiveService.query(conversation);
1127				} else {
1128					if (query.getConversation() == null) {
1129						this.mMessageArchiveService.query(conversation, query.getStart());
1130					}
1131				}
1132			}
1133			checkDeletedFiles(conversation);
1134			this.conversations.add(conversation);
1135			updateConversationUi();
1136			return conversation;
1137		}
1138	}
1139
1140	public void archiveConversation(Conversation conversation) {
1141		getNotificationService().clear(conversation);
1142		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1143		conversation.setNextEncryption(-1);
1144		synchronized (this.conversations) {
1145			if (conversation.getMode() == Conversation.MODE_MULTI) {
1146				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1147					Bookmark bookmark = conversation.getBookmark();
1148					if (bookmark != null && bookmark.autojoin()) {
1149						bookmark.setAutojoin(false);
1150						pushBookmarks(bookmark.getAccount());
1151					}
1152				}
1153				leaveMuc(conversation);
1154			} else {
1155				conversation.endOtrIfNeeded();
1156			}
1157			this.databaseBackend.updateConversation(conversation);
1158			this.conversations.remove(conversation);
1159			updateConversationUi();
1160		}
1161	}
1162
1163	public void createAccount(final Account account) {
1164		account.initAccountServices(this);
1165		databaseBackend.createAccount(account);
1166		this.accounts.add(account);
1167		this.reconnectAccountInBackground(account);
1168		updateAccountUi();
1169	}
1170
1171	public void updateAccount(final Account account) {
1172		this.statusListener.onStatusChanged(account);
1173		databaseBackend.updateAccount(account);
1174		reconnectAccount(account, false);
1175		updateAccountUi();
1176		getNotificationService().updateErrorNotification();
1177	}
1178
1179	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1180		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1181		sendIqPacket(account, iq, new OnIqPacketReceived() {
1182			@Override
1183			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1184				if (packet.getType() == IqPacket.TYPE.RESULT) {
1185					account.setPassword(newPassword);
1186					databaseBackend.updateAccount(account);
1187					callback.onPasswordChangeSucceeded();
1188				} else {
1189					callback.onPasswordChangeFailed();
1190				}
1191			}
1192		});
1193	}
1194
1195	public void deleteAccount(final Account account) {
1196		synchronized (this.conversations) {
1197			for (final Conversation conversation : conversations) {
1198				if (conversation.getAccount() == account) {
1199					if (conversation.getMode() == Conversation.MODE_MULTI) {
1200						leaveMuc(conversation);
1201					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1202						conversation.endOtrIfNeeded();
1203					}
1204					conversations.remove(conversation);
1205				}
1206			}
1207			if (account.getXmppConnection() != null) {
1208				this.disconnect(account, true);
1209			}
1210			databaseBackend.deleteAccount(account);
1211			this.accounts.remove(account);
1212			updateAccountUi();
1213			getNotificationService().updateErrorNotification();
1214		}
1215	}
1216
1217	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1218		synchronized (this) {
1219			if (checkListeners()) {
1220				switchToForeground();
1221			}
1222			this.mOnConversationUpdate = listener;
1223			this.mNotificationService.setIsInForeground(true);
1224			if (this.convChangedListenerCount < 2) {
1225				this.convChangedListenerCount++;
1226			}
1227		}
1228	}
1229
1230	public void removeOnConversationListChangedListener() {
1231		synchronized (this) {
1232			this.convChangedListenerCount--;
1233			if (this.convChangedListenerCount <= 0) {
1234				this.convChangedListenerCount = 0;
1235				this.mOnConversationUpdate = null;
1236				this.mNotificationService.setIsInForeground(false);
1237				if (checkListeners()) {
1238					switchToBackground();
1239				}
1240			}
1241		}
1242	}
1243
1244	public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1245		synchronized (this) {
1246			if (checkListeners()) {
1247				switchToForeground();
1248			}
1249			this.mOnShowErrorToast = onShowErrorToast;
1250			if (this.showErrorToastListenerCount < 2) {
1251				this.showErrorToastListenerCount++;
1252			}
1253		}
1254		this.mOnShowErrorToast = onShowErrorToast;
1255	}
1256
1257	public void removeOnShowErrorToastListener() {
1258		synchronized (this) {
1259			this.showErrorToastListenerCount--;
1260			if (this.showErrorToastListenerCount <= 0) {
1261				this.showErrorToastListenerCount = 0;
1262				this.mOnShowErrorToast = null;
1263				if (checkListeners()) {
1264					switchToBackground();
1265				}
1266			}
1267		}
1268	}
1269
1270	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1271		synchronized (this) {
1272			if (checkListeners()) {
1273				switchToForeground();
1274			}
1275			this.mOnAccountUpdate = listener;
1276			if (this.accountChangedListenerCount < 2) {
1277				this.accountChangedListenerCount++;
1278			}
1279		}
1280	}
1281
1282	public void removeOnAccountListChangedListener() {
1283		synchronized (this) {
1284			this.accountChangedListenerCount--;
1285			if (this.accountChangedListenerCount <= 0) {
1286				this.mOnAccountUpdate = null;
1287				this.accountChangedListenerCount = 0;
1288				if (checkListeners()) {
1289					switchToBackground();
1290				}
1291			}
1292		}
1293	}
1294
1295	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1296		synchronized (this) {
1297			if (checkListeners()) {
1298				switchToForeground();
1299			}
1300			this.mOnRosterUpdate = listener;
1301			if (this.rosterChangedListenerCount < 2) {
1302				this.rosterChangedListenerCount++;
1303			}
1304		}
1305	}
1306
1307	public void removeOnRosterUpdateListener() {
1308		synchronized (this) {
1309			this.rosterChangedListenerCount--;
1310			if (this.rosterChangedListenerCount <= 0) {
1311				this.rosterChangedListenerCount = 0;
1312				this.mOnRosterUpdate = null;
1313				if (checkListeners()) {
1314					switchToBackground();
1315				}
1316			}
1317		}
1318	}
1319
1320	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1321		synchronized (this) {
1322			if (checkListeners()) {
1323				switchToForeground();
1324			}
1325			this.mOnUpdateBlocklist = listener;
1326			if (this.updateBlocklistListenerCount < 2) {
1327				this.updateBlocklistListenerCount++;
1328			}
1329		}
1330	}
1331
1332	public void removeOnUpdateBlocklistListener() {
1333		synchronized (this) {
1334			this.updateBlocklistListenerCount--;
1335			if (this.updateBlocklistListenerCount <= 0) {
1336				this.updateBlocklistListenerCount = 0;
1337				this.mOnUpdateBlocklist = null;
1338				if (checkListeners()) {
1339					switchToBackground();
1340				}
1341			}
1342		}
1343	}
1344
1345	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1346		synchronized (this) {
1347			if (checkListeners()) {
1348				switchToForeground();
1349			}
1350			this.mOnMucRosterUpdate = listener;
1351			if (this.mucRosterChangedListenerCount < 2) {
1352				this.mucRosterChangedListenerCount++;
1353			}
1354		}
1355	}
1356
1357	public void removeOnMucRosterUpdateListener() {
1358		synchronized (this) {
1359			this.mucRosterChangedListenerCount--;
1360			if (this.mucRosterChangedListenerCount <= 0) {
1361				this.mucRosterChangedListenerCount = 0;
1362				this.mOnMucRosterUpdate = null;
1363				if (checkListeners()) {
1364					switchToBackground();
1365				}
1366			}
1367		}
1368	}
1369
1370	private boolean checkListeners() {
1371		return (this.mOnAccountUpdate == null
1372				&& this.mOnConversationUpdate == null
1373				&& this.mOnRosterUpdate == null
1374				&& this.mOnUpdateBlocklist == null
1375				&& this.mOnShowErrorToast == null);
1376	}
1377
1378	private void switchToForeground() {
1379		for (Account account : getAccounts()) {
1380			if (account.getStatus() == Account.State.ONLINE) {
1381				XmppConnection connection = account.getXmppConnection();
1382				if (connection != null && connection.getFeatures().csi()) {
1383					connection.sendActive();
1384				}
1385			}
1386		}
1387		Log.d(Config.LOGTAG, "app switched into foreground");
1388	}
1389
1390	private void switchToBackground() {
1391		for (Account account : getAccounts()) {
1392			if (account.getStatus() == Account.State.ONLINE) {
1393				XmppConnection connection = account.getXmppConnection();
1394				if (connection != null && connection.getFeatures().csi()) {
1395					connection.sendInactive();
1396				}
1397			}
1398		}
1399		for(Conversation conversation : getConversations()) {
1400			conversation.setIncomingChatState(ChatState.ACTIVE);
1401		}
1402		this.mNotificationService.setIsInForeground(false);
1403		Log.d(Config.LOGTAG, "app switched into background");
1404	}
1405
1406	private void connectMultiModeConversations(Account account) {
1407		List<Conversation> conversations = getConversations();
1408		for (Conversation conversation : conversations) {
1409			if ((conversation.getMode() == Conversation.MODE_MULTI)
1410					&& (conversation.getAccount() == account)) {
1411				conversation.resetMucOptions();
1412				joinMuc(conversation);
1413			}
1414		}
1415	}
1416
1417	public void joinMuc(Conversation conversation) {
1418		Account account = conversation.getAccount();
1419		account.pendingConferenceJoins.remove(conversation);
1420		account.pendingConferenceLeaves.remove(conversation);
1421		if (account.getStatus() == Account.State.ONLINE) {
1422			final String nick = conversation.getMucOptions().getProposedNick();
1423			final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1424			if (joinJid == null) {
1425				return; //safety net
1426			}
1427			Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1428			PresencePacket packet = new PresencePacket();
1429			packet.setFrom(conversation.getAccount().getJid());
1430			packet.setTo(joinJid);
1431			Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1432			if (conversation.getMucOptions().getPassword() != null) {
1433				x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1434			}
1435			x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1436			String sig = account.getPgpSignature();
1437			if (sig != null) {
1438				packet.addChild("status").setContent("online");
1439				packet.addChild("x", "jabber:x:signed").setContent(sig);
1440			}
1441			sendPresencePacket(account, packet);
1442			fetchConferenceConfiguration(conversation);
1443			if (!joinJid.equals(conversation.getJid())) {
1444				conversation.setContactJid(joinJid);
1445				databaseBackend.updateConversation(conversation);
1446			}
1447			conversation.setHasMessagesLeftOnServer(false);
1448		} else {
1449			account.pendingConferenceJoins.add(conversation);
1450		}
1451	}
1452
1453	public void providePasswordForMuc(Conversation conversation, String password) {
1454		if (conversation.getMode() == Conversation.MODE_MULTI) {
1455			conversation.getMucOptions().setPassword(password);
1456			if (conversation.getBookmark() != null) {
1457				conversation.getBookmark().setAutojoin(true);
1458				pushBookmarks(conversation.getAccount());
1459			}
1460			databaseBackend.updateConversation(conversation);
1461			joinMuc(conversation);
1462		}
1463	}
1464
1465	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1466		final MucOptions options = conversation.getMucOptions();
1467		final Jid joinJid = options.createJoinJid(nick);
1468		if (options.online()) {
1469			Account account = conversation.getAccount();
1470			options.setOnRenameListener(new OnRenameListener() {
1471
1472				@Override
1473				public void onSuccess() {
1474					conversation.setContactJid(joinJid);
1475					databaseBackend.updateConversation(conversation);
1476					Bookmark bookmark = conversation.getBookmark();
1477					if (bookmark != null) {
1478						bookmark.setNick(nick);
1479						pushBookmarks(bookmark.getAccount());
1480					}
1481					callback.success(conversation);
1482				}
1483
1484				@Override
1485				public void onFailure() {
1486					callback.error(R.string.nick_in_use, conversation);
1487				}
1488			});
1489
1490			PresencePacket packet = new PresencePacket();
1491			packet.setTo(joinJid);
1492			packet.setFrom(conversation.getAccount().getJid());
1493
1494			String sig = account.getPgpSignature();
1495			if (sig != null) {
1496				packet.addChild("status").setContent("online");
1497				packet.addChild("x", "jabber:x:signed").setContent(sig);
1498			}
1499			sendPresencePacket(account, packet);
1500		} else {
1501			conversation.setContactJid(joinJid);
1502			databaseBackend.updateConversation(conversation);
1503			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1504				Bookmark bookmark = conversation.getBookmark();
1505				if (bookmark != null) {
1506					bookmark.setNick(nick);
1507					pushBookmarks(bookmark.getAccount());
1508				}
1509				joinMuc(conversation);
1510			}
1511		}
1512	}
1513
1514	public void leaveMuc(Conversation conversation) {
1515		Account account = conversation.getAccount();
1516		account.pendingConferenceJoins.remove(conversation);
1517		account.pendingConferenceLeaves.remove(conversation);
1518		if (account.getStatus() == Account.State.ONLINE) {
1519			PresencePacket packet = new PresencePacket();
1520			packet.setTo(conversation.getJid());
1521			packet.setFrom(conversation.getAccount().getJid());
1522			packet.setAttribute("type", "unavailable");
1523			sendPresencePacket(conversation.getAccount(), packet);
1524			conversation.getMucOptions().setOffline();
1525			conversation.deregisterWithBookmark();
1526			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1527					+ ": leaving muc " + conversation.getJid());
1528		} else {
1529			account.pendingConferenceLeaves.add(conversation);
1530		}
1531	}
1532
1533	private String findConferenceServer(final Account account) {
1534		String server;
1535		if (account.getXmppConnection() != null) {
1536			server = account.getXmppConnection().getMucServer();
1537			if (server != null) {
1538				return server;
1539			}
1540		}
1541		for (Account other : getAccounts()) {
1542			if (other != account && other.getXmppConnection() != null) {
1543				server = other.getXmppConnection().getMucServer();
1544				if (server != null) {
1545					return server;
1546				}
1547			}
1548		}
1549		return null;
1550	}
1551
1552	public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1553		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1554		if (account.getStatus() == Account.State.ONLINE) {
1555			try {
1556				String server = findConferenceServer(account);
1557				if (server == null) {
1558					if (callback != null) {
1559						callback.error(R.string.no_conference_server_found, null);
1560					}
1561					return;
1562				}
1563				String name = new BigInteger(75, getRNG()).toString(32);
1564				Jid jid = Jid.fromParts(name, server, null);
1565				final Conversation conversation = findOrCreateConversation(account, jid, true);
1566				joinMuc(conversation);
1567				Bundle options = new Bundle();
1568				options.putString("muc#roomconfig_persistentroom", "1");
1569				options.putString("muc#roomconfig_membersonly", "1");
1570				options.putString("muc#roomconfig_publicroom", "0");
1571				options.putString("muc#roomconfig_whois", "anyone");
1572				pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1573					@Override
1574					public void onPushSucceeded() {
1575						for (Jid invite : jids) {
1576							invite(conversation, invite);
1577						}
1578						if (account.countPresences() > 1) {
1579							directInvite(conversation, account.getJid().toBareJid());
1580						}
1581						if (callback != null) {
1582							callback.success(conversation);
1583						}
1584					}
1585
1586					@Override
1587					public void onPushFailed() {
1588						if (callback != null) {
1589							callback.error(R.string.conference_creation_failed, conversation);
1590						}
1591					}
1592				});
1593
1594			} catch (InvalidJidException e) {
1595				if (callback != null) {
1596					callback.error(R.string.conference_creation_failed, null);
1597				}
1598			}
1599		} else {
1600			if (callback != null) {
1601				callback.error(R.string.not_connected_try_again, null);
1602			}
1603		}
1604	}
1605
1606	public void fetchConferenceConfiguration(final Conversation conversation) {
1607		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1608		request.setTo(conversation.getJid().toBareJid());
1609		request.query("http://jabber.org/protocol/disco#info");
1610		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1611			@Override
1612			public void onIqPacketReceived(Account account, IqPacket packet) {
1613				if (packet.getType() != IqPacket.TYPE.ERROR) {
1614					ArrayList<String> features = new ArrayList<>();
1615					for (Element child : packet.query().getChildren()) {
1616						if (child != null && child.getName().equals("feature")) {
1617							String var = child.getAttribute("var");
1618							if (var != null) {
1619								features.add(var);
1620							}
1621						}
1622					}
1623					conversation.getMucOptions().updateFeatures(features);
1624					updateConversationUi();
1625				}
1626			}
1627		});
1628	}
1629
1630	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1631		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1632		request.setTo(conversation.getJid().toBareJid());
1633		request.query("http://jabber.org/protocol/muc#owner");
1634		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1635			@Override
1636			public void onIqPacketReceived(Account account, IqPacket packet) {
1637				if (packet.getType() != IqPacket.TYPE.ERROR) {
1638					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1639					for (Field field : data.getFields()) {
1640						if (options.containsKey(field.getName())) {
1641							field.setValue(options.getString(field.getName()));
1642						}
1643					}
1644					data.submit();
1645					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1646					set.setTo(conversation.getJid().toBareJid());
1647					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1648					sendIqPacket(account, set, new OnIqPacketReceived() {
1649						@Override
1650						public void onIqPacketReceived(Account account, IqPacket packet) {
1651							if (packet.getType() == IqPacket.TYPE.RESULT) {
1652								if (callback != null) {
1653									callback.onPushSucceeded();
1654								}
1655							} else {
1656								if (callback != null) {
1657									callback.onPushFailed();
1658								}
1659							}
1660						}
1661					});
1662				} else {
1663					if (callback != null) {
1664						callback.onPushFailed();
1665					}
1666				}
1667			}
1668		});
1669	}
1670
1671	public void pushSubjectToConference(final Conversation conference, final String subject) {
1672		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1673		this.sendMessagePacket(conference.getAccount(), packet);
1674		final MucOptions mucOptions = conference.getMucOptions();
1675		final MucOptions.User self = mucOptions.getSelf();
1676		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1677			Bundle options = new Bundle();
1678			options.putString("muc#roomconfig_persistentroom", "1");
1679			this.pushConferenceConfiguration(conference, options, null);
1680		}
1681	}
1682
1683	public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1684		final Jid jid = user.toBareJid();
1685		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
1686		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1687			@Override
1688			public void onIqPacketReceived(Account account, IqPacket packet) {
1689				if (packet.getType() == IqPacket.TYPE.RESULT) {
1690					callback.onAffiliationChangedSuccessful(jid);
1691				} else {
1692					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
1693				}
1694			}
1695		});
1696	}
1697
1698	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
1699		List<Jid> jids = new ArrayList<>();
1700		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
1701			if (user.getAffiliation() == before && user.getJid() != null) {
1702				jids.add(user.getJid());
1703			}
1704		}
1705		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
1706		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
1707	}
1708
1709	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
1710		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
1711		Log.d(Config.LOGTAG, request.toString());
1712		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1713			@Override
1714			public void onIqPacketReceived(Account account, IqPacket packet) {
1715				Log.d(Config.LOGTAG, packet.toString());
1716				if (packet.getType() == IqPacket.TYPE.RESULT) {
1717					callback.onRoleChangedSuccessful(nick);
1718				} else {
1719					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
1720				}
1721			}
1722		});
1723	}
1724
1725	public void disconnect(Account account, boolean force) {
1726		if ((account.getStatus() == Account.State.ONLINE)
1727				|| (account.getStatus() == Account.State.DISABLED)) {
1728			if (!force) {
1729				List<Conversation> conversations = getConversations();
1730				for (Conversation conversation : conversations) {
1731					if (conversation.getAccount() == account) {
1732						if (conversation.getMode() == Conversation.MODE_MULTI) {
1733							leaveMuc(conversation);
1734						} else {
1735							if (conversation.endOtrIfNeeded()) {
1736								Log.d(Config.LOGTAG, account.getJid().toBareJid()
1737										+ ": ended otr session with "
1738										+ conversation.getJid());
1739							}
1740						}
1741					}
1742				}
1743				sendOfflinePresence(account);
1744			}
1745			account.getXmppConnection().disconnect(force);
1746		}
1747	}
1748
1749	@Override
1750	public IBinder onBind(Intent intent) {
1751		return mBinder;
1752	}
1753
1754	public void updateMessage(Message message) {
1755		databaseBackend.updateMessage(message);
1756		updateConversationUi();
1757	}
1758
1759	protected void syncDirtyContacts(Account account) {
1760		for (Contact contact : account.getRoster().getContacts()) {
1761			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1762				pushContactToServer(contact);
1763			}
1764			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1765				deleteContactOnServer(contact);
1766			}
1767		}
1768	}
1769
1770	public void createContact(Contact contact) {
1771		SharedPreferences sharedPref = getPreferences();
1772		boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1773		if (autoGrant) {
1774			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1775			contact.setOption(Contact.Options.ASKING);
1776		}
1777		pushContactToServer(contact);
1778	}
1779
1780	public void onOtrSessionEstablished(Conversation conversation) {
1781		final Account account = conversation.getAccount();
1782		final Session otrSession = conversation.getOtrSession();
1783		Log.d(Config.LOGTAG,
1784				account.getJid().toBareJid() + " otr session established with "
1785						+ conversation.getJid() + "/"
1786						+ otrSession.getSessionID().getUserID());
1787		conversation.findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
1788
1789			@Override
1790			public void onMessageFound(Message message) {
1791				SessionID id = otrSession.getSessionID();
1792				try {
1793					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
1794				} catch (InvalidJidException e) {
1795					return;
1796				}
1797				if (message.needsUploading()) {
1798					mJingleConnectionManager.createNewConnection(message);
1799				} else {
1800					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message, true);
1801					if (outPacket != null) {
1802						message.setStatus(Message.STATUS_SEND);
1803						databaseBackend.updateMessage(message);
1804						sendMessagePacket(account, outPacket);
1805					}
1806				}
1807				updateConversationUi();
1808			}
1809		});
1810	}
1811
1812	public boolean renewSymmetricKey(Conversation conversation) {
1813		Account account = conversation.getAccount();
1814		byte[] symmetricKey = new byte[32];
1815		this.mRandom.nextBytes(symmetricKey);
1816		Session otrSession = conversation.getOtrSession();
1817		if (otrSession != null) {
1818			MessagePacket packet = new MessagePacket();
1819			packet.setType(MessagePacket.TYPE_CHAT);
1820			packet.setFrom(account.getJid());
1821			packet.addChild("private", "urn:xmpp:carbons:2");
1822			packet.addChild("no-copy", "urn:xmpp:hints");
1823			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
1824					+ otrSession.getSessionID().getUserID());
1825			try {
1826				packet.setBody(otrSession
1827						.transformSending(CryptoHelper.FILETRANSFER
1828								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
1829				sendMessagePacket(account, packet);
1830				conversation.setSymmetricKey(symmetricKey);
1831				return true;
1832			} catch (OtrException e) {
1833				return false;
1834			}
1835		}
1836		return false;
1837	}
1838
1839	public void pushContactToServer(final Contact contact) {
1840		contact.resetOption(Contact.Options.DIRTY_DELETE);
1841		contact.setOption(Contact.Options.DIRTY_PUSH);
1842		final Account account = contact.getAccount();
1843		if (account.getStatus() == Account.State.ONLINE) {
1844			final boolean ask = contact.getOption(Contact.Options.ASKING);
1845			final boolean sendUpdates = contact
1846					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
1847					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
1848			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1849			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
1850			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
1851			if (sendUpdates) {
1852				sendPresencePacket(account,
1853						mPresenceGenerator.sendPresenceUpdatesTo(contact));
1854			}
1855			if (ask) {
1856				sendPresencePacket(account,
1857						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
1858			}
1859		}
1860	}
1861
1862	public void publishAvatar(final Account account,
1863							  final Uri image,
1864							  final UiCallback<Avatar> callback) {
1865		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
1866		final int size = Config.AVATAR_SIZE;
1867		final Avatar avatar = getFileBackend()
1868				.getPepAvatar(image, size, format);
1869		if (avatar != null) {
1870			avatar.height = size;
1871			avatar.width = size;
1872			if (format.equals(Bitmap.CompressFormat.WEBP)) {
1873				avatar.type = "image/webp";
1874			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1875				avatar.type = "image/jpeg";
1876			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
1877				avatar.type = "image/png";
1878			}
1879			if (!getFileBackend().save(avatar)) {
1880				callback.error(R.string.error_saving_avatar, avatar);
1881				return;
1882			}
1883			final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
1884			this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1885
1886				@Override
1887				public void onIqPacketReceived(Account account, IqPacket result) {
1888					if (result.getType() == IqPacket.TYPE.RESULT) {
1889						final IqPacket packet = XmppConnectionService.this.mIqGenerator
1890								.publishAvatarMetadata(avatar);
1891						sendIqPacket(account, packet, new OnIqPacketReceived() {
1892
1893							@Override
1894							public void onIqPacketReceived(Account account,
1895														   IqPacket result) {
1896								if (result.getType() == IqPacket.TYPE.RESULT) {
1897									if (account.setAvatar(avatar.getFilename())) {
1898										getAvatarService().clear(account);
1899										databaseBackend.updateAccount(account);
1900									}
1901									callback.success(avatar);
1902								} else {
1903									callback.error(
1904											R.string.error_publish_avatar_server_reject,
1905											avatar);
1906								}
1907							}
1908						});
1909					} else {
1910						callback.error(
1911								R.string.error_publish_avatar_server_reject,
1912								avatar);
1913					}
1914				}
1915			});
1916		} else {
1917			callback.error(R.string.error_publish_avatar_converting, null);
1918		}
1919	}
1920
1921	public void fetchAvatar(Account account, Avatar avatar) {
1922		fetchAvatar(account, avatar, null);
1923	}
1924
1925	private static String generateFetchKey(Account account, final Avatar avatar) {
1926		return account.getJid().toBareJid()+"_"+avatar.owner+"_"+avatar.sha1sum;
1927	}
1928
1929	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
1930		final String KEY = generateFetchKey(account, avatar);
1931		synchronized(this.mInProgressAvatarFetches) {
1932			if (this.mInProgressAvatarFetches.contains(KEY)) {
1933				return;
1934			} else {
1935				switch (avatar.origin) {
1936					case PEP:
1937						this.mInProgressAvatarFetches.add(KEY);
1938						fetchAvatarPep(account, avatar, callback);
1939						break;
1940					case VCARD:
1941						this.mInProgressAvatarFetches.add(KEY);
1942						fetchAvatarVcard(account, avatar, callback);
1943						break;
1944				}
1945			}
1946		}
1947	}
1948
1949	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
1950		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
1951		sendIqPacket(account, packet, new OnIqPacketReceived() {
1952
1953			@Override
1954			public void onIqPacketReceived(Account account, IqPacket result) {
1955				synchronized (mInProgressAvatarFetches) {
1956					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
1957				}
1958				final String ERROR = account.getJid().toBareJid()
1959						+ ": fetching avatar for " + avatar.owner + " failed ";
1960				if (result.getType() == IqPacket.TYPE.RESULT) {
1961					avatar.image = mIqParser.avatarData(result);
1962					if (avatar.image != null) {
1963						if (getFileBackend().save(avatar)) {
1964							if (account.getJid().toBareJid().equals(avatar.owner)) {
1965								if (account.setAvatar(avatar.getFilename())) {
1966									databaseBackend.updateAccount(account);
1967								}
1968								getAvatarService().clear(account);
1969								updateConversationUi();
1970								updateAccountUi();
1971							} else {
1972								Contact contact = account.getRoster()
1973										.getContact(avatar.owner);
1974								contact.setAvatar(avatar);
1975								getAvatarService().clear(contact);
1976								updateConversationUi();
1977								updateRosterUi();
1978							}
1979							if (callback != null) {
1980								callback.success(avatar);
1981							}
1982							Log.d(Config.LOGTAG, account.getJid().toBareJid()
1983									+ ": succesfuly fetched pep avatar for " + avatar.owner);
1984							return;
1985						}
1986					} else {
1987
1988						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
1989					}
1990				} else {
1991					Element error = result.findChild("error");
1992					if (error == null) {
1993						Log.d(Config.LOGTAG, ERROR + "(server error)");
1994					} else {
1995						Log.d(Config.LOGTAG, ERROR + error.toString());
1996					}
1997				}
1998				if (callback != null) {
1999					callback.error(0, null);
2000				}
2001
2002			}
2003		});
2004	}
2005
2006	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2007		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2008		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2009			@Override
2010			public void onIqPacketReceived(Account account, IqPacket packet) {
2011				synchronized (mInProgressAvatarFetches) {
2012					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2013				}
2014				if (packet.getType() == IqPacket.TYPE.RESULT) {
2015					Element vCard = packet.findChild("vCard", "vcard-temp");
2016					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2017					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2018					if (image != null) {
2019						avatar.image = image;
2020						if (getFileBackend().save(avatar)) {
2021							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2022									+ ": successfully fetched vCard avatar for " + avatar.owner);
2023							Contact contact = account.getRoster()
2024									.getContact(avatar.owner);
2025							contact.setAvatar(avatar);
2026							getAvatarService().clear(contact);
2027							updateConversationUi();
2028							updateRosterUi();
2029						}
2030					}
2031				}
2032			}
2033		});
2034	}
2035
2036	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2037		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2038		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2039
2040			@Override
2041			public void onIqPacketReceived(Account account, IqPacket packet) {
2042				if (packet.getType() == IqPacket.TYPE.RESULT) {
2043					Element pubsub = packet.findChild("pubsub",
2044							"http://jabber.org/protocol/pubsub");
2045					if (pubsub != null) {
2046						Element items = pubsub.findChild("items");
2047						if (items != null) {
2048							Avatar avatar = Avatar.parseMetadata(items);
2049							if (avatar != null) {
2050								avatar.owner = account.getJid().toBareJid();
2051								if (fileBackend.isAvatarCached(avatar)) {
2052									if (account.setAvatar(avatar.getFilename())) {
2053										databaseBackend.updateAccount(account);
2054									}
2055									getAvatarService().clear(account);
2056									callback.success(avatar);
2057								} else {
2058									fetchAvatarPep(account, avatar, callback);
2059								}
2060								return;
2061							}
2062						}
2063					}
2064				}
2065				callback.error(0, null);
2066			}
2067		});
2068	}
2069
2070	public void deleteContactOnServer(Contact contact) {
2071		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2072		contact.resetOption(Contact.Options.DIRTY_PUSH);
2073		contact.setOption(Contact.Options.DIRTY_DELETE);
2074		Account account = contact.getAccount();
2075		if (account.getStatus() == Account.State.ONLINE) {
2076			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2077			Element item = iq.query(Xmlns.ROSTER).addChild("item");
2078			item.setAttribute("jid", contact.getJid().toString());
2079			item.setAttribute("subscription", "remove");
2080			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2081		}
2082	}
2083
2084	public void updateConversation(Conversation conversation) {
2085		this.databaseBackend.updateConversation(conversation);
2086	}
2087
2088	public void reconnectAccount(final Account account, final boolean force) {
2089		synchronized (account) {
2090			if (account.getXmppConnection() != null) {
2091				disconnect(account, force);
2092			}
2093			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2094
2095				synchronized (this.mInProgressAvatarFetches) {
2096					for(Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext();) {
2097						final String KEY = iterator.next();
2098						if (KEY.startsWith(account.getJid().toBareJid()+"_")) {
2099							iterator.remove();
2100						}
2101					}
2102				}
2103
2104				if (account.getXmppConnection() == null) {
2105					account.setXmppConnection(createConnection(account));
2106				}
2107				Thread thread = new Thread(account.getXmppConnection());
2108				thread.start();
2109				scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
2110			} else {
2111				account.getRoster().clearPresences();
2112				account.setXmppConnection(null);
2113			}
2114		}
2115	}
2116
2117	public void reconnectAccountInBackground(final Account account) {
2118		new Thread(new Runnable() {
2119			@Override
2120			public void run() {
2121				reconnectAccount(account,false);
2122			}
2123		}).start();
2124	}
2125
2126	public void invite(Conversation conversation, Jid contact) {
2127		Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": inviting "+contact+" to "+conversation.getJid().toBareJid());
2128		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2129		sendMessagePacket(conversation.getAccount(), packet);
2130	}
2131
2132	public void directInvite(Conversation conversation, Jid jid) {
2133		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2134		sendMessagePacket(conversation.getAccount(),packet);
2135	}
2136
2137	public void resetSendingToWaiting(Account account) {
2138		for (Conversation conversation : getConversations()) {
2139			if (conversation.getAccount() == account) {
2140				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2141
2142					@Override
2143					public void onMessageFound(Message message) {
2144						markMessage(message, Message.STATUS_WAITING);
2145					}
2146				});
2147			}
2148		}
2149	}
2150
2151	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2152		if (uuid == null) {
2153			return null;
2154		}
2155		for (Conversation conversation : getConversations()) {
2156			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2157				final Message message = conversation.findSentMessageWithUuid(uuid);
2158				if (message != null) {
2159					markMessage(message, status);
2160				}
2161				return message;
2162			}
2163		}
2164		return null;
2165	}
2166
2167	public boolean markMessage(Conversation conversation, String uuid,
2168							   int status) {
2169		if (uuid == null) {
2170			return false;
2171		} else {
2172			Message message = conversation.findSentMessageWithUuid(uuid);
2173			if (message != null) {
2174				markMessage(message, status);
2175				return true;
2176			} else {
2177				return false;
2178			}
2179		}
2180	}
2181
2182	public void markMessage(Message message, int status) {
2183		if (status == Message.STATUS_SEND_FAILED
2184				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2185				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2186			return;
2187		}
2188		message.setStatus(status);
2189		databaseBackend.updateMessage(message);
2190		updateConversationUi();
2191	}
2192
2193	public SharedPreferences getPreferences() {
2194		return PreferenceManager
2195				.getDefaultSharedPreferences(getApplicationContext());
2196	}
2197
2198	public boolean forceEncryption() {
2199		return getPreferences().getBoolean("force_encryption", false);
2200	}
2201
2202	public boolean confirmMessages() {
2203		return getPreferences().getBoolean("confirm_messages", true);
2204	}
2205
2206	public boolean sendChatStates() {
2207		return getPreferences().getBoolean("chat_states", false);
2208	}
2209
2210	public boolean saveEncryptedMessages() {
2211		return !getPreferences().getBoolean("dont_save_encrypted", false);
2212	}
2213
2214	public boolean indicateReceived() {
2215		return getPreferences().getBoolean("indicate_received", false);
2216	}
2217
2218	public int unreadCount() {
2219		int count = 0;
2220		for(Conversation conversation : getConversations()) {
2221			count += conversation.unreadCount();
2222		}
2223		return count;
2224	}
2225
2226
2227	public void showErrorToastInUi(int resId) {
2228		if (mOnShowErrorToast != null) {
2229			mOnShowErrorToast.onShowErrorToast(resId);
2230		}
2231	}
2232
2233	public void updateConversationUi() {
2234		if (mOnConversationUpdate != null) {
2235			mOnConversationUpdate.onConversationUpdate();
2236		}
2237	}
2238
2239	public void updateAccountUi() {
2240		if (mOnAccountUpdate != null) {
2241			mOnAccountUpdate.onAccountUpdate();
2242		}
2243	}
2244
2245	public void updateRosterUi() {
2246		if (mOnRosterUpdate != null) {
2247			mOnRosterUpdate.onRosterUpdate();
2248		}
2249	}
2250
2251	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2252		if (mOnUpdateBlocklist != null) {
2253			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2254		}
2255	}
2256
2257	public void updateMucRosterUi() {
2258		if (mOnMucRosterUpdate != null) {
2259			mOnMucRosterUpdate.onMucRosterUpdate();
2260		}
2261	}
2262
2263	public Account findAccountByJid(final Jid accountJid) {
2264		for (Account account : this.accounts) {
2265			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2266				return account;
2267			}
2268		}
2269		return null;
2270	}
2271
2272	public Conversation findConversationByUuid(String uuid) {
2273		for (Conversation conversation : getConversations()) {
2274			if (conversation.getUuid().equals(uuid)) {
2275				return conversation;
2276			}
2277		}
2278		return null;
2279	}
2280
2281	public void markRead(final Conversation conversation) {
2282		mNotificationService.clear(conversation);
2283		conversation.markRead();
2284		updateUnreadCountBadge();
2285	}
2286
2287	public synchronized void updateUnreadCountBadge() {
2288		int count = unreadCount();
2289		if (unreadCount != count) {
2290			Log.d(Config.LOGTAG, "update unread count to " + count);
2291			if (count > 0) {
2292				ShortcutBadger.with(getApplicationContext()).count(count);
2293			} else {
2294				ShortcutBadger.with(getApplicationContext()).remove();
2295			}
2296			unreadCount = count;
2297		}
2298	}
2299
2300	public void sendReadMarker(final Conversation conversation) {
2301		final Message markable = conversation.getLatestMarkableMessage();
2302		this.markRead(conversation);
2303		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2304			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2305			Account account = conversation.getAccount();
2306			final Jid to = markable.getCounterpart();
2307			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2308			this.sendMessagePacket(conversation.getAccount(), packet);
2309		}
2310		updateConversationUi();
2311	}
2312
2313	public SecureRandom getRNG() {
2314		return this.mRandom;
2315	}
2316
2317	public MemorizingTrustManager getMemorizingTrustManager() {
2318		return this.mMemorizingTrustManager;
2319	}
2320
2321	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2322		this.mMemorizingTrustManager = trustManager;
2323	}
2324
2325	public void updateMemorizingTrustmanager() {
2326		final MemorizingTrustManager tm;
2327		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2328		if (dontTrustSystemCAs) {
2329			 tm = new MemorizingTrustManager(getApplicationContext(), null);
2330		} else {
2331			tm = new MemorizingTrustManager(getApplicationContext());
2332		}
2333		setMemorizingTrustManager(tm);
2334	}
2335
2336	public PowerManager getPowerManager() {
2337		return this.pm;
2338	}
2339
2340	public LruCache<String, Bitmap> getBitmapCache() {
2341		return this.mBitmapCache;
2342	}
2343
2344	public void syncRosterToDisk(final Account account) {
2345		Runnable runnable = new Runnable() {
2346
2347			@Override
2348			public void run() {
2349				databaseBackend.writeRoster(account.getRoster());
2350			}
2351		};
2352		mDatabaseExecutor.execute(runnable);
2353
2354	}
2355
2356	public List<String> getKnownHosts() {
2357		final List<String> hosts = new ArrayList<>();
2358		for (final Account account : getAccounts()) {
2359			if (!hosts.contains(account.getServer().toString())) {
2360				hosts.add(account.getServer().toString());
2361			}
2362			for (final Contact contact : account.getRoster().getContacts()) {
2363				if (contact.showInRoster()) {
2364					final String server = contact.getServer().toString();
2365					if (server != null && !hosts.contains(server)) {
2366						hosts.add(server);
2367					}
2368				}
2369			}
2370		}
2371		return hosts;
2372	}
2373
2374	public List<String> getKnownConferenceHosts() {
2375		final ArrayList<String> mucServers = new ArrayList<>();
2376		for (final Account account : accounts) {
2377			if (account.getXmppConnection() != null) {
2378				final String server = account.getXmppConnection().getMucServer();
2379				if (server != null && !mucServers.contains(server)) {
2380					mucServers.add(server);
2381				}
2382			}
2383		}
2384		return mucServers;
2385	}
2386
2387	public void sendMessagePacket(Account account, MessagePacket packet) {
2388		XmppConnection connection = account.getXmppConnection();
2389		if (connection != null) {
2390			connection.sendMessagePacket(packet);
2391		}
2392	}
2393
2394	public void sendPresencePacket(Account account, PresencePacket packet) {
2395		XmppConnection connection = account.getXmppConnection();
2396		if (connection != null) {
2397			connection.sendPresencePacket(packet);
2398		}
2399	}
2400
2401	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2402		final XmppConnection connection = account.getXmppConnection();
2403		if (connection != null) {
2404			connection.sendIqPacket(packet, callback);
2405		}
2406	}
2407
2408	public void sendPresence(final Account account) {
2409		sendPresencePacket(account, mPresenceGenerator.sendPresence(account));
2410	}
2411
2412	public void sendOfflinePresence(final Account account) {
2413		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2414	}
2415
2416	public MessageGenerator getMessageGenerator() {
2417		return this.mMessageGenerator;
2418	}
2419
2420	public PresenceGenerator getPresenceGenerator() {
2421		return this.mPresenceGenerator;
2422	}
2423
2424	public IqGenerator getIqGenerator() {
2425		return this.mIqGenerator;
2426	}
2427
2428	public IqParser getIqParser() {
2429		return this.mIqParser;
2430	}
2431
2432	public JingleConnectionManager getJingleConnectionManager() {
2433		return this.mJingleConnectionManager;
2434	}
2435
2436	public MessageArchiveService getMessageArchiveService() {
2437		return this.mMessageArchiveService;
2438	}
2439
2440	public List<Contact> findContacts(Jid jid) {
2441		ArrayList<Contact> contacts = new ArrayList<>();
2442		for (Account account : getAccounts()) {
2443			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2444				Contact contact = account.getRoster().getContactFromRoster(jid);
2445				if (contact != null) {
2446					contacts.add(contact);
2447				}
2448			}
2449		}
2450		return contacts;
2451	}
2452
2453	public NotificationService getNotificationService() {
2454		return this.mNotificationService;
2455	}
2456
2457	public HttpConnectionManager getHttpConnectionManager() {
2458		return this.mHttpConnectionManager;
2459	}
2460
2461	public void resendFailedMessages(final Message message) {
2462		final Collection<Message> messages = new ArrayList<>();
2463		Message current = message;
2464		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2465			messages.add(current);
2466			if (current.mergeable(current.next())) {
2467				current = current.next();
2468			} else {
2469				break;
2470			}
2471		}
2472		for (final Message msg : messages) {
2473			markMessage(msg, Message.STATUS_WAITING);
2474			this.resendMessage(msg);
2475		}
2476	}
2477
2478	public void clearConversationHistory(final Conversation conversation) {
2479		conversation.clearMessages();
2480		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2481		new Thread(new Runnable() {
2482			@Override
2483			public void run() {
2484				databaseBackend.deleteMessagesInConversation(conversation);
2485			}
2486		}).start();
2487	}
2488
2489	public void sendBlockRequest(final Blockable blockable) {
2490		if (blockable != null && blockable.getBlockedJid() != null) {
2491			final Jid jid = blockable.getBlockedJid();
2492			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2493
2494				@Override
2495				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2496					if (packet.getType() == IqPacket.TYPE.RESULT) {
2497						account.getBlocklist().add(jid);
2498						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2499					}
2500				}
2501			});
2502		}
2503	}
2504
2505	public void sendUnblockRequest(final Blockable blockable) {
2506		if (blockable != null && blockable.getJid() != null) {
2507			final Jid jid = blockable.getBlockedJid();
2508			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2509				@Override
2510				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2511					if (packet.getType() == IqPacket.TYPE.RESULT) {
2512						account.getBlocklist().remove(jid);
2513						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2514					}
2515				}
2516			});
2517		}
2518	}
2519
2520	public interface OnMoreMessagesLoaded {
2521		public void onMoreMessagesLoaded(int count, Conversation conversation);
2522
2523		public void informUser(int r);
2524	}
2525
2526	public interface OnAccountPasswordChanged {
2527		public void onPasswordChangeSucceeded();
2528
2529		public void onPasswordChangeFailed();
2530	}
2531
2532	public interface OnAffiliationChanged {
2533		public void onAffiliationChangedSuccessful(Jid jid);
2534
2535		public void onAffiliationChangeFailed(Jid jid, int resId);
2536	}
2537
2538	public interface OnRoleChanged {
2539		public void onRoleChangedSuccessful(String nick);
2540
2541		public void onRoleChangeFailed(String nick, int resid);
2542	}
2543
2544	public interface OnConversationUpdate {
2545		public void onConversationUpdate();
2546	}
2547
2548	public interface OnAccountUpdate {
2549		public void onAccountUpdate();
2550	}
2551
2552	public interface OnRosterUpdate {
2553		public void onRosterUpdate();
2554	}
2555
2556	public interface OnMucRosterUpdate {
2557		public void onMucRosterUpdate();
2558	}
2559
2560	public interface OnConferenceOptionsPushed {
2561		public void onPushSucceeded();
2562
2563		public void onPushFailed();
2564	}
2565
2566	public interface OnShowErrorToast {
2567		void onShowErrorToast(int resId);
2568	}
2569
2570	public class XmppConnectionBinder extends Binder {
2571		public XmppConnectionService getService() {
2572			return XmppConnectionService.this;
2573		}
2574	}
2575}