XmppConnectionService.java

   1package eu.siacs.conversations.services;
   2
   3import java.text.ParseException;
   4import java.text.SimpleDateFormat;
   5import java.util.Collections;
   6import java.util.Comparator;
   7import java.util.Date;
   8import java.util.Hashtable;
   9import java.util.List;
  10import java.util.Locale;
  11import java.util.Random;
  12
  13import org.openintents.openpgp.util.OpenPgpApi;
  14import org.openintents.openpgp.util.OpenPgpServiceConnection;
  15
  16import net.java.otr4j.OtrException;
  17import net.java.otr4j.session.Session;
  18import net.java.otr4j.session.SessionStatus;
  19
  20import eu.siacs.conversations.crypto.PgpEngine;
  21import eu.siacs.conversations.crypto.PgpEngine.OpenPgpException;
  22import eu.siacs.conversations.entities.Account;
  23import eu.siacs.conversations.entities.Contact;
  24import eu.siacs.conversations.entities.Conversation;
  25import eu.siacs.conversations.entities.Message;
  26import eu.siacs.conversations.entities.MucOptions;
  27import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
  28import eu.siacs.conversations.entities.Presences;
  29import eu.siacs.conversations.persistance.DatabaseBackend;
  30import eu.siacs.conversations.persistance.OnPhoneContactsMerged;
  31import eu.siacs.conversations.ui.OnAccountListChangedListener;
  32import eu.siacs.conversations.ui.OnConversationListChangedListener;
  33import eu.siacs.conversations.ui.OnRosterFetchedListener;
  34import eu.siacs.conversations.utils.ExceptionHelper;
  35import eu.siacs.conversations.utils.MessageParser;
  36import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
  37import eu.siacs.conversations.utils.PhoneHelper;
  38import eu.siacs.conversations.utils.UIHelper;
  39import eu.siacs.conversations.xml.Element;
  40import eu.siacs.conversations.xmpp.OnBindListener;
  41import eu.siacs.conversations.xmpp.OnIqPacketReceived;
  42import eu.siacs.conversations.xmpp.OnJinglePacketReceived;
  43import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
  44import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
  45import eu.siacs.conversations.xmpp.OnStatusChanged;
  46import eu.siacs.conversations.xmpp.OnTLSExceptionReceived;
  47import eu.siacs.conversations.xmpp.XmppConnection;
  48import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  49import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
  50import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
  51import eu.siacs.conversations.xmpp.stanzas.jingle.JinglePacket;
  52import android.app.AlarmManager;
  53import android.app.PendingIntent;
  54import android.app.Service;
  55import android.content.Context;
  56import android.content.Intent;
  57import android.content.SharedPreferences;
  58import android.database.ContentObserver;
  59import android.database.DatabaseUtils;
  60import android.net.ConnectivityManager;
  61import android.net.NetworkInfo;
  62import android.os.Binder;
  63import android.os.Bundle;
  64import android.os.IBinder;
  65import android.os.PowerManager;
  66import android.os.PowerManager.WakeLock;
  67import android.os.SystemClock;
  68import android.preference.PreferenceManager;
  69import android.provider.ContactsContract;
  70import android.util.Log;
  71
  72public class XmppConnectionService extends Service {
  73
  74	protected static final String LOGTAG = "xmppService";
  75	public DatabaseBackend databaseBackend;
  76
  77	public long startDate;
  78
  79	private static final int PING_MAX_INTERVAL = 300;
  80	private static final int PING_MIN_INTERVAL = 10;
  81	private static final int PING_TIMEOUT = 5;
  82	private static final int CONNECT_TIMEOUT = 60;
  83
  84	private List<Account> accounts;
  85	private List<Conversation> conversations = null;
  86
  87	public OnConversationListChangedListener convChangedListener = null;
  88	private int convChangedListenerCount = 0;
  89	private OnAccountListChangedListener accountChangedListener = null;
  90	private OnTLSExceptionReceived tlsException = null;
  91
  92	public void setOnTLSExceptionReceivedListener(
  93			OnTLSExceptionReceived listener) {
  94		tlsException = listener;
  95	}
  96
  97	private Random mRandom = new Random(System.currentTimeMillis());
  98
  99	private ContentObserver contactObserver = new ContentObserver(null) {
 100		@Override
 101		public void onChange(boolean selfChange) {
 102			super.onChange(selfChange);
 103			Log.d(LOGTAG, "contact list has changed");
 104			mergePhoneContactsWithRoster(null);
 105		}
 106	};
 107
 108	private XmppConnectionService service = this;
 109
 110	private final IBinder mBinder = new XmppConnectionBinder();
 111	private OnMessagePacketReceived messageListener = new OnMessagePacketReceived() {
 112
 113		@Override
 114		public void onMessagePacketReceived(Account account,
 115				MessagePacket packet) {
 116			Message message = null;
 117			boolean notify = true;
 118			if ((packet.getType() == MessagePacket.TYPE_CHAT)) {
 119				String pgpBody = MessageParser.getPgpBody(packet);
 120				if (pgpBody != null) {
 121					message = MessageParser.parsePgpChat(pgpBody, packet,
 122							account, service);
 123					message.markUnread();
 124				} else if (packet.hasChild("body")
 125						&& (packet.getBody().startsWith("?OTR"))) {
 126					message = MessageParser.parseOtrChat(packet, account,
 127							service);
 128					if (message != null) {
 129						message.markUnread();
 130					}
 131				} else if (packet.hasChild("body")) {
 132					message = MessageParser.parsePlainTextChat(packet, account,
 133							service);
 134					message.markUnread();
 135				} else if (packet.hasChild("received")
 136						|| (packet.hasChild("sent"))) {
 137					message = MessageParser.parseCarbonMessage(packet, account,
 138							service);
 139					if (message != null) {
 140						message.getConversation().markRead();
 141					}
 142					notify = false;
 143				}
 144
 145			} else if (packet.getType() == MessagePacket.TYPE_GROUPCHAT) {
 146				message = MessageParser
 147						.parseGroupchat(packet, account, service);
 148				if (message != null) {
 149					if (message.getStatus() == Message.STATUS_RECIEVED) {
 150						message.markUnread();
 151					} else {
 152						message.getConversation().markRead();
 153						notify = false;
 154					}
 155				}
 156			} else if (packet.getType() == MessagePacket.TYPE_ERROR) {
 157				message = MessageParser.parseError(packet, account, service);
 158			} else if (packet.getType() == MessagePacket.TYPE_NORMAL) {
 159				if (packet.hasChild("x")) {
 160					Element x = packet.findChild("x");
 161					if (x.hasChild("invite")) {
 162						findOrCreateConversation(account, packet.getFrom(),
 163								true);
 164						if (convChangedListener != null) {
 165							convChangedListener.onConversationListChanged();
 166						}
 167						Log.d(LOGTAG,
 168								"invitation received to " + packet.getFrom());
 169					}
 170
 171				} else {
 172					// Log.d(LOGTAG, "unparsed message " + packet.toString());
 173				}
 174			}
 175			if ((message == null) || (message.getBody() == null)) {
 176				return;
 177			}
 178			if (packet.hasChild("delay")) {
 179				try {
 180					String stamp = packet.findChild("delay").getAttribute(
 181							"stamp");
 182					stamp = stamp.replace("Z", "+0000");
 183					Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
 184							.parse(stamp);
 185					message.setTime(date.getTime());
 186				} catch (ParseException e) {
 187					Log.d(LOGTAG, "error trying to parse date" + e.getMessage());
 188				}
 189			}
 190			Conversation conversation = message.getConversation();
 191			conversation.getMessages().add(message);
 192			if (packet.getType() != MessagePacket.TYPE_ERROR) {
 193				databaseBackend.createMessage(message);
 194			}
 195			if (convChangedListener != null) {
 196				convChangedListener.onConversationListChanged();
 197			} else {
 198				UIHelper.updateNotification(getApplicationContext(),
 199						getConversations(), message.getConversation(), notify);
 200			}
 201		}
 202	};
 203	private OnStatusChanged statusListener = new OnStatusChanged() {
 204
 205		@Override
 206		public void onStatusChanged(Account account) {
 207			if (accountChangedListener != null) {
 208				accountChangedListener.onAccountListChangedListener();
 209			}
 210			if (account.getStatus() == Account.STATUS_ONLINE) {
 211				List<Conversation> conversations = getConversations();
 212				for (int i = 0; i < conversations.size(); ++i) {
 213					if (conversations.get(i).getAccount() == account) {
 214						sendUnsendMessages(conversations.get(i));
 215					}
 216				}
 217				scheduleWakeupCall(PING_MAX_INTERVAL, true);
 218			} else if (account.getStatus() == Account.STATUS_OFFLINE) {
 219				if (!account.isOptionSet(Account.OPTION_DISABLED)) {
 220					int timeToReconnect = mRandom.nextInt(50) + 10;
 221					scheduleWakeupCall(timeToReconnect, false);
 222				}
 223
 224			} else if (account.getStatus() == Account.STATUS_REGISTRATION_SUCCESSFULL) {
 225				databaseBackend.updateAccount(account);
 226				reconnectAccount(account, true);
 227			}
 228		}
 229	};
 230
 231	private OnPresencePacketReceived presenceListener = new OnPresencePacketReceived() {
 232
 233		@Override
 234		public void onPresencePacketReceived(Account account,
 235				PresencePacket packet) {
 236			if (packet.hasChild("x","http://jabber.org/protocol/muc#user")) {
 237				Conversation muc = findMuc(
 238						packet.getAttribute("from").split("/")[0], account);
 239				if (muc != null) {
 240					muc.getMucOptions().processPacket(packet);
 241				} else {
 242					Log.d(LOGTAG,account.getJid()+": could not find muc for received muc package "+packet.toString());
 243				}
 244			} else if (packet.hasChild("x","http://jabber.org/protocol/muc")) {
 245				Conversation muc = findMuc(packet.getAttribute("from").split("/")[0], account);
 246				if (muc != null) {
 247					Log.d(LOGTAG,account.getJid()+": reading muc status packet "+packet.toString());
 248					int error = muc.getMucOptions().getError();
 249					muc.getMucOptions().processPacket(packet);
 250					if ((muc.getMucOptions().getError() != error)
 251							&& (convChangedListener != null)) {
 252						Log.d(LOGTAG, "muc error status changed");
 253						convChangedListener.onConversationListChanged();
 254					}
 255				}
 256			} else {
 257				String[] fromParts = packet.getAttribute("from").split("/");
 258				String type = packet.getAttribute("type");
 259				if (fromParts[0].equals(account.getJid())) {
 260					if (fromParts.length==2) {
 261						if (type == null) {
 262							account.updatePresence(fromParts[1],Presences.parseShow(packet.findChild("show")));
 263						} else if (type.equals("unavailable")) {
 264							account.removePresence(fromParts[1]);
 265						}
 266					}
 267						
 268				} else {
 269					Contact contact = findContact(account, fromParts[0]);
 270					if (contact == null) {
 271						// most likely roster not synced
 272						return;
 273					}
 274					if (type == null) {
 275						if (fromParts.length == 2) {
 276							contact.updatePresence(fromParts[1], Presences.parseShow(packet.findChild("show")));
 277							PgpEngine pgp = getPgpEngine();
 278							if (pgp != null) {
 279								Element x = packet.findChild("x","jabber:x:signed");
 280								if (x != null) {
 281									try {
 282										Element status = packet.findChild("status");
 283										String msg;
 284										if (status!=null) {
 285											msg = status.getContent();
 286										} else {
 287											msg = "";
 288										}
 289										contact.setPgpKeyId(pgp.fetchKeyId(msg, x
 290														.getContent()));
 291									} catch (OpenPgpException e) {
 292										Log.d(LOGTAG, "faulty pgp. just ignore");
 293									}
 294								}
 295							}
 296							databaseBackend.updateContact(contact);
 297						} else {
 298							// Log.d(LOGTAG,"presence without resource "+packet.toString());
 299						}
 300					} else if (type.equals("unavailable")) {
 301						if (fromParts.length != 2) {
 302							// Log.d(LOGTAG,"received presence with no resource "+packet.toString());
 303						} else {
 304							contact.removePresence(fromParts[1]);
 305							databaseBackend.updateContact(contact);
 306						}
 307					} else if (type.equals("subscribe")) {
 308						if (contact
 309								.getSubscriptionOption(Contact.Subscription.PREEMPTIVE_GRANT)) {
 310							sendPresenceUpdatesTo(contact);
 311							contact.setSubscriptionOption(Contact.Subscription.FROM);
 312							contact.resetSubscriptionOption(Contact.Subscription.PREEMPTIVE_GRANT);
 313							replaceContactInConversation(contact.getJid(),
 314									contact);
 315							databaseBackend.updateContact(contact);
 316							if ((contact
 317									.getSubscriptionOption(Contact.Subscription.ASKING))
 318									&& (!contact
 319											.getSubscriptionOption(Contact.Subscription.TO))) {
 320								requestPresenceUpdatesFrom(contact);
 321							}
 322						} else {
 323							// TODO: ask user to handle it maybe
 324						}
 325					} else {
 326						//Log.d(LOGTAG, packet.toString());
 327					}
 328					replaceContactInConversation(contact.getJid(), contact);
 329				}
 330			}
 331		}
 332	};
 333
 334	private OnIqPacketReceived unknownIqListener = new OnIqPacketReceived() {
 335
 336		@Override
 337		public void onIqPacketReceived(Account account, IqPacket packet) {
 338			if (packet.hasChild("query")) {
 339				Element query = packet.findChild("query");
 340				String xmlns = query.getAttribute("xmlns");
 341				if ((xmlns != null) && (xmlns.equals("jabber:iq:roster"))) {
 342					processRosterItems(account, query);
 343					mergePhoneContactsWithRoster(null);
 344				}
 345			}
 346		}
 347	};
 348	
 349	private OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
 350		
 351		@Override
 352		public void onJinglePacketReceived(Account account, JinglePacket packet) {
 353			Log.d(LOGTAG,account.getJid()+": jingle packet received"+packet.toString());
 354		}
 355	};
 356
 357	private OpenPgpServiceConnection pgpServiceConnection;
 358	private PgpEngine mPgpEngine = null;
 359	private Intent pingIntent;
 360	private PendingIntent pendingPingIntent = null;
 361	private WakeLock wakeLock;
 362
 363	public PgpEngine getPgpEngine() {
 364		if (pgpServiceConnection.isBound()) {
 365			if (this.mPgpEngine == null) {
 366				this.mPgpEngine = new PgpEngine(new OpenPgpApi(
 367						getApplicationContext(),
 368						pgpServiceConnection.getService()));
 369			}
 370			return mPgpEngine;
 371		} else {
 372			return null;
 373		}
 374
 375	}
 376
 377	protected Conversation findMuc(String name, Account account) {
 378		for (Conversation conversation : this.conversations) {
 379			if (conversation.getContactJid().split("/")[0].equals(name)
 380					&& (conversation.getAccount() == account)) {
 381				return conversation;
 382			}
 383		}
 384		return null;
 385	}
 386
 387	private void processRosterItems(Account account, Element elements) {
 388		String version = elements.getAttribute("ver");
 389		if (version != null) {
 390			account.setRosterVersion(version);
 391			databaseBackend.updateAccount(account);
 392		}
 393		for (Element item : elements.getChildren()) {
 394			if (item.getName().equals("item")) {
 395				String jid = item.getAttribute("jid");
 396				String subscription = item.getAttribute("subscription");
 397				Contact contact = databaseBackend.findContact(account, jid);
 398				if (contact == null) {
 399					if (!subscription.equals("remove")) {
 400						String name = item.getAttribute("name");
 401						if (name == null) {
 402							name = jid.split("@")[0];
 403						}
 404						contact = new Contact(account, name, jid, null);
 405						contact.parseSubscriptionFromElement(item);
 406						databaseBackend.createContact(contact);
 407					}
 408				} else {
 409					if (subscription.equals("remove")) {
 410						databaseBackend.deleteContact(contact);
 411						replaceContactInConversation(contact.getJid(), null);
 412					} else {
 413						contact.parseSubscriptionFromElement(item);
 414						databaseBackend.updateContact(contact);
 415						replaceContactInConversation(contact.getJid(), contact);
 416					}
 417				}
 418			}
 419		}
 420	}
 421
 422	private void replaceContactInConversation(String jid, Contact contact) {
 423		List<Conversation> conversations = getConversations();
 424		for (int i = 0; i < conversations.size(); ++i) {
 425			if ((conversations.get(i).getContactJid().equals(jid))) {
 426				conversations.get(i).setContact(contact);
 427				break;
 428			}
 429		}
 430	}
 431
 432	public class XmppConnectionBinder extends Binder {
 433		public XmppConnectionService getService() {
 434			return XmppConnectionService.this;
 435		}
 436	}
 437
 438	@Override
 439	public int onStartCommand(Intent intent, int flags, int startId) {
 440		this.wakeLock.acquire();
 441		// Log.d(LOGTAG,"calling start service. caller was:"+intent.getAction());
 442		ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
 443				.getSystemService(Context.CONNECTIVITY_SERVICE);
 444		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
 445		boolean isConnected = activeNetwork != null
 446				&& activeNetwork.isConnected();
 447
 448		for (Account account : accounts) {
 449			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
 450				if (!isConnected) {
 451					account.setStatus(Account.STATUS_NO_INTERNET);
 452					if (statusListener != null) {
 453						statusListener.onStatusChanged(account);
 454					}
 455				} else {
 456					if (account.getStatus() == Account.STATUS_NO_INTERNET) {
 457						account.setStatus(Account.STATUS_OFFLINE);
 458						if (statusListener != null) {
 459							statusListener.onStatusChanged(account);
 460						}
 461					}
 462
 463					// TODO 3 remaining cases
 464					if (account.getStatus() == Account.STATUS_ONLINE) {
 465						long lastReceived = account.getXmppConnection().lastPaketReceived;
 466						long lastSent = account.getXmppConnection().lastPingSent;
 467						if (lastSent - lastReceived >= PING_TIMEOUT * 1000) {
 468							Log.d(LOGTAG, account.getJid() + ": ping timeout");
 469							this.reconnectAccount(account, true);
 470						} else if (SystemClock.elapsedRealtime() - lastReceived >= PING_MIN_INTERVAL * 1000) {
 471							account.getXmppConnection().sendPing();
 472							account.getXmppConnection().lastPingSent = SystemClock
 473									.elapsedRealtime();
 474							this.scheduleWakeupCall(2, false);
 475						}
 476					} else if (account.getStatus() == Account.STATUS_OFFLINE) {
 477						if (account.getXmppConnection() == null) {
 478							account.setXmppConnection(this
 479									.createConnection(account));
 480						}
 481						account.getXmppConnection().lastPingSent = SystemClock
 482								.elapsedRealtime();
 483						new Thread(account.getXmppConnection()).start();
 484					} else if ((account.getStatus() == Account.STATUS_CONNECTING)
 485							&& ((SystemClock.elapsedRealtime() - account
 486									.getXmppConnection().lastConnect) / 1000 >= CONNECT_TIMEOUT)) {
 487						Log.d(LOGTAG, account.getJid()
 488								+ ": time out during connect reconnecting");
 489						reconnectAccount(account, true);
 490					} else {
 491						Log.d(LOGTAG,
 492								"seconds since last connect:"
 493										+ ((SystemClock.elapsedRealtime() - account
 494												.getXmppConnection().lastConnect) / 1000));
 495						Log.d(LOGTAG,
 496								account.getJid() + ": status="
 497										+ account.getStatus());
 498						// TODO notify user of ssl cert problem or auth problem
 499						// or what ever
 500					}
 501					// in any case. reschedule wakup call
 502					this.scheduleWakeupCall(PING_MAX_INTERVAL, true);
 503				}
 504				if (accountChangedListener != null) {
 505					accountChangedListener.onAccountListChangedListener();
 506				}
 507			}
 508		}
 509		if (wakeLock.isHeld()) {
 510			wakeLock.release();
 511		}
 512		return START_STICKY;
 513	}
 514
 515	@Override
 516	public void onCreate() {
 517		ExceptionHelper.init(getApplicationContext());
 518		databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
 519		this.accounts = databaseBackend.getAccounts();
 520
 521		this.getConversations();
 522		
 523		getContentResolver().registerContentObserver(
 524				ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
 525		this.pgpServiceConnection = new OpenPgpServiceConnection(
 526				getApplicationContext(), "org.sufficientlysecure.keychain");
 527		this.pgpServiceConnection.bindToService();
 528
 529		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 530		this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
 531				"XmppConnection");
 532	}
 533
 534	@Override
 535	public void onDestroy() {
 536		super.onDestroy();
 537		for (Account account : accounts) {
 538			if (account.getXmppConnection() != null) {
 539				disconnect(account, true);
 540			}
 541		}
 542	}
 543
 544	protected void scheduleWakeupCall(int seconds, boolean ping) {
 545		long timeToWake = SystemClock.elapsedRealtime() + seconds * 1000;
 546		Context context = getApplicationContext();
 547		AlarmManager alarmManager = (AlarmManager) context
 548				.getSystemService(Context.ALARM_SERVICE);
 549
 550		if (ping) {
 551			if (this.pingIntent == null) {
 552				this.pingIntent = new Intent(context, EventReceiver.class);
 553				this.pingIntent.setAction("ping");
 554				this.pingIntent.putExtra("time", timeToWake);
 555				this.pendingPingIntent = PendingIntent.getBroadcast(context, 0,
 556						this.pingIntent, 0);
 557				alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
 558						timeToWake, pendingPingIntent);
 559				// Log.d(LOGTAG,"schedule ping in "+seconds+" seconds");
 560			} else {
 561				long scheduledTime = this.pingIntent.getLongExtra("time", 0);
 562				if (scheduledTime < SystemClock.elapsedRealtime()
 563						|| (scheduledTime > timeToWake)) {
 564					this.pingIntent.putExtra("time", timeToWake);
 565					alarmManager.cancel(this.pendingPingIntent);
 566					this.pendingPingIntent = PendingIntent.getBroadcast(
 567							context, 0, this.pingIntent, 0);
 568					alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
 569							timeToWake, pendingPingIntent);
 570					// Log.d(LOGTAG,"reschedule old ping to ping in "+seconds+" seconds");
 571				}
 572			}
 573		} else {
 574			Intent intent = new Intent(context, EventReceiver.class);
 575			intent.setAction("ping_check");
 576			PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0,
 577					intent, 0);
 578			alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake,
 579					alarmIntent);
 580		}
 581
 582	}
 583
 584	public XmppConnection createConnection(Account account) {
 585		SharedPreferences sharedPref = PreferenceManager
 586				.getDefaultSharedPreferences(getApplicationContext());
 587		account.setResource(sharedPref.getString("resource", "mobile").toLowerCase(Locale.getDefault()));
 588		XmppConnection connection = new XmppConnection(account, this.wakeLock);
 589		connection.setOnMessagePacketReceivedListener(this.messageListener);
 590		connection.setOnStatusChangedListener(this.statusListener);
 591		connection.setOnPresencePacketReceivedListener(this.presenceListener);
 592		connection
 593				.setOnUnregisteredIqPacketReceivedListener(this.unknownIqListener);
 594		connection.setOnJinglePacketReceivedListener(this.jingleListener);
 595		connection
 596				.setOnTLSExceptionReceivedListener(new OnTLSExceptionReceived() {
 597
 598					@Override
 599					public void onTLSExceptionReceived(String fingerprint,
 600							Account account) {
 601						Log.d(LOGTAG, "tls exception arrived in service");
 602						if (tlsException != null) {
 603							tlsException.onTLSExceptionReceived(fingerprint,
 604									account);
 605						}
 606					}
 607				});
 608		connection.setOnBindListener(new OnBindListener() {
 609
 610			@Override
 611			public void onBind(Account account) {
 612				databaseBackend.clearPresences(account);
 613				account.clearPresences(); // self presences
 614				if (account.getXmppConnection().hasFeatureRosterManagment()) {
 615					updateRoster(account, null);
 616				}
 617				connectMultiModeConversations(account);
 618				if (convChangedListener != null) {
 619					convChangedListener.onConversationListChanged();
 620				}
 621			}
 622		});
 623		return connection;
 624	}
 625
 626	synchronized public void sendMessage(Message message, String presence) {
 627		Account account = message.getConversation().getAccount();
 628		Conversation conv = message.getConversation();
 629		boolean saveInDb = false;
 630		boolean addToConversation = false;
 631		if (account.getStatus() == Account.STATUS_ONLINE) {
 632			MessagePacket packet;
 633			if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 634				if (!conv.hasValidOtrSession()) {
 635					// starting otr session. messages will be send later
 636					conv.startOtrSession(getApplicationContext(), presence,true);
 637				} else if (conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
 638					// otr session aleary exists, creating message packet
 639					// accordingly
 640					packet = prepareMessagePacket(account, message,
 641							conv.getOtrSession());
 642					account.getXmppConnection().sendMessagePacket(packet);
 643					message.setStatus(Message.STATUS_SEND);
 644				}
 645				saveInDb = true;
 646				addToConversation = true;
 647			} else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
 648				message.getConversation().endOtrIfNeeded();
 649				long keyId = message.getConversation().getContact()
 650						.getPgpKeyId();
 651				packet = new MessagePacket();
 652				packet.setType(MessagePacket.TYPE_CHAT);
 653				packet.setFrom(message.getConversation().getAccount()
 654						.getFullJid());
 655				packet.setTo(message.getCounterpart());
 656				packet.setBody("This is an XEP-0027 encryted message");
 657				packet.addChild("x","jabber:x:encrypted").setContent(this.getPgpEngine().encrypt(keyId,
 658						message.getBody()));
 659				account.getXmppConnection().sendMessagePacket(packet);
 660				message.setStatus(Message.STATUS_SEND);
 661				message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 662				saveInDb = true;
 663				addToConversation = true;
 664			} else {
 665				message.getConversation().endOtrIfNeeded();
 666				// don't encrypt
 667				if (message.getConversation().getMode() == Conversation.MODE_SINGLE) {
 668					message.setStatus(Message.STATUS_SEND);
 669					saveInDb = true;
 670					addToConversation = true;
 671				}
 672
 673				packet = prepareMessagePacket(account, message, null);
 674				account.getXmppConnection().sendMessagePacket(packet);
 675			}
 676		} else {
 677			// account is offline
 678			saveInDb = true;
 679			addToConversation = true;
 680
 681		}
 682		if (saveInDb) {
 683			databaseBackend.createMessage(message);
 684		}
 685		if (addToConversation) {
 686			conv.getMessages().add(message);
 687			if (convChangedListener != null) {
 688				convChangedListener.onConversationListChanged();
 689			}
 690		}
 691
 692	}
 693
 694	private void sendUnsendMessages(Conversation conversation) {
 695		for (int i = 0; i < conversation.getMessages().size(); ++i) {
 696			if ((conversation.getMessages().get(i).getStatus() == Message.STATUS_UNSEND)&&(conversation.getMessages().get(i).getEncryption() == Message.ENCRYPTION_NONE)) {
 697				Message message = conversation.getMessages().get(i);
 698				MessagePacket packet = prepareMessagePacket(
 699						conversation.getAccount(), message, null);
 700				conversation.getAccount().getXmppConnection()
 701						.sendMessagePacket(packet);
 702				message.setStatus(Message.STATUS_SEND);
 703				if (conversation.getMode() == Conversation.MODE_SINGLE) {
 704					databaseBackend.updateMessage(message);
 705				} else {
 706					databaseBackend.deleteMessage(message);
 707					conversation.getMessages().remove(i);
 708					i--;
 709				}
 710			}
 711		}
 712	}
 713
 714	public MessagePacket prepareMessagePacket(Account account, Message message,
 715			Session otrSession) {
 716		MessagePacket packet = new MessagePacket();
 717		if (message.getConversation().getMode() == Conversation.MODE_SINGLE) {
 718			packet.setType(MessagePacket.TYPE_CHAT);
 719			if (otrSession != null) {
 720				try {
 721					packet.setBody(otrSession.transformSending(message
 722							.getBody()));
 723				} catch (OtrException e) {
 724					Log.d(LOGTAG,
 725							account.getJid()
 726									+ ": could not encrypt message to "
 727									+ message.getCounterpart());
 728				}
 729				packet.addChild("private","urn:xmpp:carbons:2");
 730				packet.addChild("no-copy","urn:xmpp:hints");
 731				packet.setTo(otrSession.getSessionID().getAccountID() + "/"
 732						+ otrSession.getSessionID().getUserID());
 733				packet.setFrom(account.getFullJid());
 734			} else {
 735				packet.setBody(message.getBody());
 736				packet.setTo(message.getCounterpart());
 737				packet.setFrom(account.getJid());
 738			}
 739		} else if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
 740			packet.setType(MessagePacket.TYPE_GROUPCHAT);
 741			packet.setBody(message.getBody());
 742			packet.setTo(message.getCounterpart().split("/")[0]);
 743			packet.setFrom(account.getJid());
 744		}
 745		return packet;
 746	}
 747
 748	private void getRoster(Account account,
 749			final OnRosterFetchedListener listener) {
 750		List<Contact> contacts = databaseBackend.getContactsByAccount(account);
 751		for (int i = 0; i < contacts.size(); ++i) {
 752			contacts.get(i).setAccount(account);
 753		}
 754		if (listener != null) {
 755			listener.onRosterFetched(contacts);
 756		}
 757	}
 758
 759	public List<Contact> getRoster(Account account) {
 760		List<Contact> contacts = databaseBackend.getContactsByAccount(account);
 761		for (int i = 0; i < contacts.size(); ++i) {
 762			contacts.get(i).setAccount(account);
 763		}
 764		return contacts;
 765	}
 766
 767	public void updateRoster(final Account account,
 768			final OnRosterFetchedListener listener) {
 769		IqPacket iqPacket = new IqPacket(IqPacket.TYPE_GET);
 770		if (!"".equals(account.getRosterVersion())) {
 771			Log.d(LOGTAG, account.getJid() + ": fetching roster version "
 772					+ account.getRosterVersion());
 773		} else {
 774			Log.d(LOGTAG, account.getJid() + ": fetching roster");
 775		}
 776		iqPacket.query("jabber:iq:roster").setAttribute("ver", account.getRosterVersion());
 777		account.getXmppConnection().sendIqPacket(iqPacket,
 778				new OnIqPacketReceived() {
 779
 780					@Override
 781					public void onIqPacketReceived(final Account account,
 782							IqPacket packet) {
 783						Element roster = packet.findChild("query");
 784						if (roster != null) {
 785							Log.d(LOGTAG, account.getJid()
 786									+ ": processing roster");
 787							processRosterItems(account, roster);
 788							StringBuilder mWhere = new StringBuilder();
 789							mWhere.append("jid NOT IN(");
 790							List<Element> items = roster.getChildren();
 791							for (int i = 0; i < items.size(); ++i) {
 792								mWhere.append(DatabaseUtils
 793										.sqlEscapeString(items.get(i)
 794												.getAttribute("jid")));
 795								if (i != items.size() - 1) {
 796									mWhere.append(",");
 797								}
 798							}
 799							mWhere.append(") and accountUuid = \"");
 800							mWhere.append(account.getUuid());
 801							mWhere.append("\"");
 802							List<Contact> contactsToDelete = databaseBackend
 803									.getContacts(mWhere.toString());
 804							for (Contact contact : contactsToDelete) {
 805								databaseBackend.deleteContact(contact);
 806								replaceContactInConversation(contact.getJid(),
 807										null);
 808							}
 809
 810						} else {
 811							Log.d(LOGTAG, account.getJid()
 812									+ ": empty roster returend");
 813						}
 814						mergePhoneContactsWithRoster(new OnPhoneContactsMerged() {
 815
 816							@Override
 817							public void phoneContactsMerged() {
 818								if (listener != null) {
 819									getRoster(account, listener);
 820								}
 821							}
 822						});
 823					}
 824				});
 825	}
 826
 827	public void mergePhoneContactsWithRoster(
 828			final OnPhoneContactsMerged listener) {
 829		PhoneHelper.loadPhoneContacts(getApplicationContext(),
 830				new OnPhoneContactsLoadedListener() {
 831					@Override
 832					public void onPhoneContactsLoaded(
 833							Hashtable<String, Bundle> phoneContacts) {
 834						List<Contact> contacts = databaseBackend
 835								.getContactsByAccount(null);
 836						for (int i = 0; i < contacts.size(); ++i) {
 837							Contact contact = contacts.get(i);
 838							if (phoneContacts.containsKey(contact.getJid())) {
 839								Bundle phoneContact = phoneContacts.get(contact
 840										.getJid());
 841								String systemAccount = phoneContact
 842										.getInt("phoneid")
 843										+ "#"
 844										+ phoneContact.getString("lookup");
 845								contact.setSystemAccount(systemAccount);
 846								contact.setPhotoUri(phoneContact
 847										.getString("photouri"));
 848								contact.setDisplayName(phoneContact
 849										.getString("displayname"));
 850								databaseBackend.updateContact(contact);
 851								replaceContactInConversation(contact.getJid(),
 852										contact);
 853							} else {
 854								if ((contact.getSystemAccount() != null)
 855										|| (contact.getProfilePhoto() != null)) {
 856									contact.setSystemAccount(null);
 857									contact.setPhotoUri(null);
 858									databaseBackend.updateContact(contact);
 859									replaceContactInConversation(
 860											contact.getJid(), contact);
 861								}
 862							}
 863						}
 864						if (listener != null) {
 865							listener.phoneContactsMerged();
 866						}
 867					}
 868				});
 869	}
 870
 871	public List<Conversation> getConversations() {
 872		if (this.conversations == null) {
 873			Hashtable<String, Account> accountLookupTable = new Hashtable<String, Account>();
 874			for (Account account : this.accounts) {
 875				accountLookupTable.put(account.getUuid(), account);
 876			}
 877			this.conversations = databaseBackend
 878					.getConversations(Conversation.STATUS_AVAILABLE);
 879			for (Conversation conv : this.conversations) {
 880				Account account = accountLookupTable.get(conv.getAccountUuid());
 881				conv.setAccount(account);
 882				conv.setContact(findContact(account, conv.getContactJid()));
 883				conv.setMessages(databaseBackend.getMessages(conv, 50));
 884			}
 885		}
 886		Collections.sort(this.conversations, new Comparator<Conversation>() {
 887			@Override
 888			public int compare(Conversation lhs, Conversation rhs) {
 889				return (int) (rhs.getLatestMessage().getTimeSent() - lhs
 890						.getLatestMessage().getTimeSent());
 891			}
 892		});
 893		return this.conversations;
 894	}
 895
 896	public List<Account> getAccounts() {
 897		return this.accounts;
 898	}
 899
 900	public Contact findContact(Account account, String jid) {
 901		Contact contact = databaseBackend.findContact(account, jid);
 902		if (contact != null) {
 903			contact.setAccount(account);
 904		}
 905		return contact;
 906	}
 907
 908	public Conversation findOrCreateConversation(Account account, String jid,
 909			boolean muc) {
 910		for (Conversation conv : this.getConversations()) {
 911			if ((conv.getAccount().equals(account))
 912					&& (conv.getContactJid().split("/")[0].equals(jid))) {
 913				return conv;
 914			}
 915		}
 916		Conversation conversation = databaseBackend.findConversation(account,
 917				jid);
 918		if (conversation != null) {
 919			conversation.setStatus(Conversation.STATUS_AVAILABLE);
 920			conversation.setAccount(account);
 921			if (muc) {
 922				conversation.setMode(Conversation.MODE_MULTI);
 923			} else {
 924				conversation.setMode(Conversation.MODE_SINGLE);
 925			}
 926			conversation.setMessages(databaseBackend.getMessages(conversation,
 927					50));
 928			this.databaseBackend.updateConversation(conversation);
 929			conversation.setContact(findContact(account,
 930					conversation.getContactJid()));
 931		} else {
 932			String conversationName;
 933			Contact contact = findContact(account, jid);
 934			if (contact != null) {
 935				conversationName = contact.getDisplayName();
 936			} else {
 937				conversationName = jid.split("@")[0];
 938			}
 939			if (muc) {
 940				conversation = new Conversation(conversationName, account, jid,
 941						Conversation.MODE_MULTI);
 942			} else {
 943				conversation = new Conversation(conversationName, account, jid,
 944						Conversation.MODE_SINGLE);
 945			}
 946			conversation.setContact(contact);
 947			this.databaseBackend.createConversation(conversation);
 948		}
 949		this.conversations.add(conversation);
 950		if ((account.getStatus() == Account.STATUS_ONLINE)&&(conversation.getMode() == Conversation.MODE_MULTI)) {
 951			joinMuc(conversation);
 952		}
 953		if (this.convChangedListener != null) {
 954			this.convChangedListener.onConversationListChanged();
 955		}
 956		return conversation;
 957	}
 958
 959	public void archiveConversation(Conversation conversation) {
 960		if (conversation.getMode() == Conversation.MODE_MULTI) {
 961			leaveMuc(conversation);
 962		} else {
 963			conversation.endOtrIfNeeded();
 964		}
 965		this.databaseBackend.updateConversation(conversation);
 966		this.conversations.remove(conversation);
 967		if (this.convChangedListener != null) {
 968			this.convChangedListener.onConversationListChanged();
 969		}
 970	}
 971
 972	public int getConversationCount() {
 973		return this.databaseBackend.getConversationCount();
 974	}
 975
 976	public void createAccount(Account account) {
 977		databaseBackend.createAccount(account);
 978		this.accounts.add(account);
 979		this.reconnectAccount(account, false);
 980		if (accountChangedListener != null)
 981			accountChangedListener.onAccountListChangedListener();
 982	}
 983
 984	public void deleteContact(Contact contact) {
 985		IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
 986		Element query = iq.query("jabber:iq:roster");
 987		query.addChild("item").setAttribute("jid", contact.getJid()).setAttribute("subscription", "remove");
 988		contact.getAccount().getXmppConnection().sendIqPacket(iq, null);
 989		replaceContactInConversation(contact.getJid(), null);
 990		databaseBackend.deleteContact(contact);
 991	}
 992
 993	public void updateAccount(Account account) {
 994		databaseBackend.updateAccount(account);
 995		reconnectAccount(account, false);
 996		if (accountChangedListener != null)
 997			accountChangedListener.onAccountListChangedListener();
 998	}
 999
