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