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