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",
 834				account.getRosterVersion());
 835		account.getXmppConnection().sendIqPacket(iqPacket, mIqParser);
 836	}
 837
 838	public void fetchBookmarks(final Account account) {
 839		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
 840		final Element query = iqPacket.query("jabber:iq:private");
 841		query.addChild("storage", "storage:bookmarks");
 842		final OnIqPacketReceived callback = new OnIqPacketReceived() {
 843
 844			@Override
 845			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 846				final Element query = packet.query();
 847				final List<Bookmark> bookmarks = new CopyOnWriteArrayList<>();
 848				final Element storage = query.findChild("storage",
 849						"storage:bookmarks");
 850				if (storage != null) {
 851					for (final Element item : storage.getChildren()) {
 852						if (item.getName().equals("conference")) {
 853							final Bookmark bookmark = Bookmark.parse(item, account);
 854							bookmarks.add(bookmark);
 855							Conversation conversation = find(bookmark);
 856							if (conversation != null) {
 857								conversation.setBookmark(bookmark);
 858							} else if (bookmark.autojoin() && bookmark.getJid() != null) {
 859								conversation = findOrCreateConversation(
 860										account, bookmark.getJid(), true);
 861								conversation.setBookmark(bookmark);
 862								joinMuc(conversation);
 863							}
 864						}
 865					}
 866				}
 867				account.setBookmarks(bookmarks);
 868			}
 869		};
 870		sendIqPacket(account, iqPacket, callback);
 871	}
 872
 873	public void pushBookmarks(Account account) {
 874		IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
 875		Element query = iqPacket.query("jabber:iq:private");
 876		Element storage = query.addChild("storage", "storage:bookmarks");
 877		for (Bookmark bookmark : account.getBookmarks()) {
 878			storage.addChild(bookmark);
 879		}
 880		sendIqPacket(account, iqPacket, mDefaultIqHandler);
 881	}
 882
 883	public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
 884		if (mPhoneContactMergerThread != null) {
 885			mPhoneContactMergerThread.interrupt();
 886		}
 887		mPhoneContactMergerThread = new Thread(new Runnable() {
 888			@Override
 889			public void run() {
 890				Log.d(Config.LOGTAG,"start merging phone contacts with roster");
 891				for (Account account : accounts) {
 892					List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
 893					for (Bundle phoneContact : phoneContacts) {
 894						if (Thread.interrupted()) {
 895							Log.d(Config.LOGTAG,"interrupted merging phone contacts");
 896							return;
 897						}
 898						Jid jid;
 899						try {
 900							jid = Jid.fromString(phoneContact.getString("jid"));
 901						} catch (final InvalidJidException e) {
 902							continue;
 903						}
 904						final Contact contact = account.getRoster().getContact(jid);
 905						String systemAccount = phoneContact.getInt("phoneid")
 906							+ "#"
 907							+ phoneContact.getString("lookup");
 908						contact.setSystemAccount(systemAccount);
 909						if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
 910							getAvatarService().clear(contact);
 911						}
 912						contact.setSystemName(phoneContact.getString("displayname"));
 913						withSystemAccounts.remove(contact);
 914					}
 915					for(Contact contact : withSystemAccounts) {
 916						contact.setSystemAccount(null);
 917						contact.setSystemName(null);
 918						if (contact.setPhotoUri(null)) {
 919							getAvatarService().clear(contact);
 920						}
 921					}
 922				}
 923				Log.d(Config.LOGTAG,"finished merging phone contacts");
 924				updateAccountUi();
 925			}
 926		});
 927		mPhoneContactMergerThread.start();
 928	}
 929
 930	private void restoreFromDatabase() {
 931		synchronized (this.conversations) {
 932			final Map<String, Account> accountLookupTable = new Hashtable<>();
 933			for (Account account : this.accounts) {
 934				accountLookupTable.put(account.getUuid(), account);
 935			}
 936			this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
 937			for (Conversation conversation : this.conversations) {
 938				Account account = accountLookupTable.get(conversation.getAccountUuid());
 939				conversation.setAccount(account);
 940			}
 941			Runnable runnable =new Runnable() {
 942				@Override
 943				public void run() {
 944					Log.d(Config.LOGTAG,"restoring roster");
 945					for(Account account : accounts) {
 946						databaseBackend.readRoster(account.getRoster());
 947					}
 948					getBitmapCache().evictAll();
 949					Looper.prepare();
 950					PhoneHelper.loadPhoneContacts(getApplicationContext(),
 951							new CopyOnWriteArrayList<Bundle>(),
 952							XmppConnectionService.this);
 953					Log.d(Config.LOGTAG,"restoring messages");
 954					for (Conversation conversation : conversations) {
 955						conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
 956						checkDeletedFiles(conversation);
 957					}
 958					mRestoredFromDatabase = true;
 959					Log.d(Config.LOGTAG,"restored all messages");
 960					updateConversationUi();
 961				}
 962			};
 963			mDatabaseExecutor.execute(runnable);
 964		}
 965	}
 966
 967	public List<Conversation> getConversations() {
 968		return this.conversations;
 969	}
 970
 971	private void checkDeletedFiles(Conversation conversation) {
 972		conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
 973
 974			@Override
 975			public void onMessageFound(Message message) {
 976				if (!getFileBackend().isFileAvailable(message)) {
 977					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
 978				}
 979			}
 980		});
 981	}
 982
 983	private void markFileDeleted(String uuid) {
 984		for (Conversation conversation : getConversations()) {
 985			Message message = conversation.findMessageWithFileAndUuid(uuid);
 986			if (message != null) {
 987				if (!getFileBackend().isFileAvailable(message)) {
 988					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
 989					updateConversationUi();
 990				}
 991				return;
 992			}
 993		}
 994	}
 995
 996	public void populateWithOrderedConversations(final List<Conversation> list) {
 997		populateWithOrderedConversations(list, true);
 998	}
 999
