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