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		this.mNotificationService.setIsInForeground(false);
1345		Log.d(Config.LOGTAG, "app switched into background");
1346	}
1347
1348	private void connectMultiModeConversations(Account account) {
1349		List<Conversation> conversations = getConversations();
1350		for (Conversation conversation : conversations) {
1351			if ((conversation.getMode() == Conversation.MODE_MULTI)
1352					&& (conversation.getAccount() == account)) {
1353				conversation.resetMucOptions();
1354				joinMuc(conversation);
1355			}
1356		}
1357	}
1358
1359	public void joinMuc(Conversation conversation) {
1360		Account account = conversation.getAccount();
1361		account.pendingConferenceJoins.remove(conversation);
1362		account.pendingConferenceLeaves.remove(conversation);
1363		if (account.getStatus() == Account.State.ONLINE) {
1364			final String nick = conversation.getMucOptions().getProposedNick();
1365			final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1366			if (joinJid == null) {
1367				return; //safety net
1368			}
1369			Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1370			PresencePacket packet = new PresencePacket();
1371			packet.setFrom(conversation.getAccount().getJid());
1372			packet.setTo(joinJid);
1373			Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1374			if (conversation.getMucOptions().getPassword() != null) {
1375				x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1376			}
1377			x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1378			String sig = account.getPgpSignature();
1379			if (sig != null) {
1380				packet.addChild("status").setContent("online");
1381				packet.addChild("x", "jabber:x:signed").setContent(sig);
1382			}
1383			sendPresencePacket(account, packet);
1384			fetchConferenceConfiguration(conversation);
1385			if (!joinJid.equals(conversation.getJid())) {
1386				conversation.setContactJid(joinJid);
1387				databaseBackend.updateConversation(conversation);
1388			}
1389			conversation.setHasMessagesLeftOnServer(false);
1390		} else {
1391			account.pendingConferenceJoins.add(conversation);
1392		}
1393	}
1394
1395	public void providePasswordForMuc(Conversation conversation, String password) {
1396		if (conversation.getMode() == Conversation.MODE_MULTI) {
1397			conversation.getMucOptions().setPassword(password);
1398			if (conversation.getBookmark() != null) {
1399				conversation.getBookmark().setAutojoin(true);
1400				pushBookmarks(conversation.getAccount());
1401			}
1402			databaseBackend.updateConversation(conversation);
1403			joinMuc(conversation);
1404		}
1405	}
1406
1407	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1408		final MucOptions options = conversation.getMucOptions();
1409		final Jid joinJid = options.createJoinJid(nick);
1410		if (options.online()) {
1411			Account account = conversation.getAccount();
1412			options.setOnRenameListener(new OnRenameListener() {
1413
1414				@Override
1415				public void onSuccess() {
1416					conversation.setContactJid(joinJid);
1417					databaseBackend.updateConversation(conversation);
1418					Bookmark bookmark = conversation.getBookmark();
1419					if (bookmark != null) {
1420						bookmark.setNick(nick);
1421						pushBookmarks(bookmark.getAccount());
1422					}
1423					callback.success(conversation);
1424				}
1425
1426				@Override
1427				public void onFailure() {
1428					callback.error(R.string.nick_in_use, conversation);
1429				}
1430			});
1431
1432			PresencePacket packet = new PresencePacket();
1433			packet.setTo(joinJid);
1434			packet.setFrom(conversation.getAccount().getJid());
1435
1436			String sig = account.getPgpSignature();
1437			if (sig != null) {
1438				packet.addChild("status").setContent("online");
1439				packet.addChild("x", "jabber:x:signed").setContent(sig);
1440			}
1441			sendPresencePacket(account, packet);
1442		} else {
1443			conversation.setContactJid(joinJid);
1444			databaseBackend.updateConversation(conversation);
1445			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1446				Bookmark bookmark = conversation.getBookmark();
1447				if (bookmark != null) {
1448					bookmark.setNick(nick);
1449					pushBookmarks(bookmark.getAccount());
1450				}
1451				joinMuc(conversation);
1452			}
1453		}
1454	}
1455
1456	public void leaveMuc(Conversation conversation) {
1457		Account account = conversation.getAccount();
1458		account.pendingConferenceJoins.remove(conversation);
1459		account.pendingConferenceLeaves.remove(conversation);
1460		if (account.getStatus() == Account.State.ONLINE) {
1461			PresencePacket packet = new PresencePacket();
1462			packet.setTo(conversation.getJid());
1463			packet.setFrom(conversation.getAccount().getJid());
1464			packet.setAttribute("type", "unavailable");
1465			sendPresencePacket(conversation.getAccount(), packet);
1466			conversation.getMucOptions().setOffline();
1467			conversation.deregisterWithBookmark();
1468			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1469					+ ": leaving muc " + conversation.getJid());
1470		} else {
1471			account.pendingConferenceLeaves.add(conversation);
1472		}
1473	}
1474
1475	private String findConferenceServer(final Account account) {
1476		String server;
1477		if (account.getXmppConnection() != null) {
1478			server = account.getXmppConnection().getMucServer();
1479			if (server != null) {
1480				return server;
1481			}
1482		}
1483		for (Account other : getAccounts()) {
1484			if (other != account && other.getXmppConnection() != null) {
1485				server = other.getXmppConnection().getMucServer();
1486				if (server != null) {
1487					return server;
1488				}
1489			}
1490		}
1491		return null;
1492	}
1493
1494	public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1495		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1496		if (account.getStatus() == Account.State.ONLINE) {
1497			try {
1498				String server = findConferenceServer(account);
1499				if (server == null) {
1500					if (callback != null) {
1501						callback.error(R.string.no_conference_server_found, null);
1502					}
1503					return;
1504				}
1505				String name = new BigInteger(75, getRNG()).toString(32);
1506				Jid jid = Jid.fromParts(name, server, null);
1507				final Conversation conversation = findOrCreateConversation(account, jid, true);
1508				joinMuc(conversation);
1509				Bundle options = new Bundle();
1510				options.putString("muc#roomconfig_persistentroom", "1");
1511				options.putString("muc#roomconfig_membersonly", "1");
1512				options.putString("muc#roomconfig_publicroom", "0");
1513				options.putString("muc#roomconfig_whois", "anyone");
1514				pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1515					@Override
1516					public void onPushSucceeded() {
1517						for (Jid invite : jids) {
1518							invite(conversation, invite);
1519						}
1520						if (callback != null) {
1521							callback.success(conversation);
1522						}
1523					}
1524
1525					@Override
1526					public void onPushFailed() {
1527						if (callback != null) {
1528							callback.error(R.string.conference_creation_failed, conversation);
1529						}
1530					}
1531				});
1532
1533			} catch (InvalidJidException e) {
1534				if (callback != null) {
1535					callback.error(R.string.conference_creation_failed, null);
1536				}
1537			}
1538		} else {
1539			if (callback != null) {
1540				callback.error(R.string.not_connected_try_again, null);
1541			}
1542		}
1543	}
1544
1545	public void fetchConferenceConfiguration(final Conversation conversation) {
1546		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1547		request.setTo(conversation.getJid().toBareJid());
1548		request.query("http://jabber.org/protocol/disco#info");
1549		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1550			@Override
1551			public void onIqPacketReceived(Account account, IqPacket packet) {
1552				if (packet.getType() != IqPacket.TYPE.ERROR) {
1553					ArrayList<String> features = new ArrayList<>();
1554					for (Element child : packet.query().getChildren()) {
1555						if (child != null && child.getName().equals("feature")) {
1556							String var = child.getAttribute("var");
1557							if (var != null) {
1558								features.add(var);
1559							}
1560						}
1561					}
1562					conversation.getMucOptions().updateFeatures(features);
1563					updateConversationUi();
1564				}
1565			}
1566		});
1567	}
1568
1569	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1570		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1571		request.setTo(conversation.getJid().toBareJid());
1572		request.query("http://jabber.org/protocol/muc#owner");
1573		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1574			@Override
1575			public void onIqPacketReceived(Account account, IqPacket packet) {
1576				if (packet.getType() != IqPacket.TYPE.ERROR) {
1577					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1578					for (Field field : data.getFields()) {
1579						if (options.containsKey(field.getName())) {
1580							field.setValue(options.getString(field.getName()));
1581						}
1582					}
1583					data.submit();
1584					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1585					set.setTo(conversation.getJid().toBareJid());
1586					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1587					sendIqPacket(account, set, new OnIqPacketReceived() {
1588						@Override
1589						public void onIqPacketReceived(Account account, IqPacket packet) {
1590							if (packet.getType() == IqPacket.TYPE.RESULT) {
1591								if (callback != null) {
1592									callback.onPushSucceeded();
1593								}
1594							} else {
1595								if (callback != null) {
1596									callback.onPushFailed();
1597								}
1598							}
1599						}
1600					});
1601				} else {
1602					if (callback != null) {
1603						callback.onPushFailed();
1604					}
1605				}
1606			}
1607		});
1608	}
1609
1610	public void pushSubjectToConference(final Conversation conference, final String subject) {
1611		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1612		this.sendMessagePacket(conference.getAccount(), packet);
1613		final MucOptions mucOptions = conference.getMucOptions();
1614		final MucOptions.User self = mucOptions.getSelf();
1615		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1616			Bundle options = new Bundle();
1617			options.putString("muc#roomconfig_persistentroom", "1");
1618			this.pushConferenceConfiguration(conference, options, null);
1619		}
1620	}
1621
1622	public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1623		final Jid jid = user.toBareJid();
1624		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
1625		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1626			@Override
1627			public void onIqPacketReceived(Account account, IqPacket packet) {
1628				if (packet.getType() == IqPacket.TYPE.RESULT) {
1629					callback.onAffiliationChangedSuccessful(jid);
1630				} else {
1631					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
1632				}
1633			}
1634		});
1635	}
1636
1637	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
1638		List<Jid> jids = new ArrayList<>();
1639		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
1640			if (user.getAffiliation() == before) {
1641				jids.add(user.getJid());
1642			}
1643		}
1644		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
1645		sendIqPacket(conference.getAccount(), request, null);
1646	}
1647
1648	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
1649		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
1650		Log.d(Config.LOGTAG, request.toString());
1651		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1652			@Override
1653			public void onIqPacketReceived(Account account, IqPacket packet) {
1654				Log.d(Config.LOGTAG, packet.toString());
1655				if (packet.getType() == IqPacket.TYPE.RESULT) {
1656					callback.onRoleChangedSuccessful(nick);
1657				} else {
1658					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
1659				}
1660			}
1661		});
1662	}
1663
1664	public void disconnect(Account account, boolean force) {
1665		if ((account.getStatus() == Account.State.ONLINE)
1666				|| (account.getStatus() == Account.State.DISABLED)) {
1667			if (!force) {
1668				List<Conversation> conversations = getConversations();
1669				for (Conversation conversation : conversations) {
1670					if (conversation.getAccount() == account) {
1671						if (conversation.getMode() == Conversation.MODE_MULTI) {
1672							leaveMuc(conversation);
1673						} else {
1674							if (conversation.endOtrIfNeeded()) {
1675								Log.d(Config.LOGTAG, account.getJid().toBareJid()
1676										+ ": ended otr session with "
1677										+ conversation.getJid());
1678							}
1679						}
1680					}
1681				}
1682			}
1683			account.getXmppConnection().disconnect(force);
1684		}
1685	}
1686
1687	@Override
1688	public IBinder onBind(Intent intent) {
1689		return mBinder;
1690	}
1691
1692	public void updateMessage(Message message) {
1693		databaseBackend.updateMessage(message);
1694		updateConversationUi();
1695	}
1696
1697	protected void syncDirtyContacts(Account account) {
1698		for (Contact contact : account.getRoster().getContacts()) {
1699			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1700				pushContactToServer(contact);
1701			}
1702			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1703				deleteContactOnServer(contact);
1704			}
1705		}
1706	}
1707
1708	public void createContact(Contact contact) {
1709		SharedPreferences sharedPref = getPreferences();
1710		boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1711		if (autoGrant) {
1712			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1713			contact.setOption(Contact.Options.ASKING);
1714		}
1715		pushContactToServer(contact);
1716	}
1717
1718	public void onOtrSessionEstablished(Conversation conversation) {
1719		final Account account = conversation.getAccount();
1720		final Session otrSession = conversation.getOtrSession();
1721		Log.d(Config.LOGTAG,
1722				account.getJid().toBareJid() + " otr session established with "
1723						+ conversation.getJid() + "/"
1724						+ otrSession.getSessionID().getUserID());
1725		conversation.findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
1726
1727			@Override
1728			public void onMessageFound(Message message) {
1729				SessionID id = otrSession.getSessionID();
1730				try {
1731					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
1732				} catch (InvalidJidException e) {
1733					return;
1734				}
1735				if (message.getType() == Message.TYPE_TEXT) {
1736					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message, true);
1737					if (outPacket != null) {
1738						message.setStatus(Message.STATUS_SEND);
1739						databaseBackend.updateMessage(message);
1740						sendMessagePacket(account, outPacket);
1741					}
1742				} else if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
1743					mJingleConnectionManager.createNewConnection(message);
1744				}
1745				updateConversationUi();
1746			}
1747		});
1748	}
1749
1750	public boolean renewSymmetricKey(Conversation conversation) {
1751		Account account = conversation.getAccount();
1752		byte[] symmetricKey = new byte[32];
1753		this.mRandom.nextBytes(symmetricKey);
1754		Session otrSession = conversation.getOtrSession();
1755		if (otrSession != null) {
1756			MessagePacket packet = new MessagePacket();
1757			packet.setType(MessagePacket.TYPE_CHAT);
1758			packet.setFrom(account.getJid());
1759			packet.addChild("private", "urn:xmpp:carbons:2");
1760			packet.addChild("no-copy", "urn:xmpp:hints");
1761			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
1762					+ otrSession.getSessionID().getUserID());
1763			try {
1764				packet.setBody(otrSession
1765						.transformSending(CryptoHelper.FILETRANSFER
1766								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
1767				sendMessagePacket(account, packet);
1768				conversation.setSymmetricKey(symmetricKey);
1769				return true;
1770			} catch (OtrException e) {
1771				return false;
1772			}
1773		}
1774		return false;
1775	}
1776
1777	public void pushContactToServer(final Contact contact) {
1778		contact.resetOption(Contact.Options.DIRTY_DELETE);
1779		contact.setOption(Contact.Options.DIRTY_PUSH);
1780		final Account account = contact.getAccount();
1781		if (account.getStatus() == Account.State.ONLINE) {
1782			final boolean ask = contact.getOption(Contact.Options.ASKING);
1783			final boolean sendUpdates = contact
1784					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
1785					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
1786			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1787			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
1788			account.getXmppConnection().sendIqPacket(iq, null);
1789			if (sendUpdates) {
1790				sendPresencePacket(account,
1791						mPresenceGenerator.sendPresenceUpdatesTo(contact));
1792			}
1793			if (ask) {
1794				sendPresencePacket(account,
1795						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
1796			}
1797		}
1798	}
1799
1800	public void publishAvatar(final Account account,
1801							  final Uri image,
1802							  final UiCallback<Avatar> callback) {
1803		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
1804		final int size = Config.AVATAR_SIZE;
1805		final Avatar avatar = getFileBackend()
1806				.getPepAvatar(image, size, format);
1807		if (avatar != null) {
1808			avatar.height = size;
1809			avatar.width = size;
1810			if (format.equals(Bitmap.CompressFormat.WEBP)) {
1811				avatar.type = "image/webp";
1812			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1813				avatar.type = "image/jpeg";
1814			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
1815				avatar.type = "image/png";
1816			}
1817			if (!getFileBackend().save(avatar)) {
1818				callback.error(R.string.error_saving_avatar, avatar);
1819				return;
1820			}
1821			final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
1822			this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1823
1824				@Override
1825				public void onIqPacketReceived(Account account, IqPacket result) {
1826					if (result.getType() == IqPacket.TYPE.RESULT) {
1827						final IqPacket packet = XmppConnectionService.this.mIqGenerator
1828								.publishAvatarMetadata(avatar);
1829						sendIqPacket(account, packet, new OnIqPacketReceived() {
1830
1831							@Override
1832							public void onIqPacketReceived(Account account,
1833														   IqPacket result) {
1834								if (result.getType() == IqPacket.TYPE.RESULT) {
1835									if (account.setAvatar(avatar.getFilename())) {
1836										databaseBackend.updateAccount(account);
1837									}
1838									callback.success(avatar);
1839								} else {
1840									callback.error(
1841											R.string.error_publish_avatar_server_reject,
1842											avatar);
1843								}
1844							}
1845						});
1846					} else {
1847						callback.error(
1848								R.string.error_publish_avatar_server_reject,
1849								avatar);
1850					}
1851				}
1852			});
1853		} else {
1854			callback.error(R.string.error_publish_avatar_converting, null);
1855		}
1856	}
1857
1858	public void fetchAvatar(Account account, Avatar avatar) {
1859		fetchAvatar(account, avatar, null);
1860	}
1861
1862	public void fetchAvatar(Account account, final Avatar avatar,
1863							final UiCallback<Avatar> callback) {
1864		IqPacket packet = this.mIqGenerator.retrieveAvatar(avatar);
1865		sendIqPacket(account, packet, new OnIqPacketReceived() {
1866
1867			@Override
1868			public void onIqPacketReceived(Account account, IqPacket result) {
1869				final String ERROR = account.getJid().toBareJid()
1870						+ ": fetching avatar for " + avatar.owner + " failed ";
1871				if (result.getType() == IqPacket.TYPE.RESULT) {
1872					avatar.image = mIqParser.avatarData(result);
1873					if (avatar.image != null) {
1874						if (getFileBackend().save(avatar)) {
1875							if (account.getJid().toBareJid().equals(avatar.owner)) {
1876								if (account.setAvatar(avatar.getFilename())) {
1877									databaseBackend.updateAccount(account);
1878								}
1879								getAvatarService().clear(account);
1880								updateConversationUi();
1881								updateAccountUi();
1882							} else {
1883								Contact contact = account.getRoster()
1884										.getContact(avatar.owner);
1885								contact.setAvatar(avatar.getFilename());
1886								getAvatarService().clear(contact);
1887								updateConversationUi();
1888								updateRosterUi();
1889							}
1890							if (callback != null) {
1891								callback.success(avatar);
1892							}
1893							Log.d(Config.LOGTAG, account.getJid().toBareJid()
1894									+ ": succesfully fetched avatar for "
1895									+ avatar.owner);
1896							return;
1897						}
1898					} else {
1899
1900						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
1901					}
1902				} else {
1903					Element error = result.findChild("error");
1904					if (error == null) {
1905						Log.d(Config.LOGTAG, ERROR + "(server error)");
1906					} else {
1907						Log.d(Config.LOGTAG, ERROR + error.toString());
1908					}
1909				}
1910				if (callback != null) {
1911					callback.error(0, null);
1912				}
1913
1914			}
1915		});
1916	}
1917
1918	public void checkForAvatar(Account account,
1919							   final UiCallback<Avatar> callback) {
1920		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
1921		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1922
1923			@Override
1924			public void onIqPacketReceived(Account account, IqPacket packet) {
1925				if (packet.getType() == IqPacket.TYPE.RESULT) {
1926					Element pubsub = packet.findChild("pubsub",
1927							"http://jabber.org/protocol/pubsub");
1928					if (pubsub != null) {
1929						Element items = pubsub.findChild("items");
1930						if (items != null) {
1931							Avatar avatar = Avatar.parseMetadata(items);
1932							if (avatar != null) {
1933								avatar.owner = account.getJid().toBareJid();
1934								if (fileBackend.isAvatarCached(avatar)) {
1935									if (account.setAvatar(avatar.getFilename())) {
1936										databaseBackend.updateAccount(account);
1937									}
1938									getAvatarService().clear(account);
1939									callback.success(avatar);
1940								} else {
1941									fetchAvatar(account, avatar, callback);
1942								}
1943								return;
1944							}
1945						}
1946					}
1947				}
1948				callback.error(0, null);
1949			}
1950		});
1951	}
1952
1953	public void deleteContactOnServer(Contact contact) {
1954		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
1955		contact.resetOption(Contact.Options.DIRTY_PUSH);
1956		contact.setOption(Contact.Options.DIRTY_DELETE);
1957		Account account = contact.getAccount();
1958		if (account.getStatus() == Account.State.ONLINE) {
1959			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1960			Element item = iq.query(Xmlns.ROSTER).addChild("item");
1961			item.setAttribute("jid", contact.getJid().toString());
1962			item.setAttribute("subscription", "remove");
1963			account.getXmppConnection().sendIqPacket(iq, null);
1964		}
1965	}
1966
1967	public void updateConversation(Conversation conversation) {
1968		this.databaseBackend.updateConversation(conversation);
1969	}
1970
1971	public void reconnectAccount(final Account account, final boolean force) {
1972		new Thread(new Runnable() {
1973
1974			@Override
1975			public void run() {
1976				if (account.getXmppConnection() != null) {
1977					disconnect(account, force);
1978				}
1979				if (!account.isOptionSet(Account.OPTION_DISABLED)) {
1980					if (account.getXmppConnection() == null) {
1981						account.setXmppConnection(createConnection(account));
1982					}
1983					Thread thread = new Thread(account.getXmppConnection());
1984					thread.start();
1985					scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
1986				} else {
1987					account.getRoster().clearPresences();
1988					account.setXmppConnection(null);
1989				}
1990			}
1991		}).start();
1992	}
1993
1994	public void invite(Conversation conversation, Jid contact) {
1995		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
1996		sendMessagePacket(conversation.getAccount(), packet);
1997	}
1998
1999	public void resetSendingToWaiting(Account account) {
2000		for (Conversation conversation : getConversations()) {
2001			if (conversation.getAccount() == account) {
2002				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2003
2004					@Override
2005					public void onMessageFound(Message message) {
2006						markMessage(message, Message.STATUS_WAITING);
2007					}
2008				});
2009			}
2010		}
2011	}
2012
2013	public boolean markMessage(final Account account, final Jid recipient, final String uuid,
2014							   final int status) {
2015		if (uuid == null) {
2016			return false;
2017		} else {
2018			for (Conversation conversation : getConversations()) {
2019				if (conversation.getJid().equals(recipient)
2020						&& conversation.getAccount().equals(account)) {
2021					return markMessage(conversation, uuid, status);
2022				}
2023			}
2024			return false;
2025		}
2026	}
2027
2028	public boolean markMessage(Conversation conversation, String uuid,
2029							   int status) {
2030		if (uuid == null) {
2031			return false;
2032		} else {
2033			Message message = conversation.findSentMessageWithUuid(uuid);
2034			if (message != null) {
2035				markMessage(message, status);
2036				return true;
2037			} else {
2038				return false;
2039			}
2040		}
2041	}
2042
2043	public void markMessage(Message message, int status) {
2044		if (status == Message.STATUS_SEND_FAILED
2045				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2046				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2047			return;
2048		}
2049		message.setStatus(status);
2050		databaseBackend.updateMessage(message);
2051		updateConversationUi();
2052	}
2053
2054	public SharedPreferences getPreferences() {
2055		return PreferenceManager
2056				.getDefaultSharedPreferences(getApplicationContext());
2057	}
2058
2059	public boolean forceEncryption() {
2060		return getPreferences().getBoolean("force_encryption", false);
2061	}
2062
2063	public boolean confirmMessages() {
2064		return getPreferences().getBoolean("confirm_messages", true);
2065	}
2066
2067	public boolean sendChatStates() {
2068		return getPreferences().getBoolean("chat_states", false);
2069	}
2070
2071	public boolean saveEncryptedMessages() {
2072		return !getPreferences().getBoolean("dont_save_encrypted", false);
2073	}
2074
2075	public boolean indicateReceived() {
2076		return getPreferences().getBoolean("indicate_received", false);
2077	}
2078
2079	public void updateConversationUi() {
2080		if (mOnConversationUpdate != null) {
2081			mOnConversationUpdate.onConversationUpdate();
2082		}
2083	}
2084
2085	public void updateAccountUi() {
2086		if (mOnAccountUpdate != null) {
2087			mOnAccountUpdate.onAccountUpdate();
2088		}
2089	}
2090
2091	public void updateRosterUi() {
2092		if (mOnRosterUpdate != null) {
2093			mOnRosterUpdate.onRosterUpdate();
2094		}
2095	}
2096
2097	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2098		if (mOnUpdateBlocklist != null) {
2099			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2100		}
2101	}
2102
2103	public void updateMucRosterUi() {
2104		if (mOnMucRosterUpdate != null) {
2105			mOnMucRosterUpdate.onMucRosterUpdate();
2106		}
2107	}
2108
2109	public Account findAccountByJid(final Jid accountJid) {
2110		for (Account account : this.accounts) {
2111			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2112				return account;
2113			}
2114		}
2115		return null;
2116	}
2117
2118	public Conversation findConversationByUuid(String uuid) {
2119		for (Conversation conversation : getConversations()) {
2120			if (conversation.getUuid().equals(uuid)) {
2121				return conversation;
2122			}
2123		}
2124		return null;
2125	}
2126
2127	public void markRead(final Conversation conversation) {
2128		mNotificationService.clear(conversation);
2129		conversation.markRead();
2130	}
2131
2132	public void sendReadMarker(final Conversation conversation) {
2133		final Message markable = conversation.getLatestMarkableMessage();
2134		this.markRead(conversation);
2135		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2136			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2137			Account account = conversation.getAccount();
2138			final Jid to = markable.getCounterpart();
2139			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2140			this.sendMessagePacket(conversation.getAccount(), packet);
2141		}
2142		updateConversationUi();
2143	}
2144
2145	public SecureRandom getRNG() {
2146		return this.mRandom;
2147	}
2148
2149	public MemorizingTrustManager getMemorizingTrustManager() {
2150		return this.mMemorizingTrustManager;
2151	}
2152
2153	public PowerManager getPowerManager() {
2154		return this.pm;
2155	}
2156
2157	public LruCache<String, Bitmap> getBitmapCache() {
2158		return this.mBitmapCache;
2159	}
2160
2161	public void syncRosterToDisk(final Account account) {
2162		new Thread(new Runnable() {
2163
2164			@Override
2165			public void run() {
2166				databaseBackend.writeRoster(account.getRoster());
2167			}
2168		}).start();
2169
2170	}
2171
2172	public List<String> getKnownHosts() {
2173		final List<String> hosts = new ArrayList<>();
2174		for (final Account account : getAccounts()) {
2175			if (!hosts.contains(account.getServer().toString())) {
2176				hosts.add(account.getServer().toString());
2177			}
2178			for (final Contact contact : account.getRoster().getContacts()) {
2179				if (contact.showInRoster()) {
2180					final String server = contact.getServer().toString();
2181					if (server != null && !hosts.contains(server)) {
2182						hosts.add(server);
2183					}
2184				}
2185			}
2186		}
2187		return hosts;
2188	}
2189
2190	public List<String> getKnownConferenceHosts() {
2191		final ArrayList<String> mucServers = new ArrayList<>();
2192		for (final Account account : accounts) {
2193			if (account.getXmppConnection() != null) {
2194				final String server = account.getXmppConnection().getMucServer();
2195				if (server != null && !mucServers.contains(server)) {
2196					mucServers.add(server);
2197				}
2198			}
2199		}
2200		return mucServers;
2201	}
2202
2203	public void sendMessagePacket(Account account, MessagePacket packet) {
2204		XmppConnection connection = account.getXmppConnection();
2205		if (connection != null) {
2206			connection.sendMessagePacket(packet);
2207		}
2208	}
2209
2210	public void sendPresencePacket(Account account, PresencePacket packet) {
2211		XmppConnection connection = account.getXmppConnection();
2212		if (connection != null) {
2213			connection.sendPresencePacket(packet);
2214		}
2215	}
2216
2217	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2218		final XmppConnection connection = account.getXmppConnection();
2219		if (connection != null) {
2220			connection.sendIqPacket(packet, callback);
2221		}
2222	}
2223
2224	public void sendPresence(final Account account) {
2225		sendPresencePacket(account, mPresenceGenerator.sendPresence(account));
2226	}
2227
2228	public MessageGenerator getMessageGenerator() {
2229		return this.mMessageGenerator;
2230	}
2231
2232	public PresenceGenerator getPresenceGenerator() {
2233		return this.mPresenceGenerator;
2234	}
2235
2236	public IqGenerator getIqGenerator() {
2237		return this.mIqGenerator;
2238	}
2239
2240	public IqParser getIqParser() {
2241		return this.mIqParser;
2242	}
2243
2244	public JingleConnectionManager getJingleConnectionManager() {
2245		return this.mJingleConnectionManager;
2246	}
2247
2248	public MessageArchiveService getMessageArchiveService() {
2249		return this.mMessageArchiveService;
2250	}
2251
2252	public List<Contact> findContacts(Jid jid) {
2253		ArrayList<Contact> contacts = new ArrayList<>();
2254		for (Account account : getAccounts()) {
2255			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2256				Contact contact = account.getRoster().getContactFromRoster(jid);
2257				if (contact != null) {
2258					contacts.add(contact);
2259				}
2260			}
2261		}
2262		return contacts;
2263	}
2264
2265	public NotificationService getNotificationService() {
2266		return this.mNotificationService;
2267	}
2268
2269	public HttpConnectionManager getHttpConnectionManager() {
2270		return this.mHttpConnectionManager;
2271	}
2272
2273	public void resendFailedMessages(final Message message) {
2274		final Collection<Message> messages = new ArrayList<>();
2275		Message current = message;
2276		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2277			messages.add(current);
2278			if (current.mergeable(current.next())) {
2279				current = current.next();
2280			} else {
2281				break;
2282			}
2283		}
2284		for (final Message msg : messages) {
2285			markMessage(msg, Message.STATUS_WAITING);
2286			this.resendMessage(msg);
2287		}
2288	}
2289
2290	public void clearConversationHistory(final Conversation conversation) {
2291		conversation.clearMessages();
2292		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2293		new Thread(new Runnable() {
2294			@Override
2295			public void run() {
2296				databaseBackend.deleteMessagesInConversation(conversation);
2297			}
2298		}).start();
2299	}
2300
2301	public void sendBlockRequest(final Blockable blockable) {
2302		if (blockable != null && blockable.getBlockedJid() != null) {
2303			final Jid jid = blockable.getBlockedJid();
2304			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2305
2306				@Override
2307				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2308					if (packet.getType() == IqPacket.TYPE.RESULT) {
2309						account.getBlocklist().add(jid);
2310						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2311					}
2312				}
2313			});
2314		}
2315	}
2316
2317	public void sendUnblockRequest(final Blockable blockable) {
2318		if (blockable != null && blockable.getJid() != null) {
2319			final Jid jid = blockable.getBlockedJid();
2320			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2321				@Override
2322				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2323					if (packet.getType() == IqPacket.TYPE.RESULT) {
2324						account.getBlocklist().remove(jid);
2325						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2326					}
2327				}
2328			});
2329		}
2330	}
2331
2332	public interface OnMoreMessagesLoaded {
2333		public void onMoreMessagesLoaded(int count, Conversation conversation);
2334
2335		public void informUser(int r);
2336	}
2337
2338	public interface OnAccountPasswordChanged {
2339		public void onPasswordChangeSucceeded();
2340
2341		public void onPasswordChangeFailed();
2342	}
2343
2344	public interface OnAffiliationChanged {
2345		public void onAffiliationChangedSuccessful(Jid jid);
2346
2347		public void onAffiliationChangeFailed(Jid jid, int resId);
2348	}
2349
2350	public interface OnRoleChanged {
2351		public void onRoleChangedSuccessful(String nick);
2352
2353		public void onRoleChangeFailed(String nick, int resid);
2354	}
2355
2356	public interface OnConversationUpdate {
2357		public void onConversationUpdate();
2358	}
2359
2360	public interface OnAccountUpdate {
2361		public void onAccountUpdate();
2362	}
2363
2364	public interface OnRosterUpdate {
2365		public void onRosterUpdate();
2366	}
2367
2368	public interface OnMucRosterUpdate {
2369		public void onMucRosterUpdate();
2370	}
2371
2372	public interface OnConferenceOptionsPushed {
2373		public void onPushSucceeded();
2374
2375		public void onPushFailed();
2376	}
2377
2378	public class XmppConnectionBinder extends Binder {
2379		public XmppConnectionService getService() {
2380			return XmppConnectionService.this;
2381		}
2382	}
2383}