XmppConnectionService.java

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