XmppConnectionService.java

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