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