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