1000	public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1001		list.clear();
1002		if (includeNoFileUpload) {
1003			list.addAll(getConversations());
1004		} else {
1005			for (Conversation conversation : getConversations()) {
1006				if (conversation.getMode() == Conversation.MODE_SINGLE
1007						|| conversation.getAccount().httpUploadAvailable()) {
1008					list.add(conversation);
1009				}
1010			}
1011		}
1012		Collections.sort(list, new Comparator<Conversation>() {
1013			@Override
1014			public int compare(Conversation lhs, Conversation rhs) {
1015				Message left = lhs.getLatestMessage();
1016				Message right = rhs.getLatestMessage();
1017				if (left.getTimeSent() > right.getTimeSent()) {
1018					return -1;
1019				} else if (left.getTimeSent() < right.getTimeSent()) {
1020					return 1;
1021				} else {
1022					return 0;
1023				}
1024			}
1025		});
1026	}
1027
1028	public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1029		Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1030		if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation,callback)) {
1031			return;
1032		}
1033		Runnable runnable = new Runnable() {
1034			@Override
1035			public void run() {
1036				final Account account = conversation.getAccount();
1037				List<Message> messages = databaseBackend.getMessages(conversation, 50,timestamp);
1038				if (messages.size() > 0) {
1039					conversation.addAll(0, messages);
1040					checkDeletedFiles(conversation);
1041					callback.onMoreMessagesLoaded(messages.size(), conversation);
1042				} else if (conversation.hasMessagesLeftOnServer()
1043						&& account.isOnlineAndConnected()
1044						&& account.getXmppConnection().getFeatures().mam()) {
1045					MessageArchiveService.Query query = getMessageArchiveService().query(conversation,0,timestamp - 1);
1046					if (query != null) {
1047						query.setCallback(callback);
1048					}
1049					callback.informUser(R.string.fetching_history_from_server);
1050				}
1051			}
1052		};
1053		mDatabaseExecutor.execute(runnable);
1054	}
1055
1056	public List<Account> getAccounts() {
1057		return this.accounts;
1058	}
1059
1060	public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1061		for (final Conversation conversation : haystack) {
1062			if (conversation.getContact() == contact) {
1063				return conversation;
1064			}
1065		}
1066		return null;
1067	}
1068
1069	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1070		if (jid == null) {
1071			return null;
1072		}
1073		for (final Conversation conversation : haystack) {
1074			if ((account == null || conversation.getAccount() == account)
1075					&& (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1076				return conversation;
1077			}
1078		}
1079		return null;
1080	}
1081
1082	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1083		return this.findOrCreateConversation(account, jid, muc, null);
1084	}
1085
1086	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1087		synchronized (this.conversations) {
1088			Conversation conversation = find(account, jid);
1089			if (conversation != null) {
1090				return conversation;
1091			}
1092			conversation = databaseBackend.findConversation(account, jid);
1093			if (conversation != null) {
1094				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1095				conversation.setAccount(account);
1096				if (muc) {
1097					conversation.setMode(Conversation.MODE_MULTI);
1098					conversation.setContactJid(jid);
1099				} else {
1100					conversation.setMode(Conversation.MODE_SINGLE);
1101					conversation.setContactJid(jid.toBareJid());
1102				}
1103				conversation.setNextEncryption(-1);
1104				conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1105				this.databaseBackend.updateConversation(conversation);
1106			} else {
1107				String conversationName;
1108				Contact contact = account.getRoster().getContact(jid);
1109				if (contact != null) {
1110					conversationName = contact.getDisplayName();
1111				} else {
1112					conversationName = jid.getLocalpart();
1113				}
1114				if (muc) {
1115					conversation = new Conversation(conversationName, account, jid,
1116							Conversation.MODE_MULTI);
1117				} else {
1118					conversation = new Conversation(conversationName, account, jid.toBareJid(),
1119							Conversation.MODE_SINGLE);
1120				}
1121				this.databaseBackend.createConversation(conversation);
1122			}
1123			if (account.getXmppConnection() != null
1124					&& account.getXmppConnection().getFeatures().mam()
1125					&& !muc) {
1126				if (query == null) {
1127					this.mMessageArchiveService.query(conversation);
1128				} else {
1129					if (query.getConversation() == null) {
1130						this.mMessageArchiveService.query(conversation, query.getStart());
1131					}
1132				}
1133			}
1134			checkDeletedFiles(conversation);
1135			this.conversations.add(conversation);
1136			updateConversationUi();
1137			return conversation;
1138		}
1139	}
1140
1141	public void archiveConversation(Conversation conversation) {
1142		getNotificationService().clear(conversation);
1143		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1144		conversation.setNextEncryption(-1);
1145		synchronized (this.conversations) {
1146			if (conversation.getMode() == Conversation.MODE_MULTI) {
1147				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1148					Bookmark bookmark = conversation.getBookmark();
1149					if (bookmark != null && bookmark.autojoin()) {
1150						bookmark.setAutojoin(false);
1151						pushBookmarks(bookmark.getAccount());
1152					}
1153				}
1154				leaveMuc(conversation);
1155			} else {
1156				conversation.endOtrIfNeeded();
1157			}
1158			this.databaseBackend.updateConversation(conversation);
1159			this.conversations.remove(conversation);
1160			updateConversationUi();
1161		}
1162	}
1163
1164	public void createAccount(final Account account) {
1165		account.initAccountServices(this);
1166		databaseBackend.createAccount(account);
1167		this.accounts.add(account);
1168		this.reconnectAccountInBackground(account);
1169		updateAccountUi();
1170	}
1171
1172	public void updateAccount(final Account account) {
1173		this.statusListener.onStatusChanged(account);
1174		databaseBackend.updateAccount(account);
1175		reconnectAccount(account, false);
1176		updateAccountUi();
1177		getNotificationService().updateErrorNotification();
1178	}
1179
1180	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1181		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1182		sendIqPacket(account, iq, new OnIqPacketReceived() {
1183			@Override
1184			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1185				if (packet.getType() == IqPacket.TYPE.RESULT) {
1186					account.setPassword(newPassword);
1187					databaseBackend.updateAccount(account);
1188					callback.onPasswordChangeSucceeded();
1189				} else {
1190					callback.onPasswordChangeFailed();
1191				}
1192			}
1193		});
1194	}
1195
1196	public void deleteAccount(final Account account) {
1197		synchronized (this.conversations) {
1198			for (final Conversation conversation : conversations) {
1199				if (conversation.getAccount() == account) {
1200					if (conversation.getMode() == Conversation.MODE_MULTI) {
1201						leaveMuc(conversation);
1202					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1203						conversation.endOtrIfNeeded();
1204					}
1205					conversations.remove(conversation);
1206				}
1207			}
1208			if (account.getXmppConnection() != null) {
1209				this.disconnect(account, true);
1210			}
1211			databaseBackend.deleteAccount(account);
1212			this.accounts.remove(account);
1213			updateAccountUi();
1214			getNotificationService().updateErrorNotification();
1215		}
1216	}
1217
1218	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1219		synchronized (this) {
1220			if (checkListeners()) {
1221				switchToForeground();
1222			}
1223			this.mOnConversationUpdate = listener;
1224			this.mNotificationService.setIsInForeground(true);
1225			if (this.convChangedListenerCount < 2) {
1226				this.convChangedListenerCount++;
1227			}
1228		}
1229	}
1230
1231	public void removeOnConversationListChangedListener() {
1232		synchronized (this) {
1233			this.convChangedListenerCount--;
1234			if (this.convChangedListenerCount <= 0) {
1235				this.convChangedListenerCount = 0;
1236				this.mOnConversationUpdate = null;
1237				this.mNotificationService.setIsInForeground(false);
1238				if (checkListeners()) {
1239					switchToBackground();
1240				}
1241			}
1242		}
1243	}
1244
1245	public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1246		synchronized (this) {
1247			if (checkListeners()) {
1248				switchToForeground();
1249			}
1250			this.mOnShowErrorToast = onShowErrorToast;
1251			if (this.showErrorToastListenerCount < 2) {
1252				this.showErrorToastListenerCount++;
1253			}
1254		}
1255		this.mOnShowErrorToast = onShowErrorToast;
1256	}
1257
1258	public void removeOnShowErrorToastListener() {
1259		synchronized (this) {
1260			this.showErrorToastListenerCount--;
1261			if (this.showErrorToastListenerCount <= 0) {
1262				this.showErrorToastListenerCount = 0;
1263				this.mOnShowErrorToast = null;
1264				if (checkListeners()) {
1265					switchToBackground();
1266				}
1267			}
1268		}
1269	}
1270
1271	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1272		synchronized (this) {
1273			if (checkListeners()) {
1274				switchToForeground();
1275			}
1276			this.mOnAccountUpdate = listener;
1277			if (this.accountChangedListenerCount < 2) {
1278				this.accountChangedListenerCount++;
1279			}
1280		}
1281	}
1282
1283	public void removeOnAccountListChangedListener() {
1284		synchronized (this) {
1285			this.accountChangedListenerCount--;
1286			if (this.accountChangedListenerCount <= 0) {
1287				this.mOnAccountUpdate = null;
1288				this.accountChangedListenerCount = 0;
1289				if (checkListeners()) {
1290					switchToBackground();
1291				}
1292			}
1293		}
1294	}
1295
1296	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1297		synchronized (this) {
1298			if (checkListeners()) {
1299				switchToForeground();
1300			}
1301			this.mOnRosterUpdate = listener;
1302			if (this.rosterChangedListenerCount < 2) {
1303				this.rosterChangedListenerCount++;
1304			}
1305		}
1306	}
1307
1308	public void removeOnRosterUpdateListener() {
1309		synchronized (this) {
1310			this.rosterChangedListenerCount--;
1311			if (this.rosterChangedListenerCount <= 0) {
1312				this.rosterChangedListenerCount = 0;
1313				this.mOnRosterUpdate = null;
1314				if (checkListeners()) {
1315					switchToBackground();
1316				}
1317			}
1318		}
1319	}
1320
1321	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1322		synchronized (this) {
1323			if (checkListeners()) {
1324				switchToForeground();
1325			}
1326			this.mOnUpdateBlocklist = listener;
1327			if (this.updateBlocklistListenerCount < 2) {
1328				this.updateBlocklistListenerCount++;
1329			}
1330		}
1331	}
1332
1333	public void removeOnUpdateBlocklistListener() {
1334		synchronized (this) {
1335			this.updateBlocklistListenerCount--;
1336			if (this.updateBlocklistListenerCount <= 0) {
1337				this.updateBlocklistListenerCount = 0;
1338				this.mOnUpdateBlocklist = null;
1339				if (checkListeners()) {
1340					switchToBackground();
1341				}
1342			}
1343		}
1344	}
1345
1346	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1347		synchronized (this) {
1348			if (checkListeners()) {
1349				switchToForeground();
1350			}
1351			this.mOnMucRosterUpdate = listener;
1352			if (this.mucRosterChangedListenerCount < 2) {
1353				this.mucRosterChangedListenerCount++;
1354			}
1355		}
1356	}
1357
1358	public void removeOnMucRosterUpdateListener() {
1359		synchronized (this) {
1360			this.mucRosterChangedListenerCount--;
1361			if (this.mucRosterChangedListenerCount <= 0) {
1362				this.mucRosterChangedListenerCount = 0;
1363				this.mOnMucRosterUpdate = null;
1364				if (checkListeners()) {
1365					switchToBackground();
1366				}
1367			}
1368		}
1369	}
1370
1371	private boolean checkListeners() {
1372		return (this.mOnAccountUpdate == null
1373				&& this.mOnConversationUpdate == null
1374				&& this.mOnRosterUpdate == null
1375				&& this.mOnUpdateBlocklist == null
1376				&& this.mOnShowErrorToast == null);
1377	}
1378
1379	private void switchToForeground() {
1380		for (Account account : getAccounts()) {
1381			if (account.getStatus() == Account.State.ONLINE) {
1382				XmppConnection connection = account.getXmppConnection();
1383				if (connection != null && connection.getFeatures().csi()) {
1384					connection.sendActive();
1385				}
1386			}
1387		}
1388		Log.d(Config.LOGTAG, "app switched into foreground");
1389	}
1390
1391	private void switchToBackground() {
1392		for (Account account : getAccounts()) {
1393			if (account.getStatus() == Account.State.ONLINE) {
1394				XmppConnection connection = account.getXmppConnection();
1395				if (connection != null && connection.getFeatures().csi()) {
1396					connection.sendInactive();
1397				}
1398			}
1399		}
1400		for(Conversation conversation : getConversations()) {
1401			conversation.setIncomingChatState(ChatState.ACTIVE);
1402		}
1403		this.mNotificationService.setIsInForeground(false);
1404		Log.d(Config.LOGTAG, "app switched into background");
1405	}
1406
1407	private void connectMultiModeConversations(Account account) {
1408		List<Conversation> conversations = getConversations();
1409		for (Conversation conversation : conversations) {
1410			if ((conversation.getMode() == Conversation.MODE_MULTI)
1411					&& (conversation.getAccount() == account)) {
1412				conversation.resetMucOptions();
1413				joinMuc(conversation);
1414			}
1415		}
1416	}
1417
1418	public void joinMuc(Conversation conversation) {
1419		Account account = conversation.getAccount();
1420		account.pendingConferenceJoins.remove(conversation);
1421		account.pendingConferenceLeaves.remove(conversation);
1422		if (account.getStatus() == Account.State.ONLINE) {
1423			final String nick = conversation.getMucOptions().getProposedNick();
1424			final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1425			if (joinJid == null) {
1426				return; //safety net
1427			}
1428			Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1429			PresencePacket packet = new PresencePacket();
1430			packet.setFrom(conversation.getAccount().getJid());
1431			packet.setTo(joinJid);
1432			Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1433			if (conversation.getMucOptions().getPassword() != null) {
1434				x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1435			}
1436			x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1437			String sig = account.getPgpSignature();
1438			if (sig != null) {
1439				packet.addChild("status").setContent("online");
1440				packet.addChild("x", "jabber:x:signed").setContent(sig);
1441			}
1442			sendPresencePacket(account, packet);
1443			fetchConferenceConfiguration(conversation);
1444			if (!joinJid.equals(conversation.getJid())) {
1445				conversation.setContactJid(joinJid);
1446				databaseBackend.updateConversation(conversation);
1447			}
1448			conversation.setHasMessagesLeftOnServer(false);
1449		} else {
1450			account.pendingConferenceJoins.add(conversation);
1451		}
1452	}
1453
1454	public void providePasswordForMuc(Conversation conversation, String password) {
1455		if (conversation.getMode() == Conversation.MODE_MULTI) {
1456			conversation.getMucOptions().setPassword(password);
1457			if (conversation.getBookmark() != null) {
1458				conversation.getBookmark().setAutojoin(true);
1459				pushBookmarks(conversation.getAccount());
1460			}
1461			databaseBackend.updateConversation(conversation);
1462			joinMuc(conversation);
1463		}
1464	}
1465
1466	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1467		final MucOptions options = conversation.getMucOptions();
1468		final Jid joinJid = options.createJoinJid(nick);
1469		if (options.online()) {
1470			Account account = conversation.getAccount();
1471			options.setOnRenameListener(new OnRenameListener() {
1472
1473				@Override
1474				public void onSuccess() {
1475					conversation.setContactJid(joinJid);
1476					databaseBackend.updateConversation(conversation);
1477					Bookmark bookmark = conversation.getBookmark();
1478					if (bookmark != null) {
1479						bookmark.setNick(nick);
1480						pushBookmarks(bookmark.getAccount());
1481					}
1482					callback.success(conversation);
1483				}
1484
1485				@Override
1486				public void onFailure() {
1487					callback.error(R.string.nick_in_use, conversation);
1488				}
1489			});
1490
1491			PresencePacket packet = new PresencePacket();
1492			packet.setTo(joinJid);
1493			packet.setFrom(conversation.getAccount().getJid());
1494
1495			String sig = account.getPgpSignature();
1496			if (sig != null) {
1497				packet.addChild("status").setContent("online");
1498				packet.addChild("x", "jabber:x:signed").setContent(sig);
1499			}
1500			sendPresencePacket(account, packet);
1501		} else {
1502			conversation.setContactJid(joinJid);
1503			databaseBackend.updateConversation(conversation);
1504			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1505				Bookmark bookmark = conversation.getBookmark();
1506				if (bookmark != null) {
1507					bookmark.setNick(nick);
1508					pushBookmarks(bookmark.getAccount());
1509				}
1510				joinMuc(conversation);
1511			}
1512		}
1513	}
1514
1515	public void leaveMuc(Conversation conversation) {
1516		Account account = conversation.getAccount();
1517		account.pendingConferenceJoins.remove(conversation);
1518		account.pendingConferenceLeaves.remove(conversation);
1519		if (account.getStatus() == Account.State.ONLINE) {
1520			PresencePacket packet = new PresencePacket();
1521			packet.setTo(conversation.getJid());
1522			packet.setFrom(conversation.getAccount().getJid());
1523			packet.setAttribute("type", "unavailable");
1524			sendPresencePacket(conversation.getAccount(), packet);
1525			conversation.getMucOptions().setOffline();
1526			conversation.deregisterWithBookmark();
1527			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1528					+ ": leaving muc " + conversation.getJid());
1529		} else {
1530			account.pendingConferenceLeaves.add(conversation);
1531		}
1532	}
1533
1534	private String findConferenceServer(final Account account) {
1535		String server;
1536		if (account.getXmppConnection() != null) {
1537			server = account.getXmppConnection().getMucServer();
1538			if (server != null) {
1539				return server;
1540			}
1541		}
1542		for (Account other : getAccounts()) {
1543			if (other != account && other.getXmppConnection() != null) {
1544				server = other.getXmppConnection().getMucServer();
1545				if (server != null) {
1546					return server;
1547				}
1548			}
1549		}
1550		return null;
1551	}
1552
1553	public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1554		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1555		if (account.getStatus() == Account.State.ONLINE) {
1556			try {
1557				String server = findConferenceServer(account);
1558				if (server == null) {
1559					if (callback != null) {
1560						callback.error(R.string.no_conference_server_found, null);
1561					}
1562					return;
1563				}
1564				String name = new BigInteger(75, getRNG()).toString(32);
1565				Jid jid = Jid.fromParts(name, server, null);
1566				final Conversation conversation = findOrCreateConversation(account, jid, true);
1567				joinMuc(conversation);
1568				Bundle options = new Bundle();
1569				options.putString("muc#roomconfig_persistentroom", "1");
1570				options.putString("muc#roomconfig_membersonly", "1");
1571				options.putString("muc#roomconfig_publicroom", "0");
1572				options.putString("muc#roomconfig_whois", "anyone");
1573				pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1574					@Override
1575					public void onPushSucceeded() {
1576						for (Jid invite : jids) {
1577							invite(conversation, invite);
1578						}
1579						if (account.countPresences() > 1) {
1580							directInvite(conversation, account.getJid().toBareJid());
1581						}
1582						if (callback != null) {
1583							callback.success(conversation);
1584						}
1585					}
1586
1587					@Override
1588					public void onPushFailed() {
1589						if (callback != null) {
1590							callback.error(R.string.conference_creation_failed, conversation);
1591						}
1592					}
1593				});
1594
1595			} catch (InvalidJidException e) {
1596				if (callback != null) {
1597					callback.error(R.string.conference_creation_failed, null);
1598				}
1599			}
1600		} else {
1601			if (callback != null) {
1602				callback.error(R.string.not_connected_try_again, null);
1603			}
1604		}
1605	}
1606
1607	public void fetchConferenceConfiguration(final Conversation conversation) {
1608		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1609		request.setTo(conversation.getJid().toBareJid());
1610		request.query("http://jabber.org/protocol/disco#info");
1611		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1612			@Override
1613			public void onIqPacketReceived(Account account, IqPacket packet) {
1614				if (packet.getType() != IqPacket.TYPE.ERROR) {
1615					ArrayList<String> features = new ArrayList<>();
1616					for (Element child : packet.query().getChildren()) {
1617						if (child != null && child.getName().equals("feature")) {
1618							String var = child.getAttribute("var");
1619							if (var != null) {
1620								features.add(var);
1621							}
1622						}
1623					}
1624					conversation.getMucOptions().updateFeatures(features);
1625					updateConversationUi();
1626				}
1627			}
1628		});
1629	}
1630
1631	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1632		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1633		request.setTo(conversation.getJid().toBareJid());
1634		request.query("http://jabber.org/protocol/muc#owner");
1635		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1636			@Override
1637			public void onIqPacketReceived(Account account, IqPacket packet) {
1638				if (packet.getType() != IqPacket.TYPE.ERROR) {
1639					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1640					for (Field field : data.getFields()) {
1641						if (options.containsKey(field.getName())) {
1642							field.setValue(options.getString(field.getName()));
1643						}
1644					}
1645					data.submit();
1646					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1647					set.setTo(conversation.getJid().toBareJid());
1648					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1649					sendIqPacket(account, set, new OnIqPacketReceived() {
1650						@Override
1651						public void onIqPacketReceived(Account account, IqPacket packet) {
1652							if (packet.getType() == IqPacket.TYPE.RESULT) {
1653								if (callback != null) {
1654									callback.onPushSucceeded();
1655								}
1656							} else {
1657								if (callback != null) {
1658									callback.onPushFailed();
1659								}
1660							}
1661						}
1662					});
1663				} else {
1664					if (callback != null) {
1665						callback.onPushFailed();
1666					}
1667				}
1668			}
1669		});
1670	}
1671
1672	public void pushSubjectToConference(final Conversation conference, final String subject) {
1673		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1674		this.sendMessagePacket(conference.getAccount(), packet);
1675		final MucOptions mucOptions = conference.getMucOptions();
1676		final MucOptions.User self = mucOptions.getSelf();
1677		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1678			Bundle options = new Bundle();
1679			options.putString("muc#roomconfig_persistentroom", "1");
1680			this.pushConferenceConfiguration(conference, options, null);
1681		}
1682	}
1683
1684	public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1685		final Jid jid = user.toBareJid();
1686		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
1687		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1688			@Override
1689			public void onIqPacketReceived(Account account, IqPacket packet) {
1690				if (packet.getType() == IqPacket.TYPE.RESULT) {
1691					callback.onAffiliationChangedSuccessful(jid);
1692				} else {
1693					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
1694				}
1695			}
1696		});
1697	}
1698
1699	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
1700		List<Jid> jids = new ArrayList<>();
1701		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
1702			if (user.getAffiliation() == before) {
1703				jids.add(user.getJid());
1704			}
1705		}
1706		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
1707		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
1708	}
1709
1710	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
1711		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
1712		Log.d(Config.LOGTAG, request.toString());
1713		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1714			@Override
1715			public void onIqPacketReceived(Account account, IqPacket packet) {
1716				Log.d(Config.LOGTAG, packet.toString());
1717				if (packet.getType() == IqPacket.TYPE.RESULT) {
1718					callback.onRoleChangedSuccessful(nick);
1719				} else {
1720					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
1721				}
1722			}
1723		});
1724	}
1725
1726	public void disconnect(Account account, boolean force) {
1727		if ((account.getStatus() == Account.State.ONLINE)
1728				|| (account.getStatus() == Account.State.DISABLED)) {
1729			if (!force) {
1730				List<Conversation> conversations = getConversations();
1731				for (Conversation conversation : conversations) {
1732					if (conversation.getAccount() == account) {
1733						if (conversation.getMode() == Conversation.MODE_MULTI) {
1734							leaveMuc(conversation);
1735						} else {
1736							if (conversation.endOtrIfNeeded()) {
1737								Log.d(Config.LOGTAG, account.getJid().toBareJid()
1738										+ ": ended otr session with "
1739										+ conversation.getJid());
1740							}
1741						}
1742					}
1743				}
1744				sendOfflinePresence(account);
1745			}
1746			account.getXmppConnection().disconnect(force);
1747		}
1748	}
1749
1750	@Override
1751	public IBinder onBind(Intent intent) {
1752		return mBinder;
1753	}
1754
1755	public void updateMessage(Message message) {
1756		databaseBackend.updateMessage(message);
1757		updateConversationUi();
1758	}
1759
1760	protected void syncDirtyContacts(Account account) {
1761		for (Contact contact : account.getRoster().getContacts()) {
1762			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1763				pushContactToServer(contact);
1764			}
1765			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1766				deleteContactOnServer(contact);
1767			}
1768		}
1769	}
1770
1771	public void createContact(Contact contact) {
1772		SharedPreferences sharedPref = getPreferences();
1773		boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1774		if (autoGrant) {
1775			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1776			contact.setOption(Contact.Options.ASKING);
1777		}
1778		pushContactToServer(contact);
1779	}
1780
1781	public void onOtrSessionEstablished(Conversation conversation) {
1782		final Account account = conversation.getAccount();
1783		final Session otrSession = conversation.getOtrSession();
1784		Log.d(Config.LOGTAG,
1785				account.getJid().toBareJid() + " otr session established with "
1786						+ conversation.getJid() + "/"
1787						+ otrSession.getSessionID().getUserID());
1788		conversation.findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
1789
1790			@Override
1791			public void onMessageFound(Message message) {
1792				SessionID id = otrSession.getSessionID();
1793				try {
1794					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
1795				} catch (InvalidJidException e) {
1796					return;
1797				}
1798				if (message.needsUploading()) {
1799					mJingleConnectionManager.createNewConnection(message);
1800				} else {
1801					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message, true);
1802					if (outPacket != null) {
1803						message.setStatus(Message.STATUS_SEND);
1804						databaseBackend.updateMessage(message);
1805						sendMessagePacket(account, outPacket);
1806					}
1807				}
1808				updateConversationUi();
1809			}
1810		});
1811	}
1812
1813	public boolean renewSymmetricKey(Conversation conversation) {
1814		Account account = conversation.getAccount();
1815		byte[] symmetricKey = new byte[32];
1816		this.mRandom.nextBytes(symmetricKey);
1817		Session otrSession = conversation.getOtrSession();
1818		if (otrSession != null) {
1819			MessagePacket packet = new MessagePacket();
1820			packet.setType(MessagePacket.TYPE_CHAT);
1821			packet.setFrom(account.getJid());
1822			packet.addChild("private", "urn:xmpp:carbons:2");
1823			packet.addChild("no-copy", "urn:xmpp:hints");
1824			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
1825					+ otrSession.getSessionID().getUserID());
1826			try {
1827				packet.setBody(otrSession
1828						.transformSending(CryptoHelper.FILETRANSFER
1829								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
1830				sendMessagePacket(account, packet);
1831				conversation.setSymmetricKey(symmetricKey);
1832				return true;
1833			} catch (OtrException e) {
1834				return false;
1835			}
1836		}
1837		return false;
1838	}
1839
1840	public void pushContactToServer(final Contact contact) {
1841		contact.resetOption(Contact.Options.DIRTY_DELETE);
1842		contact.setOption(Contact.Options.DIRTY_PUSH);
1843		final Account account = contact.getAccount();
1844		if (account.getStatus() == Account.State.ONLINE) {
1845			final boolean ask = contact.getOption(Contact.Options.ASKING);
1846			final boolean sendUpdates = contact
1847					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
1848					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
1849			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1850			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
1851			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
1852			if (sendUpdates) {
1853				sendPresencePacket(account,
1854						mPresenceGenerator.sendPresenceUpdatesTo(contact));
1855			}
1856			if (ask) {
1857				sendPresencePacket(account,
1858						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
1859			}
1860		}
1861	}
1862
1863	public void publishAvatar(final Account account,
1864							  final Uri image,
1865							  final UiCallback<Avatar> callback) {
1866		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
1867		final int size = Config.AVATAR_SIZE;
1868		final Avatar avatar = getFileBackend()
1869				.getPepAvatar(image, size, format);
1870		if (avatar != null) {
1871			avatar.height = size;
1872			avatar.width = size;
1873			if (format.equals(Bitmap.CompressFormat.WEBP)) {
1874				avatar.type = "image/webp";
1875			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1876				avatar.type = "image/jpeg";
1877			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
1878				avatar.type = "image/png";
1879			}
1880			if (!getFileBackend().save(avatar)) {
1881				callback.error(R.string.error_saving_avatar, avatar);
1882				return;
1883			}
1884			final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
1885			this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1886
1887				@Override
1888				public void onIqPacketReceived(Account account, IqPacket result) {
1889					if (result.getType() == IqPacket.TYPE.RESULT) {
1890						final IqPacket packet = XmppConnectionService.this.mIqGenerator
1891								.publishAvatarMetadata(avatar);
1892						sendIqPacket(account, packet, new OnIqPacketReceived() {
1893
1894							@Override
1895							public void onIqPacketReceived(Account account,
1896														   IqPacket result) {
1897								if (result.getType() == IqPacket.TYPE.RESULT) {
1898									if (account.setAvatar(avatar.getFilename())) {
1899										getAvatarService().clear(account);
1900										databaseBackend.updateAccount(account);
1901									}
1902									callback.success(avatar);
1903								} else {
1904									callback.error(
1905											R.string.error_publish_avatar_server_reject,
1906											avatar);
1907								}
1908							}
1909						});
1910					} else {
1911						callback.error(
1912								R.string.error_publish_avatar_server_reject,
1913								avatar);
1914					}
1915				}
1916			});
1917		} else {
1918			callback.error(R.string.error_publish_avatar_converting, null);
1919		}
1920	}
1921
1922	public void fetchAvatar(Account account, Avatar avatar) {
1923		fetchAvatar(account, avatar, null);
1924	}
1925
1926	private static String generateFetchKey(Account account, final Avatar avatar) {
1927		return account.getJid().toBareJid()+"_"+avatar.owner+"_"+avatar.sha1sum;
1928	}
1929
1930	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
1931		final String KEY = generateFetchKey(account, avatar);
1932		synchronized(this.mInProgressAvatarFetches) {
1933			if (this.mInProgressAvatarFetches.contains(KEY)) {
1934				return;
1935			} else {
1936				switch (avatar.origin) {
1937					case PEP:
1938						this.mInProgressAvatarFetches.add(KEY);
1939						fetchAvatarPep(account, avatar, callback);
1940						break;
1941					case VCARD:
1942						this.mInProgressAvatarFetches.add(KEY);
1943						fetchAvatarVcard(account, avatar, callback);
1944						break;
1945				}
1946			}
1947		}
1948	}
1949
1950	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
1951		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
1952		sendIqPacket(account, packet, new OnIqPacketReceived() {
1953
1954			@Override
1955			public void onIqPacketReceived(Account account, IqPacket result) {
1956				synchronized (mInProgressAvatarFetches) {
1957					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
1958				}
1959				final String ERROR = account.getJid().toBareJid()
1960						+ ": fetching avatar for " + avatar.owner + " failed ";
1961				if (result.getType() == IqPacket.TYPE.RESULT) {
1962					avatar.image = mIqParser.avatarData(result);
1963					if (avatar.image != null) {
1964						if (getFileBackend().save(avatar)) {
1965							if (account.getJid().toBareJid().equals(avatar.owner)) {
1966								if (account.setAvatar(avatar.getFilename())) {
1967									databaseBackend.updateAccount(account);
1968								}
1969								getAvatarService().clear(account);
1970								updateConversationUi();
1971								updateAccountUi();
1972							} else {
1973								Contact contact = account.getRoster()
1974										.getContact(avatar.owner);
1975								contact.setAvatar(avatar);
1976								getAvatarService().clear(contact);
1977								updateConversationUi();
1978								updateRosterUi();
1979							}
1980							if (callback != null) {
1981								callback.success(avatar);
1982							}
1983							Log.d(Config.LOGTAG, account.getJid().toBareJid()
1984									+ ": succesfuly fetched pep avatar for " + avatar.owner);
1985							return;
1986						}
1987					} else {
1988
1989						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
1990					}
1991				} else {
1992					Element error = result.findChild("error");
1993					if (error == null) {
1994						Log.d(Config.LOGTAG, ERROR + "(server error)");
1995					} else {
1996						Log.d(Config.LOGTAG, ERROR + error.toString());
1997					}
1998				}
1999				if (callback != null) {
2000					callback.error(0, null);
2001				}
2002
2003			}
2004		});
2005	}
2006
2007	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2008		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2009		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2010			@Override
2011			public void onIqPacketReceived(Account account, IqPacket packet) {
2012				synchronized (mInProgressAvatarFetches) {
2013					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2014				}
2015				if (packet.getType() == IqPacket.TYPE.RESULT) {
2016					Element vCard = packet.findChild("vCard", "vcard-temp");
2017					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2018					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2019					if (image != null) {
2020						avatar.image = image;
2021						if (getFileBackend().save(avatar)) {
2022							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2023									+ ": successfully fetched vCard avatar for " + avatar.owner);
2024							Contact contact = account.getRoster()
2025									.getContact(avatar.owner);
2026							contact.setAvatar(avatar);
2027							getAvatarService().clear(contact);
2028							updateConversationUi();
2029							updateRosterUi();
2030						}
2031					}
2032				}
2033			}
2034		});
2035	}
2036
2037	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2038		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2039		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2040
2041			@Override
2042			public void onIqPacketReceived(Account account, IqPacket packet) {
2043				if (packet.getType() == IqPacket.TYPE.RESULT) {
2044					Element pubsub = packet.findChild("pubsub",
2045							"http://jabber.org/protocol/pubsub");
2046					if (pubsub != null) {
2047						Element items = pubsub.findChild("items");
2048						if (items != null) {
2049							Avatar avatar = Avatar.parseMetadata(items);
2050							if (avatar != null) {
2051								avatar.owner = account.getJid().toBareJid();
2052								if (fileBackend.isAvatarCached(avatar)) {
2053									if (account.setAvatar(avatar.getFilename())) {
2054										databaseBackend.updateAccount(account);
2055									}
2056									getAvatarService().clear(account);
2057									callback.success(avatar);
2058								} else {
2059									fetchAvatarPep(account, avatar, callback);
2060								}
2061								return;
2062							}
2063						}
2064					}
2065				}
2066				callback.error(0, null);
2067			}
2068		});
2069	}
2070
2071	public void deleteContactOnServer(Contact contact) {
2072		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2073		contact.resetOption(Contact.Options.DIRTY_PUSH);
2074		contact.setOption(Contact.Options.DIRTY_DELETE);
2075		Account account = contact.getAccount();
2076		if (account.getStatus() == Account.State.ONLINE) {
2077			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2078			Element item = iq.query(Xmlns.ROSTER).addChild("item");
2079			item.setAttribute("jid", contact.getJid().toString());
2080			item.setAttribute("subscription", "remove");
2081			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2082		}
2083	}
2084
2085	public void updateConversation(Conversation conversation) {
2086		this.databaseBackend.updateConversation(conversation);
2087	}
2088
2089	public void reconnectAccount(final Account account, final boolean force) {
2090		synchronized (account) {
2091			if (account.getXmppConnection() != null) {
2092				disconnect(account, force);
2093			}
2094			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2095
2096				synchronized (this.mInProgressAvatarFetches) {
2097					for(Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext();) {
2098						final String KEY = iterator.next();
2099						if (KEY.startsWith(account.getJid().toBareJid()+"_")) {
2100							iterator.remove();
2101						}
2102					}
2103				}
2104
2105				if (account.getXmppConnection() == null) {
2106					account.setXmppConnection(createConnection(account));
2107				}
2108				Thread thread = new Thread(account.getXmppConnection());
2109				thread.start();
2110				scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
2111			} else {
2112				account.getRoster().clearPresences();
2113				account.setXmppConnection(null);
2114			}
2115		}
2116	}
2117
2118	public void reconnectAccountInBackground(final Account account) {
2119		new Thread(new Runnable() {
2120			@Override
2121			public void run() {
2122				reconnectAccount(account,false);
2123			}
2124		}).start();
2125	}
2126
2127	public void invite(Conversation conversation, Jid contact) {
2128		Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": inviting "+contact+" to "+conversation.getJid().toBareJid());
2129		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2130		sendMessagePacket(conversation.getAccount(), packet);
2131	}
2132
2133	public void directInvite(Conversation conversation, Jid jid) {
2134		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2135		sendMessagePacket(conversation.getAccount(),packet);
2136	}
2137
2138	public void resetSendingToWaiting(Account account) {
2139		for (Conversation conversation : getConversations()) {
2140			if (conversation.getAccount() == account) {
2141				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2142
2143					@Override
2144					public void onMessageFound(Message message) {
2145						markMessage(message, Message.STATUS_WAITING);
2146					}
2147				});
2148			}
2149		}
2150	}
2151
2152	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2153		if (uuid == null) {
2154			return null;
2155		}
2156		for (Conversation conversation : getConversations()) {
2157			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2158				final Message message = conversation.findSentMessageWithUuid(uuid);
2159				if (message != null) {
2160					markMessage(message, status);
2161				}
2162				return message;
2163			}
2164		}
2165		return null;
2166	}
2167
2168	public boolean markMessage(Conversation conversation, String uuid,
2169							   int status) {
2170		if (uuid == null) {
2171			return false;
2172		} else {
2173			Message message = conversation.findSentMessageWithUuid(uuid);
2174			if (message != null) {
2175				markMessage(message, status);
2176				return true;
2177			} else {
2178				return false;
2179			}
2180		}
2181	}
2182
2183	public void markMessage(Message message, int status) {
2184		if (status == Message.STATUS_SEND_FAILED
2185				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2186				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2187			return;
2188		}
2189		message.setStatus(status);
2190		databaseBackend.updateMessage(message);
2191		updateConversationUi();
2192	}
2193
2194	public SharedPreferences getPreferences() {
2195		return PreferenceManager
2196				.getDefaultSharedPreferences(getApplicationContext());
2197	}
2198
2199	public boolean forceEncryption() {
2200		return getPreferences().getBoolean("force_encryption", false);
2201	}
2202
2203	public boolean confirmMessages() {
2204		return getPreferences().getBoolean("confirm_messages", true);
2205	}
2206
2207	public boolean sendChatStates() {
2208		return getPreferences().getBoolean("chat_states", false);
2209	}
2210
2211	public boolean saveEncryptedMessages() {
2212		return !getPreferences().getBoolean("dont_save_encrypted", false);
2213	}
2214
2215	public boolean indicateReceived() {
2216		return getPreferences().getBoolean("indicate_received", false);
2217	}
2218
2219	public int unreadCount() {
2220		int count = 0;
2221		for(Conversation conversation : getConversations()) {
2222			count += conversation.unreadCount();
2223		}
2224		return count;
2225	}
2226
2227
2228	public void showErrorToastInUi(int resId) {
2229		if (mOnShowErrorToast != null) {
2230			mOnShowErrorToast.onShowErrorToast(resId);
2231		}
2232	}
2233
2234	public void updateConversationUi() {
2235		if (mOnConversationUpdate != null) {
2236			mOnConversationUpdate.onConversationUpdate();
2237		}
2238	}
2239
2240	public void updateAccountUi() {
2241		if (mOnAccountUpdate != null) {
2242			mOnAccountUpdate.onAccountUpdate();
2243		}
2244	}
2245
2246	public void updateRosterUi() {
2247		if (mOnRosterUpdate != null) {
2248			mOnRosterUpdate.onRosterUpdate();
2249		}
2250	}
2251
2252	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2253		if (mOnUpdateBlocklist != null) {
2254			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2255		}
2256	}
2257
2258	public void updateMucRosterUi() {
2259		if (mOnMucRosterUpdate != null) {
2260			mOnMucRosterUpdate.onMucRosterUpdate();
2261		}
2262	}
2263
2264	public Account findAccountByJid(final Jid accountJid) {
2265		for (Account account : this.accounts) {
2266			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2267				return account;
2268			}
2269		}
2270		return null;
2271	}
2272
2273	public Conversation findConversationByUuid(String uuid) {
2274		for (Conversation conversation : getConversations()) {
2275			if (conversation.getUuid().equals(uuid)) {
2276				return conversation;
2277			}
2278		}
2279		return null;
2280	}
2281
2282	public void markRead(final Conversation conversation) {
2283		mNotificationService.clear(conversation);
2284		conversation.markRead();
2285		updateUnreadCountBadge();
2286	}
2287
2288	public synchronized void updateUnreadCountBadge() {
2289		int count = unreadCount();
2290		if (unreadCount != count) {
2291			Log.d(Config.LOGTAG, "update unread count to " + count);
2292			if (count > 0) {
2293				ShortcutBadger.with(getApplicationContext()).count(count);
2294			} else {
2295				ShortcutBadger.with(getApplicationContext()).remove();
2296			}
2297			unreadCount = count;
2298		}
2299	}
2300
2301	public void sendReadMarker(final Conversation conversation) {
2302		final Message markable = conversation.getLatestMarkableMessage();
2303		this.markRead(conversation);
2304		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2305			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2306			Account account = conversation.getAccount();
2307			final Jid to = markable.getCounterpart();
2308			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2309			this.sendMessagePacket(conversation.getAccount(), packet);
2310		}
2311		updateConversationUi();
2312	}
2313
2314	public SecureRandom getRNG() {
2315		return this.mRandom;
2316	}
2317
2318	public MemorizingTrustManager getMemorizingTrustManager() {
2319		return this.mMemorizingTrustManager;
2320	}
2321
2322	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2323		this.mMemorizingTrustManager = trustManager;
2324	}
2325
2326	public void updateMemorizingTrustmanager() {
2327		final MemorizingTrustManager tm;
2328		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2329		if (dontTrustSystemCAs) {
2330			 tm = new MemorizingTrustManager(getApplicationContext(), null);
2331		} else {
2332			tm = new MemorizingTrustManager(getApplicationContext());
2333		}
2334		setMemorizingTrustManager(tm);
2335	}
2336
2337	public PowerManager getPowerManager() {
2338		return this.pm;
2339	}
2340
2341	public LruCache<String, Bitmap> getBitmapCache() {
2342		return this.mBitmapCache;
2343	}
2344
2345	public void syncRosterToDisk(final Account account) {
2346		Runnable runnable = new Runnable() {
2347
2348			@Override
2349			public void run() {
2350				databaseBackend.writeRoster(account.getRoster());
2351			}
2352		};
2353		mDatabaseExecutor.execute(runnable);
2354
2355	}
2356
2357	public List<String> getKnownHosts() {
2358		final List<String> hosts = new ArrayList<>();
2359		for (final Account account : getAccounts()) {
2360			if (!hosts.contains(account.getServer().toString())) {
2361				hosts.add(account.getServer().toString());
2362			}
2363			for (final Contact contact : account.getRoster().getContacts()) {
2364				if (contact.showInRoster()) {
2365					final String server = contact.getServer().toString();
2366					if (server != null && !hosts.contains(server)) {
2367						hosts.add(server);
2368					}
2369				}
2370			}
2371		}
2372		return hosts;
2373	}
2374
2375	public List<String> getKnownConferenceHosts() {
2376		final ArrayList<String> mucServers = new ArrayList<>();
2377		for (final Account account : accounts) {
2378			if (account.getXmppConnection() != null) {
2379				final String server = account.getXmppConnection().getMucServer();
2380				if (server != null && !mucServers.contains(server)) {
2381					mucServers.add(server);
2382				}
2383			}
2384		}
2385		return mucServers;
2386	}
2387
2388	public void sendMessagePacket(Account account, MessagePacket packet) {
2389		XmppConnection connection = account.getXmppConnection();
2390		if (connection != null) {
2391			connection.sendMessagePacket(packet);
2392		}
2393	}
2394
2395	public void sendPresencePacket(Account account, PresencePacket packet) {
2396		XmppConnection connection = account.getXmppConnection();
2397		if (connection != null) {
2398			connection.sendPresencePacket(packet);
2399		}
2400	}
2401
2402	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2403		final XmppConnection connection = account.getXmppConnection();
2404		if (connection != null) {
2405			connection.sendIqPacket(packet, callback);
2406		}
2407	}
2408
2409	public void sendPresence(final Account account) {
2410		sendPresencePacket(account, mPresenceGenerator.sendPresence(account));
2411	}
2412
2413	public void sendOfflinePresence(final Account account) {
2414		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2415	}
2416
2417	public MessageGenerator getMessageGenerator() {
2418		return this.mMessageGenerator;
2419	}
2420
2421	public PresenceGenerator getPresenceGenerator() {
2422		return this.mPresenceGenerator;
2423	}
2424
2425	public IqGenerator getIqGenerator() {
2426		return this.mIqGenerator;
2427	}
2428
2429	public IqParser getIqParser() {
2430		return this.mIqParser;
2431	}
2432
2433	public JingleConnectionManager getJingleConnectionManager() {
2434		return this.mJingleConnectionManager;
2435	}
2436
2437	public MessageArchiveService getMessageArchiveService() {
2438		return this.mMessageArchiveService;
2439	}
2440
2441	public List<Contact> findContacts(Jid jid) {
2442		ArrayList<Contact> contacts = new ArrayList<>();
2443		for (Account account : getAccounts()) {
2444			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2445				Contact contact = account.getRoster().getContactFromRoster(jid);
2446				if (contact != null) {
2447					contacts.add(contact);
2448				}
2449			}
2450		}
2451		return contacts;
2452	}
2453
2454	public NotificationService getNotificationService() {
2455		return this.mNotificationService;
2456	}
2457
2458	public HttpConnectionManager getHttpConnectionManager() {
2459		return this.mHttpConnectionManager;
2460	}
2461
2462	public void resendFailedMessages(final Message message) {
2463		final Collection<Message> messages = new ArrayList<>();
2464		Message current = message;
2465		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2466			messages.add(current);
2467			if (current.mergeable(current.next())) {
2468				current = current.next();
2469			} else {
2470				break;
2471			}
2472		}
2473		for (final Message msg : messages) {
2474			markMessage(msg, Message.STATUS_WAITING);
2475			this.resendMessage(msg);
2476		}
2477	}
2478
2479	public void clearConversationHistory(final Conversation conversation) {
2480		conversation.clearMessages();
2481		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2482		new Thread(new Runnable() {
2483			@Override
2484			public void run() {
2485				databaseBackend.deleteMessagesInConversation(conversation);
2486			}
2487		}).start();
2488	}
2489
2490	public void sendBlockRequest(final Blockable blockable) {
2491		if (blockable != null && blockable.getBlockedJid() != null) {
2492			final Jid jid = blockable.getBlockedJid();
2493			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2494
2495				@Override
2496				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2497					if (packet.getType() == IqPacket.TYPE.RESULT) {
2498						account.getBlocklist().add(jid);
2499						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2500					}
2501				}
2502			});
2503		}
2504	}
2505
2506	public void sendUnblockRequest(final Blockable blockable) {
2507		if (blockable != null && blockable.getJid() != null) {
2508			final Jid jid = blockable.getBlockedJid();
2509			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2510				@Override
2511				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2512					if (packet.getType() == IqPacket.TYPE.RESULT) {
2513						account.getBlocklist().remove(jid);
2514						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2515					}
2516				}
2517			});
2518		}
2519	}
2520
2521	public interface OnMoreMessagesLoaded {
2522		public void onMoreMessagesLoaded(int count, Conversation conversation);
2523
2524		public void informUser(int r);
2525	}
2526
2527	public interface OnAccountPasswordChanged {
2528		public void onPasswordChangeSucceeded();
2529
2530		public void onPasswordChangeFailed();
2531	}
2532
2533	public interface OnAffiliationChanged {
2534		public void onAffiliationChangedSuccessful(Jid jid);
2535
2536		public void onAffiliationChangeFailed(Jid jid, int resId);
2537	}
2538
2539	public interface OnRoleChanged {
2540		public void onRoleChangedSuccessful(String nick);
2541
2542		public void onRoleChangeFailed(String nick, int resid);
2543	}
2544
2545	public interface OnConversationUpdate {
2546		public void onConversationUpdate();
2547	}
2548
2549	public interface OnAccountUpdate {
2550		public void onAccountUpdate();
2551	}
2552
2553	public interface OnRosterUpdate {
2554		public void onRosterUpdate();
2555	}
2556
2557	public interface OnMucRosterUpdate {
2558		public void onMucRosterUpdate();
2559	}
2560
2561	public interface OnConferenceOptionsPushed {
2562		public void onPushSucceeded();
2563
2564		public void onPushFailed();
2565	}
2566
2567	public interface OnShowErrorToast {
2568		void onShowErrorToast(int resId);
2569	}
2570
2571	public class XmppConnectionBinder extends Binder {
2572		public XmppConnectionService getService() {
2573			return XmppConnectionService.this;
2574		}
2575	}
2576}