1000	public void deleteAccount(Account account) {
1001		if (account.getXmppConnection() != null) {
1002			this.disconnect(account, true);
1003		}
1004		databaseBackend.deleteAccount(account);
1005		this.accounts.remove(account);
1006		if (accountChangedListener != null)
1007			accountChangedListener.onAccountListChangedListener();
1008	}
1009
1010	public void setOnConversationListChangedListener(
1011			OnConversationListChangedListener listener) {
1012		this.convChangedListener = listener;
1013		this.convChangedListenerCount++;
1014		Log.d(LOGTAG,"registered on conv changed in backend ("+convChangedListenerCount+")");
1015	}
1016
1017	public void removeOnConversationListChangedListener() {
1018		this.convChangedListenerCount--;
1019		Log.d(LOGTAG,"someone on conv changed listener removed listener ("+convChangedListenerCount+")");
1020		if (this.convChangedListenerCount==0) {
1021			this.convChangedListener = null;
1022		}
1023	}
1024
1025	public void setOnAccountListChangedListener(
1026			OnAccountListChangedListener listener) {
1027		this.accountChangedListener = listener;
1028	}
1029
1030	public void removeOnAccountListChangedListener() {
1031		this.accountChangedListener = null;
1032	}
1033
1034	public void connectMultiModeConversations(Account account) {
1035		List<Conversation> conversations = getConversations();
1036		for (int i = 0; i < conversations.size(); i++) {
1037			Conversation conversation = conversations.get(i);
1038			if ((conversation.getMode() == Conversation.MODE_MULTI)
1039					&& (conversation.getAccount() == account)) {
1040				joinMuc(conversation);
1041			}
1042		}
1043	}
1044
1045	public void joinMuc(Conversation conversation) {
1046		String[] mucParts = conversation.getContactJid().split("/");
1047		String muc;
1048		String nick;
1049		if (mucParts.length == 2) {
1050			muc = mucParts[0];
1051			nick = mucParts[1];
1052		} else {
1053			muc = mucParts[0];
1054			nick = conversation.getAccount().getUsername();
1055		}
1056		PresencePacket packet = new PresencePacket();
1057		packet.setAttribute("to", muc + "/" + nick);
1058		Element x = new Element("x");
1059		x.setAttribute("xmlns", "http://jabber.org/protocol/muc");
1060		if (conversation.getMessages().size() != 0) {
1061			long lastMsgTime = conversation.getLatestMessage().getTimeSent();
1062			long diff = (System.currentTimeMillis() - lastMsgTime) / 1000 - 1;
1063			x.addChild("history").setAttribute("seconds", diff + "");
1064		}
1065		packet.addChild(x);
1066		Log.d(LOGTAG,conversation.getAccount().getJid()+": joining muc "+packet.toString());
1067		conversation.getAccount().getXmppConnection()
1068				.sendPresencePacket(packet);
1069	}
1070
1071	private OnRenameListener renameListener = null;
1072
1073	public void setOnRenameListener(OnRenameListener listener) {
1074		this.renameListener = listener;
1075	}
1076
1077	public void renameInMuc(final Conversation conversation, final String nick) {
1078		final MucOptions options = conversation.getMucOptions();
1079		if (options.online()) {
1080			options.setOnRenameListener(new OnRenameListener() {
1081
1082				@Override
1083				public void onRename(boolean success) {
1084					if (renameListener != null) {
1085						renameListener.onRename(success);
1086					}
1087					if (success) {
1088						databaseBackend.updateConversation(conversation);
1089					}
1090				}
1091			});
1092			options.flagAboutToRename();
1093			PresencePacket packet = new PresencePacket();
1094			packet.setAttribute("to",
1095					conversation.getContactJid().split("/")[0] + "/" + nick);
1096			packet.setAttribute("from", conversation.getAccount().getFullJid());
1097
1098			conversation.getAccount().getXmppConnection()
1099					.sendPresencePacket(packet, null);
1100		} else {
1101			String jid = conversation.getContactJid().split("/")[0] + "/"
1102					+ nick;
1103			conversation.setContactJid(jid);
1104			databaseBackend.updateConversation(conversation);
1105			if (conversation.getAccount().getStatus() == Account.STATUS_ONLINE) {
1106				joinMuc(conversation);
1107			}
1108		}
1109	}
1110
1111	public void leaveMuc(Conversation conversation) {
1112		PresencePacket packet = new PresencePacket();
1113		packet.setAttribute("to", conversation.getContactJid().split("/")[0] + "/" + conversation.getMucOptions().getNick());
1114		packet.setAttribute("from", conversation.getAccount().getFullJid());
1115		packet.setAttribute("type", "unavailable");
1116		Log.d(LOGTAG,"send leaving muc " + packet);
1117		conversation.getAccount().getXmppConnection()
1118				.sendPresencePacket(packet);
1119		conversation.getMucOptions().setOffline();
1120	}
1121
1122	public void disconnect(Account account, boolean force) {
1123		if ((account.getStatus() == Account.STATUS_ONLINE)
1124				|| (account.getStatus() == Account.STATUS_DISABLED)) {
1125			if (!force) {
1126				List<Conversation> conversations = getConversations();
1127				for (int i = 0; i < conversations.size(); i++) {
1128					Conversation conversation = conversations.get(i);
1129					if (conversation.getAccount() == account) {
1130						if (conversation.getMode() == Conversation.MODE_MULTI) {
1131							leaveMuc(conversation);
1132						} else {
1133							conversation.endOtrIfNeeded();
1134						}
1135					}
1136				}
1137			}
1138			account.getXmppConnection().disconnect(force);
1139		}
1140	}
1141
1142	@Override
1143	public IBinder onBind(Intent intent) {
1144		return mBinder;
1145	}
1146
1147	public void updateContact(Contact contact) {
1148		databaseBackend.updateContact(contact);
1149		replaceContactInConversation(contact.getJid(), contact);
1150	}
1151
1152	public void updateMessage(Message message) {
1153		databaseBackend.updateMessage(message);
1154	}
1155
1156	public void createContact(Contact contact) {
1157		SharedPreferences sharedPref = PreferenceManager
1158				.getDefaultSharedPreferences(getApplicationContext());
1159		boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1160		if (autoGrant) {
1161			contact.setSubscriptionOption(Contact.Subscription.PREEMPTIVE_GRANT);
1162			contact.setSubscriptionOption(Contact.Subscription.ASKING);
1163		}
1164		databaseBackend.createContact(contact);
1165		IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
1166		Element query = new Element("query");
1167		query.setAttribute("xmlns", "jabber:iq:roster");
1168		Element item = new Element("item");
1169		item.setAttribute("jid", contact.getJid());
1170		item.setAttribute("name", contact.getJid());
1171		query.addChild(item);
1172		iq.addChild(query);
1173		Account account = contact.getAccount();
1174		account.getXmppConnection().sendIqPacket(iq, null);
1175		if (autoGrant) {
1176			requestPresenceUpdatesFrom(contact);
1177		}
1178		replaceContactInConversation(contact.getJid(), contact);
1179	}
1180
1181	public void requestPresenceUpdatesFrom(Contact contact) {
1182		// Requesting a Subscription type=subscribe
1183		PresencePacket packet = new PresencePacket();
1184		packet.setAttribute("type", "subscribe");
1185		packet.setAttribute("to", contact.getJid());
1186		packet.setAttribute("from", contact.getAccount().getJid());
1187		Log.d(LOGTAG, packet.toString());
1188		contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1189	}
1190
1191	public void stopPresenceUpdatesFrom(Contact contact) {
1192		// Unsubscribing type='unsubscribe'
1193		PresencePacket packet = new PresencePacket();
1194		packet.setAttribute("type", "unsubscribe");
1195		packet.setAttribute("to", contact.getJid());
1196		packet.setAttribute("from", contact.getAccount().getJid());
1197		Log.d(LOGTAG, packet.toString());
1198		contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1199	}
1200
1201	public void stopPresenceUpdatesTo(Contact contact) {
1202		// Canceling a Subscription type=unsubscribed
1203		PresencePacket packet = new PresencePacket();
1204		packet.setAttribute("type", "unsubscribed");
1205		packet.setAttribute("to", contact.getJid());
1206		packet.setAttribute("from", contact.getAccount().getJid());
1207		Log.d(LOGTAG, packet.toString());
1208		contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1209	}
1210
1211	public void sendPresenceUpdatesTo(Contact contact) {
1212		// type='subscribed'
1213		PresencePacket packet = new PresencePacket();
1214		packet.setAttribute("type", "subscribed");
1215		packet.setAttribute("to", contact.getJid());
1216		packet.setAttribute("from", contact.getAccount().getJid());
1217		Log.d(LOGTAG, packet.toString());
1218		contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1219	}
1220
1221	public void sendPgpPresence(Account account, String signature) {
1222		PresencePacket packet = new PresencePacket();
1223		packet.setAttribute("from", account.getFullJid());
1224		Element status = new Element("status");
1225		status.setContent("online");
1226		packet.addChild(status);
1227		Element x = new Element("x");
1228		x.setAttribute("xmlns", "jabber:x:signed");
1229		x.setContent(signature);
1230		packet.addChild(x);
1231		account.getXmppConnection().sendPresencePacket(packet);
1232	}
1233
1234	public void generatePgpAnnouncement(Account account)
1235			throws PgpEngine.UserInputRequiredException {
1236		if (account.getStatus() == Account.STATUS_ONLINE) {
1237			String signature = getPgpEngine().generateSignature("online");
1238			account.setKey("pgp_signature", signature);
1239			databaseBackend.updateAccount(account);
1240			sendPgpPresence(account, signature);
1241		}
1242	}
1243
1244	public void updateConversation(Conversation conversation) {
1245		this.databaseBackend.updateConversation(conversation);
1246	}
1247
1248	public Contact findContact(String uuid) {
1249		Contact contact = this.databaseBackend.getContact(uuid);
1250		for (Account account : getAccounts()) {
1251			if (contact.getAccountUuid().equals(account.getUuid())) {
1252				contact.setAccount(account);
1253			}
1254		}
1255		return contact;
1256	}
1257
1258	public void removeOnTLSExceptionReceivedListener() {
1259		this.tlsException = null;
1260	}
1261
1262	// TODO dont let thread sleep but schedule wake up
1263	public void reconnectAccount(final Account account, final boolean force) {
1264		new Thread(new Runnable() {
1265
1266			@Override
1267			public void run() {
1268				if (account.getXmppConnection() != null) {
1269					disconnect(account, force);
1270				}
1271				if (!account.isOptionSet(Account.OPTION_DISABLED)) {
1272					if (account.getXmppConnection() == null) {
1273						account.setXmppConnection(createConnection(account));
1274					}
1275					Thread thread = new Thread(account.getXmppConnection());
1276					thread.start();
1277					scheduleWakeupCall((int) (CONNECT_TIMEOUT * 1.2), false);
1278				}
1279			}
1280		}).start();
1281	}
1282
1283	public void updateConversationInGui() {
1284		if (convChangedListener != null) {
1285			convChangedListener.onConversationListChanged();
1286		}
1287	}
1288
1289	public void sendConversationSubject(Conversation conversation,
1290			String subject) {
1291		MessagePacket packet = new MessagePacket();
1292		packet.setType(MessagePacket.TYPE_GROUPCHAT);
1293		packet.setTo(conversation.getContactJid().split("/")[0]);
1294		Element subjectChild = new Element("subject");
1295		subjectChild.setContent(subject);
1296		packet.addChild(subjectChild);
1297		packet.setFrom(conversation.getAccount().getJid());
1298		Account account = conversation.getAccount();
1299		if (account.getStatus() == Account.STATUS_ONLINE) {
1300			account.getXmppConnection().sendMessagePacket(packet);
1301		}
1302	}
1303
1304	public void inviteToConference(Conversation conversation,
1305			List<Contact> contacts) {
1306		for (Contact contact : contacts) {
1307			MessagePacket packet = new MessagePacket();
1308			packet.setTo(conversation.getContactJid().split("/")[0]);
1309			packet.setFrom(conversation.getAccount().getFullJid());
1310			Element x = new Element("x");
1311			x.setAttribute("xmlns", "http://jabber.org/protocol/muc#user");
1312			Element invite = new Element("invite");
1313			invite.setAttribute("to", contact.getJid());
1314			x.addChild(invite);
1315			packet.addChild(x);
1316			Log.d(LOGTAG, packet.toString());
1317			conversation.getAccount().getXmppConnection()
1318					.sendMessagePacket(packet);
1319		}
1320
1321	}
1322}