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