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				} else {
1001					conversation.setMode(Conversation.MODE_SINGLE);
1002				}
1003				conversation.setNextEncryption(-1);
1004				conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1005				this.databaseBackend.updateConversation(conversation);
1006			} else {
1007				String conversationName;
1008				Contact contact = account.getRoster().getContact(jid);
1009				if (contact != null) {
1010					conversationName = contact.getDisplayName();
1011				} else {
1012					conversationName = jid.getLocalpart();
1013				}
1014				if (muc) {
1015					conversation = new Conversation(conversationName, account, jid,
1016							Conversation.MODE_MULTI);
1017				} else {
1018					conversation = new Conversation(conversationName, account, jid,
1019							Conversation.MODE_SINGLE);
1020				}
1021				this.databaseBackend.createConversation(conversation);
1022			}
1023			if (account.getXmppConnection() != null && account.getXmppConnection().getFeatures().mam()) {
1024				if (query == null) {
1025					this.mMessageArchiveService.query(conversation);
1026				} else {
1027					if (query.getConversation() == null) {
1028						this.mMessageArchiveService.query(conversation, query.getStart());
1029					}
1030				}
1031			}
1032			checkDeletedFiles(conversation);
1033			this.conversations.add(conversation);
1034			updateConversationUi();
1035			return conversation;
1036		}
1037	}
1038
1039	public void archiveConversation(Conversation conversation) {
1040		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1041		conversation.setNextEncryption(-1);
1042		synchronized (this.conversations) {
1043			if (conversation.getMode() == Conversation.MODE_MULTI) {
1044				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1045					Bookmark bookmark = conversation.getBookmark();
1046					if (bookmark != null && bookmark.autojoin()) {
1047						bookmark.setAutojoin(false);
1048						pushBookmarks(bookmark.getAccount());
1049					}
1050				}
1051				leaveMuc(conversation);
1052			} else {
1053				conversation.endOtrIfNeeded();
1054			}
1055			this.databaseBackend.updateConversation(conversation);
1056			this.conversations.remove(conversation);
1057			updateConversationUi();
1058		}
1059	}
1060
1061	public void createAccount(final Account account) {
1062		account.initOtrEngine(this);
1063		databaseBackend.createAccount(account);
1064		this.accounts.add(account);
1065		this.reconnectAccount(account, false);
1066		updateAccountUi();
1067	}
1068
1069	public void updateAccount(final Account account) {
1070		this.statusListener.onStatusChanged(account);
1071		databaseBackend.updateAccount(account);
1072		reconnectAccount(account, false);
1073		updateAccountUi();
1074		getNotificationService().updateErrorNotification();
1075	}
1076
1077	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1078		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1079		sendIqPacket(account, iq, new OnIqPacketReceived() {
1080			@Override
1081			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1082				if (packet.getType() == IqPacket.TYPE.RESULT) {
1083					account.setPassword(newPassword);
1084					databaseBackend.updateAccount(account);
1085					callback.onPasswordChangeSucceeded();
1086				} else {
1087					callback.onPasswordChangeFailed();
1088				}
1089			}
1090		});
1091	}
1092
1093	public void deleteAccount(final Account account) {
1094		synchronized (this.conversations) {
1095			for (final Conversation conversation : conversations) {
1096				if (conversation.getAccount() == account) {
1097					if (conversation.getMode() == Conversation.MODE_MULTI) {
1098						leaveMuc(conversation);
1099					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1100						conversation.endOtrIfNeeded();
1101					}
1102					conversations.remove(conversation);
1103				}
1104			}
1105			if (account.getXmppConnection() != null) {
1106				this.disconnect(account, true);
1107			}
1108			databaseBackend.deleteAccount(account);
1109			this.accounts.remove(account);
1110			updateAccountUi();
1111			getNotificationService().updateErrorNotification();
1112		}
1113	}
1114
1115	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1116		synchronized (this) {
1117			if (checkListeners()) {
1118				switchToForeground();
1119			}
1120			this.mOnConversationUpdate = listener;
1121			this.mNotificationService.setIsInForeground(true);
1122			if (this.convChangedListenerCount < 2) {
1123				this.convChangedListenerCount++;
1124			}
1125		}
1126	}
1127
1128	public void removeOnConversationListChangedListener() {
1129		synchronized (this) {
1130			this.convChangedListenerCount--;
1131			if (this.convChangedListenerCount <= 0) {
1132				this.convChangedListenerCount = 0;
1133				this.mOnConversationUpdate = null;
1134				this.mNotificationService.setIsInForeground(false);
1135				if (checkListeners()) {
1136					switchToBackground();
1137				}
1138			}
1139		}
1140	}
1141
1142	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1143		synchronized (this) {
1144			if (checkListeners()) {
1145				switchToForeground();
1146			}
1147			this.mOnAccountUpdate = listener;
1148			if (this.accountChangedListenerCount < 2) {
1149				this.accountChangedListenerCount++;
1150			}
1151		}
1152	}
1153
1154	public void removeOnAccountListChangedListener() {
1155		synchronized (this) {
1156			this.accountChangedListenerCount--;
1157			if (this.accountChangedListenerCount <= 0) {
1158				this.mOnAccountUpdate = null;
1159				this.accountChangedListenerCount = 0;
1160				if (checkListeners()) {
1161					switchToBackground();
1162				}
1163			}
1164		}
1165	}
1166
1167	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1168		synchronized (this) {
1169			if (checkListeners()) {
1170				switchToForeground();
1171			}
1172			this.mOnRosterUpdate = listener;
1173			if (this.rosterChangedListenerCount < 2) {
1174				this.rosterChangedListenerCount++;
1175			}
1176		}
1177	}
1178
1179	public void removeOnRosterUpdateListener() {
1180		synchronized (this) {
1181			this.rosterChangedListenerCount--;
1182			if (this.rosterChangedListenerCount <= 0) {
1183				this.rosterChangedListenerCount = 0;
1184				this.mOnRosterUpdate = null;
1185				if (checkListeners()) {
1186					switchToBackground();
1187				}
1188			}
1189		}
1190	}
1191
1192	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1193		synchronized (this) {
1194			if (checkListeners()) {
1195				switchToForeground();
1196			}
1197			this.mOnUpdateBlocklist = listener;
1198			if (this.updateBlocklistListenerCount < 2) {
1199				this.updateBlocklistListenerCount++;
1200			}
1201		}
1202	}
1203
1204	public void removeOnUpdateBlocklistListener() {
1205		synchronized (this) {
1206			this.updateBlocklistListenerCount--;
1207			if (this.updateBlocklistListenerCount <= 0) {
1208				this.updateBlocklistListenerCount = 0;
1209				this.mOnUpdateBlocklist = null;
1210				if (checkListeners()) {
1211					switchToBackground();
1212				}
1213			}
1214		}
1215	}
1216
1217	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1218		synchronized (this) {
1219			if (checkListeners()) {
1220				switchToForeground();
1221			}
1222			this.mOnMucRosterUpdate = listener;
1223			if (this.mucRosterChangedListenerCount < 2) {
1224				this.mucRosterChangedListenerCount++;
1225			}
1226		}
1227	}
1228
1229	public void removeOnMucRosterUpdateListener() {
1230		synchronized (this) {
1231			this.mucRosterChangedListenerCount--;
1232			if (this.mucRosterChangedListenerCount <= 0) {
1233				this.mucRosterChangedListenerCount = 0;
1234				this.mOnMucRosterUpdate = null;
1235				if (checkListeners()) {
1236					switchToBackground();
1237				}
1238			}
1239		}
1240	}
1241
1242	private boolean checkListeners() {
1243		return (this.mOnAccountUpdate == null
1244				&& this.mOnConversationUpdate == null
1245				&& this.mOnRosterUpdate == null
1246				&& this.mOnUpdateBlocklist == null);
1247	}
1248
1249	private void switchToForeground() {
1250		for (Account account : getAccounts()) {
1251			if (account.getStatus() == Account.State.ONLINE) {
1252				XmppConnection connection = account.getXmppConnection();
1253				if (connection != null && connection.getFeatures().csi()) {
1254					connection.sendActive();
1255				}
1256			}
1257		}
1258		Log.d(Config.LOGTAG, "app switched into foreground");
1259	}
1260
1261	private void switchToBackground() {
1262		for (Account account : getAccounts()) {
1263			if (account.getStatus() == Account.State.ONLINE) {
1264				XmppConnection connection = account.getXmppConnection();
1265				if (connection != null && connection.getFeatures().csi()) {
1266					connection.sendInactive();
1267				}
1268			}
1269		}
1270		this.mNotificationService.setIsInForeground(false);
1271		Log.d(Config.LOGTAG, "app switched into background");
1272	}
1273
1274	private void connectMultiModeConversations(Account account) {
1275		List<Conversation> conversations = getConversations();
1276		for (Conversation conversation : conversations) {
1277			if ((conversation.getMode() == Conversation.MODE_MULTI)
1278					&& (conversation.getAccount() == account)) {
1279				conversation.resetMucOptions();
1280				joinMuc(conversation);
1281			}
1282		}
1283	}
1284
1285	public void joinMuc(Conversation conversation) {
1286		Account account = conversation.getAccount();
1287		account.pendingConferenceJoins.remove(conversation);
1288		account.pendingConferenceLeaves.remove(conversation);
1289		if (account.getStatus() == Account.State.ONLINE) {
1290			final String nick = conversation.getMucOptions().getProposedNick();
1291			final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1292			if (joinJid == null) {
1293				return; //safety net
1294			}
1295			Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1296			PresencePacket packet = new PresencePacket();
1297			packet.setFrom(conversation.getAccount().getJid());
1298			packet.setTo(joinJid);
1299			Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1300			if (conversation.getMucOptions().getPassword() != null) {
1301				x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1302			}
1303			x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1304			String sig = account.getPgpSignature();
1305			if (sig != null) {
1306				packet.addChild("status").setContent("online");
1307				packet.addChild("x", "jabber:x:signed").setContent(sig);
1308			}
1309			sendPresencePacket(account, packet);
1310			fetchConferenceConfiguration(conversation);
1311			if (!joinJid.equals(conversation.getJid())) {
1312				conversation.setContactJid(joinJid);
1313				databaseBackend.updateConversation(conversation);
1314			}
1315		} else {
1316			account.pendingConferenceJoins.add(conversation);
1317		}
1318	}
1319
1320	public void providePasswordForMuc(Conversation conversation, String password) {
1321		if (conversation.getMode() == Conversation.MODE_MULTI) {
1322			conversation.getMucOptions().setPassword(password);
1323			if (conversation.getBookmark() != null) {
1324				conversation.getBookmark().setAutojoin(true);
1325				pushBookmarks(conversation.getAccount());
1326			}
1327			databaseBackend.updateConversation(conversation);
1328			joinMuc(conversation);
1329		}
1330	}
1331
1332	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1333		final MucOptions options = conversation.getMucOptions();
1334		final Jid joinJid = options.createJoinJid(nick);
1335		if (options.online()) {
1336			Account account = conversation.getAccount();
1337			options.setOnRenameListener(new OnRenameListener() {
1338
1339				@Override
1340				public void onSuccess() {
1341					conversation.setContactJid(joinJid);
1342					databaseBackend.updateConversation(conversation);
1343					Bookmark bookmark = conversation.getBookmark();
1344					if (bookmark != null) {
1345						bookmark.setNick(nick);
1346						pushBookmarks(bookmark.getAccount());
1347					}
1348					callback.success(conversation);
1349				}
1350
1351				@Override
1352				public void onFailure() {
1353					callback.error(R.string.nick_in_use, conversation);
1354				}
1355			});
1356
1357			PresencePacket packet = new PresencePacket();
1358			packet.setTo(joinJid);
1359			packet.setFrom(conversation.getAccount().getJid());
1360
1361			String sig = account.getPgpSignature();
1362			if (sig != null) {
1363				packet.addChild("status").setContent("online");
1364				packet.addChild("x", "jabber:x:signed").setContent(sig);
1365			}
1366			sendPresencePacket(account, packet);
1367		} else {
1368			conversation.setContactJid(joinJid);
1369			databaseBackend.updateConversation(conversation);
1370			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1371				Bookmark bookmark = conversation.getBookmark();
1372				if (bookmark != null) {
1373					bookmark.setNick(nick);
1374					pushBookmarks(bookmark.getAccount());
1375				}
1376				joinMuc(conversation);
1377			}
1378		}
1379	}
1380
1381	public void leaveMuc(Conversation conversation) {
1382		Account account = conversation.getAccount();
1383		account.pendingConferenceJoins.remove(conversation);
1384		account.pendingConferenceLeaves.remove(conversation);
1385		if (account.getStatus() == Account.State.ONLINE) {
1386			PresencePacket packet = new PresencePacket();
1387			packet.setTo(conversation.getJid());
1388			packet.setFrom(conversation.getAccount().getJid());
1389			packet.setAttribute("type", "unavailable");
1390			sendPresencePacket(conversation.getAccount(), packet);
1391			conversation.getMucOptions().setOffline();
1392			conversation.deregisterWithBookmark();
1393			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1394					+ ": leaving muc " + conversation.getJid());
1395		} else {
1396			account.pendingConferenceLeaves.add(conversation);
1397		}
1398	}
1399
1400	private String findConferenceServer(final Account account) {
1401		String server;
1402		if (account.getXmppConnection() != null) {
1403			server = account.getXmppConnection().getMucServer();
1404			if (server != null) {
1405				return server;
1406			}
1407		}
1408		for (Account other : getAccounts()) {
1409			if (other != account && other.getXmppConnection() != null) {
1410				server = other.getXmppConnection().getMucServer();
1411				if (server != null) {
1412					return server;
1413				}
1414			}
1415		}
1416		return null;
1417	}
1418
1419	public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1420		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1421		if (account.getStatus() == Account.State.ONLINE) {
1422			try {
1423				String server = findConferenceServer(account);
1424				if (server == null) {
1425					if (callback != null) {
1426						callback.error(R.string.no_conference_server_found, null);
1427					}
1428					return;
1429				}
1430				String name = new BigInteger(75, getRNG()).toString(32);
1431				Jid jid = Jid.fromParts(name, server, null);
1432				final Conversation conversation = findOrCreateConversation(account, jid, true);
1433				joinMuc(conversation);
1434				Bundle options = new Bundle();
1435				options.putString("muc#roomconfig_persistentroom", "1");
1436				options.putString("muc#roomconfig_membersonly", "1");
1437				options.putString("muc#roomconfig_publicroom", "0");
1438				options.putString("muc#roomconfig_whois", "anyone");
1439				pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1440					@Override
1441					public void onPushSucceeded() {
1442						for (Jid invite : jids) {
1443							invite(conversation, invite);
1444						}
1445						if (callback != null) {
1446							callback.success(conversation);
1447						}
1448					}
1449
1450					@Override
1451					public void onPushFailed() {
1452						if (callback != null) {
1453							callback.error(R.string.conference_creation_failed, conversation);
1454						}
1455					}
1456				});
1457
1458			} catch (InvalidJidException e) {
1459				if (callback != null) {
1460					callback.error(R.string.conference_creation_failed, null);
1461				}
1462			}
1463		} else {
1464			if (callback != null) {
1465				callback.error(R.string.not_connected_try_again, null);
1466			}
1467		}
1468	}
1469
1470	public void fetchConferenceConfiguration(final Conversation conversation) {
1471		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1472		request.setTo(conversation.getJid().toBareJid());
1473		request.query("http://jabber.org/protocol/disco#info");
1474		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1475			@Override
1476			public void onIqPacketReceived(Account account, IqPacket packet) {
1477				if (packet.getType() != IqPacket.TYPE.ERROR) {
1478					ArrayList<String> features = new ArrayList<>();
1479					for (Element child : packet.query().getChildren()) {
1480						if (child != null && child.getName().equals("feature")) {
1481							String var = child.getAttribute("var");
1482							if (var != null) {
1483								features.add(var);
1484							}
1485						}
1486					}
1487					conversation.getMucOptions().updateFeatures(features);
1488					updateConversationUi();
1489				}
1490			}
1491		});
1492	}
1493
1494	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1495		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1496		request.setTo(conversation.getJid().toBareJid());
1497		request.query("http://jabber.org/protocol/muc#owner");
1498		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1499			@Override
1500			public void onIqPacketReceived(Account account, IqPacket packet) {
1501				if (packet.getType() != IqPacket.TYPE.ERROR) {
1502					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1503					for (Field field : data.getFields()) {
1504						if (options.containsKey(field.getName())) {
1505							field.setValue(options.getString(field.getName()));
1506						}
1507					}
1508					data.submit();
1509					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1510					set.setTo(conversation.getJid().toBareJid());
1511					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1512					sendIqPacket(account, set, new OnIqPacketReceived() {
1513						@Override
1514						public void onIqPacketReceived(Account account, IqPacket packet) {
1515							if (packet.getType() == IqPacket.TYPE.RESULT) {
1516								if (callback != null) {
1517									callback.onPushSucceeded();
1518								}
1519							} else {
1520								if (callback != null) {
1521									callback.onPushFailed();
1522								}
1523							}
1524						}
1525					});
1526				} else {
1527					if (callback != null) {
1528						callback.onPushFailed();
1529					}
1530				}
1531			}
1532		});
1533	}
1534
1535	public void pushSubjectToConference(final Conversation conference, final String subject) {
1536		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1537		this.sendMessagePacket(conference.getAccount(), packet);
1538		final MucOptions mucOptions = conference.getMucOptions();
1539		final MucOptions.User self = mucOptions.getSelf();
1540		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1541			Bundle options = new Bundle();
1542			options.putString("muc#roomconfig_persistentroom", "1");
1543			this.pushConferenceConfiguration(conference, options, null);
1544		}
1545	}
1546
1547	public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1548		final Jid jid = user.toBareJid();
1549		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
1550		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1551			@Override
1552			public void onIqPacketReceived(Account account, IqPacket packet) {
1553				if (packet.getType() == IqPacket.TYPE.RESULT) {
1554					callback.onAffiliationChangedSuccessful(jid);
1555				} else {
1556					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
1557				}
1558			}
1559		});
1560	}
1561
1562	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
1563		List<Jid> jids = new ArrayList<>();
1564		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
1565			if (user.getAffiliation() == before) {
1566				jids.add(user.getJid());
1567			}
1568		}
1569		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
1570		sendIqPacket(conference.getAccount(), request, null);
1571	}
1572
1573	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
1574		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
1575		Log.d(Config.LOGTAG, request.toString());
1576		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1577			@Override
1578			public void onIqPacketReceived(Account account, IqPacket packet) {
1579				Log.d(Config.LOGTAG, packet.toString());
1580				if (packet.getType() == IqPacket.TYPE.RESULT) {
1581					callback.onRoleChangedSuccessful(nick);
1582				} else {
1583					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
1584				}
1585			}
1586		});
1587	}
1588
1589	public void disconnect(Account account, boolean force) {
1590		if ((account.getStatus() == Account.State.ONLINE)
1591				|| (account.getStatus() == Account.State.DISABLED)) {
1592			if (!force) {
1593				List<Conversation> conversations = getConversations();
1594				for (Conversation conversation : conversations) {
1595					if (conversation.getAccount() == account) {
1596						if (conversation.getMode() == Conversation.MODE_MULTI) {
1597							leaveMuc(conversation);
1598						} else {
1599							if (conversation.endOtrIfNeeded()) {
1600								Log.d(Config.LOGTAG, account.getJid().toBareJid()
1601										+ ": ended otr session with "
1602										+ conversation.getJid());
1603							}
1604						}
1605					}
1606				}
1607			}
1608			account.getXmppConnection().disconnect(force);
1609		}
1610	}
1611
1612	@Override
1613	public IBinder onBind(Intent intent) {
1614		return mBinder;
1615	}
1616
1617	public void updateMessage(Message message) {
1618		databaseBackend.updateMessage(message);
1619		updateConversationUi();
1620	}
1621
1622	protected void syncDirtyContacts(Account account) {
1623		for (Contact contact : account.getRoster().getContacts()) {
1624			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1625				pushContactToServer(contact);
1626			}
1627			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1628				deleteContactOnServer(contact);
1629			}
1630		}
1631	}
1632
1633	public void createContact(Contact contact) {
1634		SharedPreferences sharedPref = getPreferences();
1635		boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1636		if (autoGrant) {
1637			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1638			contact.setOption(Contact.Options.ASKING);
1639		}
1640		pushContactToServer(contact);
1641	}
1642
1643	public void onOtrSessionEstablished(Conversation conversation) {
1644		final Account account = conversation.getAccount();
1645		final Session otrSession = conversation.getOtrSession();
1646		Log.d(Config.LOGTAG,
1647				account.getJid().toBareJid() + " otr session established with "
1648						+ conversation.getJid() + "/"
1649						+ otrSession.getSessionID().getUserID());
1650		conversation.findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
1651
1652			@Override
1653			public void onMessageFound(Message message) {
1654				SessionID id = otrSession.getSessionID();
1655				try {
1656					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
1657				} catch (InvalidJidException e) {
1658					return;
1659				}
1660				if (message.getType() == Message.TYPE_TEXT) {
1661					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message, true);
1662					if (outPacket != null) {
1663						message.setStatus(Message.STATUS_SEND);
1664						databaseBackend.updateMessage(message);
1665						sendMessagePacket(account, outPacket);
1666					}
1667				} else if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
1668					mJingleConnectionManager.createNewConnection(message);
1669				}
1670				updateConversationUi();
1671			}
1672		});
1673	}
1674
1675	public boolean renewSymmetricKey(Conversation conversation) {
1676		Account account = conversation.getAccount();
1677		byte[] symmetricKey = new byte[32];
1678		this.mRandom.nextBytes(symmetricKey);
1679		Session otrSession = conversation.getOtrSession();
1680		if (otrSession != null) {
1681			MessagePacket packet = new MessagePacket();
1682			packet.setType(MessagePacket.TYPE_CHAT);
1683			packet.setFrom(account.getJid());
1684			packet.addChild("private", "urn:xmpp:carbons:2");
1685			packet.addChild("no-copy", "urn:xmpp:hints");
1686			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
1687					+ otrSession.getSessionID().getUserID());
1688			try {
1689				packet.setBody(otrSession
1690						.transformSending(CryptoHelper.FILETRANSFER
1691								+ CryptoHelper.bytesToHex(symmetricKey)));
1692				sendMessagePacket(account, packet);
1693				conversation.setSymmetricKey(symmetricKey);
1694				return true;
1695			} catch (OtrException e) {
1696				return false;
1697			}
1698		}
1699		return false;
1700	}
1701
1702	public void pushContactToServer(final Contact contact) {
1703		contact.resetOption(Contact.Options.DIRTY_DELETE);
1704		contact.setOption(Contact.Options.DIRTY_PUSH);
1705		final Account account = contact.getAccount();
1706		if (account.getStatus() == Account.State.ONLINE) {
1707			final boolean ask = contact.getOption(Contact.Options.ASKING);
1708			final boolean sendUpdates = contact
1709					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
1710					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
1711			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1712			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
1713			account.getXmppConnection().sendIqPacket(iq, null);
1714			if (sendUpdates) {
1715				sendPresencePacket(account,
1716						mPresenceGenerator.sendPresenceUpdatesTo(contact));
1717			}
1718			if (ask) {
1719				sendPresencePacket(account,
1720						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
1721			}
1722		}
1723	}
1724
1725	public void publishAvatar(final Account account,
1726							  final Uri image,
1727							  final UiCallback<Avatar> callback) {
1728		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
1729		final int size = Config.AVATAR_SIZE;
1730		final Avatar avatar = getFileBackend()
1731				.getPepAvatar(image, size, format);
1732		if (avatar != null) {
1733			avatar.height = size;
1734			avatar.width = size;
1735			if (format.equals(Bitmap.CompressFormat.WEBP)) {
1736				avatar.type = "image/webp";
1737			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1738				avatar.type = "image/jpeg";
1739			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
1740				avatar.type = "image/png";
1741			}
1742			if (!getFileBackend().save(avatar)) {
1743				callback.error(R.string.error_saving_avatar, avatar);
1744				return;
1745			}
1746			final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
1747			this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1748
1749				@Override
1750				public void onIqPacketReceived(Account account, IqPacket result) {
1751					if (result.getType() == IqPacket.TYPE.RESULT) {
1752						final IqPacket packet = XmppConnectionService.this.mIqGenerator
1753								.publishAvatarMetadata(avatar);
1754						sendIqPacket(account, packet, new OnIqPacketReceived() {
1755
1756							@Override
1757							public void onIqPacketReceived(Account account,
1758														   IqPacket result) {
1759								if (result.getType() == IqPacket.TYPE.RESULT) {
1760									if (account.setAvatar(avatar.getFilename())) {
1761										databaseBackend.updateAccount(account);
1762									}
1763									callback.success(avatar);
1764								} else {
1765									callback.error(
1766											R.string.error_publish_avatar_server_reject,
1767											avatar);
1768								}
1769							}
1770						});
1771					} else {
1772						callback.error(
1773								R.string.error_publish_avatar_server_reject,
1774								avatar);
1775					}
1776				}
1777			});
1778		} else {
1779			callback.error(R.string.error_publish_avatar_converting, null);
1780		}
1781	}
1782
1783	public void fetchAvatar(Account account, Avatar avatar) {
1784		fetchAvatar(account, avatar, null);
1785	}
1786
1787	public void fetchAvatar(Account account, final Avatar avatar,
1788							final UiCallback<Avatar> callback) {
1789		IqPacket packet = this.mIqGenerator.retrieveAvatar(avatar);
1790		sendIqPacket(account, packet, new OnIqPacketReceived() {
1791
1792			@Override
1793			public void onIqPacketReceived(Account account, IqPacket result) {
1794				final String ERROR = account.getJid().toBareJid()
1795						+ ": fetching avatar for " + avatar.owner + " failed ";
1796				if (result.getType() == IqPacket.TYPE.RESULT) {
1797					avatar.image = mIqParser.avatarData(result);
1798					if (avatar.image != null) {
1799						if (getFileBackend().save(avatar)) {
1800							if (account.getJid().toBareJid().equals(avatar.owner)) {
1801								if (account.setAvatar(avatar.getFilename())) {
1802									databaseBackend.updateAccount(account);
1803								}
1804								getAvatarService().clear(account);
1805								updateConversationUi();
1806								updateAccountUi();
1807							} else {
1808								Contact contact = account.getRoster()
1809										.getContact(avatar.owner);
1810								contact.setAvatar(avatar.getFilename());
1811								getAvatarService().clear(contact);
1812								updateConversationUi();
1813								updateRosterUi();
1814							}
1815							if (callback != null) {
1816								callback.success(avatar);
1817							}
1818							Log.d(Config.LOGTAG, account.getJid().toBareJid()
1819									+ ": succesfully fetched avatar for "
1820									+ avatar.owner);
1821							return;
1822						}
1823					} else {
1824
1825						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
1826					}
1827				} else {
1828					Element error = result.findChild("error");
1829					if (error == null) {
1830						Log.d(Config.LOGTAG, ERROR + "(server error)");
1831					} else {
1832						Log.d(Config.LOGTAG, ERROR + error.toString());
1833					}
1834				}
1835				if (callback != null) {
1836					callback.error(0, null);
1837				}
1838
1839			}
1840		});
1841	}
1842
1843	public void checkForAvatar(Account account,
1844							   final UiCallback<Avatar> callback) {
1845		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
1846		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1847
1848			@Override
1849			public void onIqPacketReceived(Account account, IqPacket packet) {
1850				if (packet.getType() == IqPacket.TYPE.RESULT) {
1851					Element pubsub = packet.findChild("pubsub",
1852							"http://jabber.org/protocol/pubsub");
1853					if (pubsub != null) {
1854						Element items = pubsub.findChild("items");
1855						if (items != null) {
1856							Avatar avatar = Avatar.parseMetadata(items);
1857							if (avatar != null) {
1858								avatar.owner = account.getJid().toBareJid();
1859								if (fileBackend.isAvatarCached(avatar)) {
1860									if (account.setAvatar(avatar.getFilename())) {
1861										databaseBackend.updateAccount(account);
1862									}
1863									getAvatarService().clear(account);
1864									callback.success(avatar);
1865								} else {
1866									fetchAvatar(account, avatar, callback);
1867								}
1868								return;
1869							}
1870						}
1871					}
1872				}
1873				callback.error(0, null);
1874			}
1875		});
1876	}
1877
1878	public void deleteContactOnServer(Contact contact) {
1879		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
1880		contact.resetOption(Contact.Options.DIRTY_PUSH);
1881		contact.setOption(Contact.Options.DIRTY_DELETE);
1882		Account account = contact.getAccount();
1883		if (account.getStatus() == Account.State.ONLINE) {
1884			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1885			Element item = iq.query(Xmlns.ROSTER).addChild("item");
1886			item.setAttribute("jid", contact.getJid().toString());
1887			item.setAttribute("subscription", "remove");
1888			account.getXmppConnection().sendIqPacket(iq, null);
1889		}
1890	}
1891
1892	public void updateConversation(Conversation conversation) {
1893		this.databaseBackend.updateConversation(conversation);
1894	}
1895
1896	public void reconnectAccount(final Account account, final boolean force) {
1897		new Thread(new Runnable() {
1898
1899			@Override
1900			public void run() {
1901				if (account.getXmppConnection() != null) {
1902					disconnect(account, force);
1903				}
1904				if (!account.isOptionSet(Account.OPTION_DISABLED)) {
1905					if (account.getXmppConnection() == null) {
1906						account.setXmppConnection(createConnection(account));
1907					}
1908					Thread thread = new Thread(account.getXmppConnection());
1909					thread.start();
1910					scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
1911				} else {
1912					account.getRoster().clearPresences();
1913					account.setXmppConnection(null);
1914				}
1915			}
1916		}).start();
1917	}
1918
1919	public void invite(Conversation conversation, Jid contact) {
1920		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
1921		sendMessagePacket(conversation.getAccount(), packet);
1922	}
1923
1924	public void resetSendingToWaiting(Account account) {
1925		for (Conversation conversation : getConversations()) {
1926			if (conversation.getAccount() == account) {
1927				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
1928
1929					@Override
1930					public void onMessageFound(Message message) {
1931						markMessage(message, Message.STATUS_WAITING);
1932					}
1933				});
1934			}
1935		}
1936	}
1937
1938	public boolean markMessage(final Account account, final Jid recipient, final String uuid,
1939							   final int status) {
1940		if (uuid == null) {
1941			return false;
1942		} else {
1943			for (Conversation conversation : getConversations()) {
1944				if (conversation.getJid().equals(recipient)
1945						&& conversation.getAccount().equals(account)) {
1946					return markMessage(conversation, uuid, status);
1947				}
1948			}
1949			return false;
1950		}
1951	}
1952
1953	public boolean markMessage(Conversation conversation, String uuid,
1954							   int status) {
1955		if (uuid == null) {
1956			return false;
1957		} else {
1958			Message message = conversation.findSentMessageWithUuid(uuid);
1959			if (message != null) {
1960				markMessage(message, status);
1961				return true;
1962			} else {
1963				return false;
1964			}
1965		}
1966	}
1967
1968	public void markMessage(Message message, int status) {
1969		if (status == Message.STATUS_SEND_FAILED
1970				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
1971				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
1972			return;
1973		}
1974		message.setStatus(status);
1975		databaseBackend.updateMessage(message);
1976		updateConversationUi();
1977	}
1978
1979	public SharedPreferences getPreferences() {
1980		return PreferenceManager
1981				.getDefaultSharedPreferences(getApplicationContext());
1982	}
1983
1984	public boolean forceEncryption() {
1985		return getPreferences().getBoolean("force_encryption", false);
1986	}
1987
1988	public boolean confirmMessages() {
1989		return getPreferences().getBoolean("confirm_messages", true);
1990	}
1991
1992	public boolean saveEncryptedMessages() {
1993		return !getPreferences().getBoolean("dont_save_encrypted", false);
1994	}
1995
1996	public boolean indicateReceived() {
1997		return getPreferences().getBoolean("indicate_received", false);
1998	}
1999
2000	public void updateConversationUi() {
2001		if (mOnConversationUpdate != null) {
2002			mOnConversationUpdate.onConversationUpdate();
2003		}
2004	}
2005
2006	public void updateAccountUi() {
2007		if (mOnAccountUpdate != null) {
2008			mOnAccountUpdate.onAccountUpdate();
2009		}
2010	}
2011
2012	public void updateRosterUi() {
2013		if (mOnRosterUpdate != null) {
2014			mOnRosterUpdate.onRosterUpdate();
2015		}
2016	}
2017
2018	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2019		if (mOnUpdateBlocklist != null) {
2020			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2021		}
2022	}
2023
2024	public void updateMucRosterUi() {
2025		if (mOnMucRosterUpdate != null) {
2026			mOnMucRosterUpdate.onMucRosterUpdate();
2027		}
2028	}
2029
2030	public Account findAccountByJid(final Jid accountJid) {
2031		for (Account account : this.accounts) {
2032			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2033				return account;
2034			}
2035		}
2036		return null;
2037	}
2038
2039	public Conversation findConversationByUuid(String uuid) {
2040		for (Conversation conversation : getConversations()) {
2041			if (conversation.getUuid().equals(uuid)) {
2042				return conversation;
2043			}
2044		}
2045		return null;
2046	}
2047
2048	public void markRead(final Conversation conversation) {
2049		mNotificationService.clear(conversation);
2050		conversation.markRead();
2051	}
2052
2053	public void sendReadMarker(final Conversation conversation) {
2054		final Message markable = conversation.getLatestMarkableMessage();
2055		this.markRead(conversation);
2056		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2057			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2058			Account account = conversation.getAccount();
2059			final Jid to = markable.getCounterpart();
2060			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2061			this.sendMessagePacket(conversation.getAccount(), packet);
2062		}
2063		updateConversationUi();
2064	}
2065
2066	public SecureRandom getRNG() {
2067		return this.mRandom;
2068	}
2069
2070	public MemorizingTrustManager getMemorizingTrustManager() {
2071		return this.mMemorizingTrustManager;
2072	}
2073
2074	public PowerManager getPowerManager() {
2075		return this.pm;
2076	}
2077
2078	public LruCache<String, Bitmap> getBitmapCache() {
2079		return this.mBitmapCache;
2080	}
2081
2082	public void syncRosterToDisk(final Account account) {
2083		new Thread(new Runnable() {
2084
2085			@Override
2086			public void run() {
2087				databaseBackend.writeRoster(account.getRoster());
2088			}
2089		}).start();
2090
2091	}
2092
2093	public List<String> getKnownHosts() {
2094		final List<String> hosts = new ArrayList<>();
2095		for (final Account account : getAccounts()) {
2096			if (!hosts.contains(account.getServer().toString())) {
2097				hosts.add(account.getServer().toString());
2098			}
2099			for (final Contact contact : account.getRoster().getContacts()) {
2100				if (contact.showInRoster()) {
2101					final String server = contact.getServer().toString();
2102					if (server != null && !hosts.contains(server)) {
2103						hosts.add(server);
2104					}
2105				}
2106			}
2107		}
2108		return hosts;
2109	}
2110
2111	public List<String> getKnownConferenceHosts() {
2112		final ArrayList<String> mucServers = new ArrayList<>();
2113		for (final Account account : accounts) {
2114			if (account.getXmppConnection() != null) {
2115				final String server = account.getXmppConnection().getMucServer();
2116				if (server != null && !mucServers.contains(server)) {
2117					mucServers.add(server);
2118				}
2119			}
2120		}
2121		return mucServers;
2122	}
2123
2124	public void sendMessagePacket(Account account, MessagePacket packet) {
2125		XmppConnection connection = account.getXmppConnection();
2126		if (connection != null) {
2127			connection.sendMessagePacket(packet);
2128		}
2129	}
2130
2131	public void sendPresencePacket(Account account, PresencePacket packet) {
2132		XmppConnection connection = account.getXmppConnection();
2133		if (connection != null) {
2134			connection.sendPresencePacket(packet);
2135		}
2136	}
2137
2138	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2139		final XmppConnection connection = account.getXmppConnection();
2140		if (connection != null) {
2141			connection.sendIqPacket(packet, callback);
2142		}
2143	}
2144
2145	public MessageGenerator getMessageGenerator() {
2146		return this.mMessageGenerator;
2147	}
2148
2149	public PresenceGenerator getPresenceGenerator() {
2150		return this.mPresenceGenerator;
2151	}
2152
2153	public IqGenerator getIqGenerator() {
2154		return this.mIqGenerator;
2155	}
2156
2157	public IqParser getIqParser() {
2158		return this.mIqParser;
2159	}
2160
2161	public JingleConnectionManager getJingleConnectionManager() {
2162		return this.mJingleConnectionManager;
2163	}
2164
2165	public MessageArchiveService getMessageArchiveService() {
2166		return this.mMessageArchiveService;
2167	}
2168
2169	public List<Contact> findContacts(Jid jid) {
2170		ArrayList<Contact> contacts = new ArrayList<>();
2171		for (Account account : getAccounts()) {
2172			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2173				Contact contact = account.getRoster().getContactFromRoster(jid);
2174				if (contact != null) {
2175					contacts.add(contact);
2176				}
2177			}
2178		}
2179		return contacts;
2180	}
2181
2182	public NotificationService getNotificationService() {
2183		return this.mNotificationService;
2184	}
2185
2186	public HttpConnectionManager getHttpConnectionManager() {
2187		return this.mHttpConnectionManager;
2188	}
2189
2190	public void resendFailedMessages(final Message message) {
2191		final Collection<Message> messages = new ArrayList<>();
2192		Message current = message;
2193		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2194			messages.add(current);
2195			if (current.mergeable(current.next())) {
2196				current = current.next();
2197			} else {
2198				break;
2199			}
2200		}
2201		for (final Message msg : messages) {
2202			markMessage(msg, Message.STATUS_WAITING);
2203			this.resendMessage(msg);
2204		}
2205	}
2206
2207	public void clearConversationHistory(final Conversation conversation) {
2208		conversation.clearMessages();
2209		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2210		new Thread(new Runnable() {
2211			@Override
2212			public void run() {
2213				databaseBackend.deleteMessagesInConversation(conversation);
2214			}
2215		}).start();
2216	}
2217
2218	public void sendBlockRequest(final Blockable blockable) {
2219		if (blockable != null && blockable.getBlockedJid() != null) {
2220			final Jid jid = blockable.getBlockedJid();
2221			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2222
2223				@Override
2224				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2225					if (packet.getType() == IqPacket.TYPE.RESULT) {
2226						account.getBlocklist().add(jid);
2227						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2228					}
2229				}
2230			});
2231		}
2232	}
2233
2234	public void sendUnblockRequest(final Blockable blockable) {
2235		if (blockable != null && blockable.getJid() != null) {
2236			final Jid jid = blockable.getBlockedJid();
2237			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2238				@Override
2239				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2240					if (packet.getType() == IqPacket.TYPE.RESULT) {
2241						account.getBlocklist().remove(jid);
2242						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2243					}
2244				}
2245			});
2246		}
2247	}
2248
2249	public interface OnMoreMessagesLoaded {
2250		public void onMoreMessagesLoaded(int count, Conversation conversation);
2251
2252		public void informUser(int r);
2253	}
2254
2255	public interface OnAccountPasswordChanged {
2256		public void onPasswordChangeSucceeded();
2257
2258		public void onPasswordChangeFailed();
2259	}
2260
2261	public interface OnAffiliationChanged {
2262		public void onAffiliationChangedSuccessful(Jid jid);
2263
2264		public void onAffiliationChangeFailed(Jid jid, int resId);
2265	}
2266
2267	public interface OnRoleChanged {
2268		public void onRoleChangedSuccessful(String nick);
2269
2270		public void onRoleChangeFailed(String nick, int resid);
2271	}
2272
2273	public interface OnConversationUpdate {
2274		public void onConversationUpdate();
2275	}
2276
2277	public interface OnAccountUpdate {
2278		public void onAccountUpdate();
2279	}
2280
2281	public interface OnRosterUpdate {
2282		public void onRosterUpdate();
2283	}
2284
2285	public interface OnMucRosterUpdate {
2286		public void onMucRosterUpdate();
2287	}
2288
2289	public interface OnConferenceOptionsPushed {
2290		public void onPushSucceeded();
2291
2292		public void onPushFailed();
2293	}
2294
2295	public class XmppConnectionBinder extends Binder {
2296		public XmppConnectionService getService() {
2297			return XmppConnectionService.this;
2298		}
2299	}
2300}