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(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
 365	public PgpEngine getPgpEngine() {
 366		if (pgpServiceConnection.isBound()) {
 367			if (this.mPgpEngine == null) {
 368				this.mPgpEngine = new PgpEngine(new OpenPgpApi(
 369						getApplicationContext(),
 370						pgpServiceConnection.getService()));
 371			}
 372			return mPgpEngine;
 373		} else {
 374			return null;
 375		}
 376
 377	}
 378
 379	protected Conversation findMuc(String name, Account account) {
 380		for (Conversation conversation : this.conversations) {
 381			if (conversation.getContactJid().split("/")[0].equals(name)
 382					&& (conversation.getAccount() == account)) {
 383				return conversation;
 384			}
 385		}
 386		return null;
 387	}
 388
 389	private void processRosterItems(Account account, Element elements) {
 390		String version = elements.getAttribute("ver");
 391		if (version != null) {
 392			account.setRosterVersion(version);
 393			databaseBackend.updateAccount(account);
 394		}
 395		for (Element item : elements.getChildren()) {
 396			if (item.getName().equals("item")) {
 397				String jid = item.getAttribute("jid");
 398				String subscription = item.getAttribute("subscription");
 399				Contact contact = databaseBackend.findContact(account, jid);
 400				if (contact == null) {
 401					if (!subscription.equals("remove")) {
 402						String name = item.getAttribute("name");
 403						if (name == null) {
 404							name = jid.split("@")[0];
 405						}
 406						contact = new Contact(account, name, jid, null);
 407						contact.parseSubscriptionFromElement(item);
 408						databaseBackend.createContact(contact);
 409					}
 410				} else {
 411					if (subscription.equals("remove")) {
 412						databaseBackend.deleteContact(contact);
 413						replaceContactInConversation(contact.getJid(), null);
 414					} else {
 415						contact.parseSubscriptionFromElement(item);
 416						databaseBackend.updateContact(contact);
 417						replaceContactInConversation(contact.getJid(), contact);
 418					}
 419				}
 420			}
 421		}
 422	}
 423
 424	private void replaceContactInConversation(String jid, Contact contact) {
 425		List<Conversation> conversations = getConversations();
 426		for (int i = 0; i < conversations.size(); ++i) {
 427			if ((conversations.get(i).getContactJid().equals(jid))) {
 428				conversations.get(i).setContact(contact);
 429				break;
 430			}
 431		}
 432	}
 433
 434	public class XmppConnectionBinder extends Binder {
 435		public XmppConnectionService getService() {
 436			return XmppConnectionService.this;
 437		}
 438	}
 439
 440	@Override
 441	public int onStartCommand(Intent intent, int flags, int startId) {
 442		this.wakeLock.acquire();
 443		// Log.d(LOGTAG,"calling start service. caller was:"+intent.getAction());
 444		ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
 445				.getSystemService(Context.CONNECTIVITY_SERVICE);
 446		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
 447		boolean isConnected = activeNetwork != null
 448				&& activeNetwork.isConnected();
 449
 450		for (Account account : accounts) {
 451			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
 452				if (!isConnected) {
 453					account.setStatus(Account.STATUS_NO_INTERNET);
 454					if (statusListener != null) {
 455						statusListener.onStatusChanged(account);
 456					}
 457				} else {
 458					if (account.getStatus() == Account.STATUS_NO_INTERNET) {
 459						account.setStatus(Account.STATUS_OFFLINE);
 460						if (statusListener != null) {
 461							statusListener.onStatusChanged(account);
 462						}
 463					}
 464
 465					// TODO 3 remaining cases
 466					if (account.getStatus() == Account.STATUS_ONLINE) {
 467						long lastReceived = account.getXmppConnection().lastPaketReceived;
 468						long lastSent = account.getXmppConnection().lastPingSent;
 469						if (lastSent - lastReceived >= PING_TIMEOUT * 1000) {
 470							Log.d(LOGTAG, account.getJid() + ": ping timeout");
 471							this.reconnectAccount(account, true);
 472						} else if (SystemClock.elapsedRealtime() - lastReceived >= PING_MIN_INTERVAL * 1000) {
 473							account.getXmppConnection().sendPing();
 474							account.getXmppConnection().lastPingSent = SystemClock
 475									.elapsedRealtime();
 476							this.scheduleWakeupCall(2, false);
 477						}
 478					} else if (account.getStatus() == Account.STATUS_OFFLINE) {
 479						if (account.getXmppConnection() == null) {
 480							account.setXmppConnection(this
 481									.createConnection(account));
 482						}
 483						account.getXmppConnection().lastPingSent = SystemClock
 484								.elapsedRealtime();
 485						new Thread(account.getXmppConnection()).start();
 486					} else if ((account.getStatus() == Account.STATUS_CONNECTING)
 487							&& ((SystemClock.elapsedRealtime() - account
 488									.getXmppConnection().lastConnect) / 1000 >= CONNECT_TIMEOUT)) {
 489						Log.d(LOGTAG, account.getJid()
 490								+ ": time out during connect reconnecting");
 491						reconnectAccount(account, true);
 492					} else {
 493						Log.d(LOGTAG,
 494								"seconds since last connect:"
 495										+ ((SystemClock.elapsedRealtime() - account
 496												.getXmppConnection().lastConnect) / 1000));
 497						Log.d(LOGTAG,
 498								account.getJid() + ": status="
 499										+ account.getStatus());
 500						// TODO notify user of ssl cert problem or auth problem
 501						// or what ever
 502					}
 503					// in any case. reschedule wakup call
 504					this.scheduleWakeupCall(PING_MAX_INTERVAL, true);
 505				}
 506				if (accountChangedListener != null) {
 507					accountChangedListener.onAccountListChangedListener();
 508				}
 509			}
 510		}
 511		if (wakeLock.isHeld()) {
 512			wakeLock.release();
 513		}
 514		return START_STICKY;
 515	}
 516
 517	@Override
 518	public void onCreate() {
 519		ExceptionHelper.init(getApplicationContext());
 520		databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
 521		this.accounts = databaseBackend.getAccounts();
 522
 523		this.getConversations();
 524		
 525		getContentResolver().registerContentObserver(
 526				ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
 527		this.pgpServiceConnection = new OpenPgpServiceConnection(
 528				getApplicationContext(), "org.sufficientlysecure.keychain");
 529		this.pgpServiceConnection.bindToService();
 530
 531		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 532		this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
 533				"XmppConnection");
 534	}
 535
 536	@Override
 537	public void onDestroy() {
 538		super.onDestroy();
 539		for (Account account : accounts) {
 540			if (account.getXmppConnection() != null) {
 541				disconnect(account, true);
 542			}
 543		}
 544	}
 545
 546	protected void scheduleWakeupCall(int seconds, boolean ping) {
 547		long timeToWake = SystemClock.elapsedRealtime() + seconds * 1000;
 548		Context context = getApplicationContext();
 549		AlarmManager alarmManager = (AlarmManager) context
 550				.getSystemService(Context.ALARM_SERVICE);
 551
 552		if (ping) {
 553			if (this.pingIntent == null) {
 554				this.pingIntent = new Intent(context, EventReceiver.class);
 555				this.pingIntent.setAction("ping");
 556				this.pingIntent.putExtra("time", timeToWake);
 557				this.pendingPingIntent = PendingIntent.getBroadcast(context, 0,
 558						this.pingIntent, 0);
 559				alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
 560						timeToWake, pendingPingIntent);
 561				// Log.d(LOGTAG,"schedule ping in "+seconds+" seconds");
 562			} else {
 563				long scheduledTime = this.pingIntent.getLongExtra("time", 0);
 564				if (scheduledTime < SystemClock.elapsedRealtime()
 565						|| (scheduledTime > timeToWake)) {
 566					this.pingIntent.putExtra("time", timeToWake);
 567					alarmManager.cancel(this.pendingPingIntent);
 568					this.pendingPingIntent = PendingIntent.getBroadcast(
 569							context, 0, this.pingIntent, 0);
 570					alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
 571							timeToWake, pendingPingIntent);
 572					// Log.d(LOGTAG,"reschedule old ping to ping in "+seconds+" seconds");
 573				}
 574			}
 575		} else {
 576			Intent intent = new Intent(context, EventReceiver.class);
 577			intent.setAction("ping_check");
 578			PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0,
 579					intent, 0);
 580			alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake,
 581					alarmIntent);
 582		}
 583
 584	}
 585
 586	public XmppConnection createConnection(Account account) {
 587		SharedPreferences sharedPref = PreferenceManager
 588				.getDefaultSharedPreferences(getApplicationContext());
 589		account.setResource(sharedPref.getString("resource", "mobile").toLowerCase(Locale.getDefault()));
 590		XmppConnection connection = new XmppConnection(account, this.wakeLock);
 591		connection.setOnMessagePacketReceivedListener(this.messageListener);
 592		connection.setOnStatusChangedListener(this.statusListener);
 593		connection.setOnPresencePacketReceivedListener(this.presenceListener);
 594		connection
 595				.setOnUnregisteredIqPacketReceivedListener(this.unknownIqListener);
 596		connection.setOnJinglePacketReceivedListener(this.jingleListener);
 597		connection
 598				.setOnTLSExceptionReceivedListener(new OnTLSExceptionReceived() {
 599
 600					@Override
 601					public void onTLSExceptionReceived(String fingerprint,
 602							Account account) {
 603						Log.d(LOGTAG, "tls exception arrived in service");
 604						if (tlsException != null) {
 605							tlsException.onTLSExceptionReceived(fingerprint,
 606									account);
 607						}
 608					}
 609				});
 610		connection.setOnBindListener(new OnBindListener() {
 611
 612			@Override
 613			public void onBind(Account account) {
 614				databaseBackend.clearPresences(account);
 615				account.clearPresences(); // self presences
 616				if (account.getXmppConnection().hasFeatureRosterManagment()) {
 617					updateRoster(account, null);
 618				}
 619				connectMultiModeConversations(account);
 620				if (convChangedListener != null) {
 621					convChangedListener.onConversationListChanged();
 622				}
 623			}
 624		});
 625		return connection;
 626	}
 627
 628	synchronized public void sendMessage(Message message, String presence) {
 629		Account account = message.getConversation().getAccount();
 630		Conversation conv = message.getConversation();
 631		boolean saveInDb = false;
 632		boolean addToConversation = false;
 633		if (account.getStatus() == Account.STATUS_ONLINE) {
 634			MessagePacket packet;
 635			if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 636				if (!conv.hasValidOtrSession()) {
 637					// starting otr session. messages will be send later
 638					conv.startOtrSession(getApplicationContext(), presence,true);
 639				} else if (conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
 640					// otr session aleary exists, creating message packet
 641					// accordingly
 642					packet = prepareMessagePacket(account, message,
 643							conv.getOtrSession());
 644					account.getXmppConnection().sendMessagePacket(packet);
 645					message.setStatus(Message.STATUS_SEND);
 646				}
 647				saveInDb = true;
 648				addToConversation = true;
 649			} else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
 650				message.getConversation().endOtrIfNeeded();
 651				long keyId = message.getConversation().getContact()
 652						.getPgpKeyId();
 653				packet = new MessagePacket();
 654				packet.setType(MessagePacket.TYPE_CHAT);
 655				packet.setFrom(message.getConversation().getAccount()
 656						.getFullJid());
 657				packet.setTo(message.getCounterpart());
 658				packet.setBody("This is an XEP-0027 encryted message");
 659				packet.addChild("x","jabber:x:encrypted").setContent(this.getPgpEngine().encrypt(keyId,
 660						message.getBody()));
 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		databaseBackend.updateAccount(account);
 997		reconnectAccount(account, false);
 998		if (accountChangedListener != null)
 999			accountChangedListener.onAccountListChangedListener();
1000	}
1001
1002	public void deleteAccount(Account account) {
1003		if (account.getXmppConnection() != null) {
1004			this.disconnect(account, true);
1005		}
1006		databaseBackend.deleteAccount(account);
1007		this.accounts.remove(account);
1008		if (accountChangedListener != null)
1009			accountChangedListener.onAccountListChangedListener();
1010	}
1011
1012	public void setOnConversationListChangedListener(
1013			OnConversationListChangedListener listener) {
1014		this.convChangedListener = listener;
1015		this.convChangedListenerCount++;
1016		Log.d(LOGTAG,"registered on conv changed in backend ("+convChangedListenerCount+")");
1017	}
1018
1019	public void removeOnConversationListChangedListener() {
1020		this.convChangedListenerCount--;
1021		Log.d(LOGTAG,"someone on conv changed listener removed listener ("+convChangedListenerCount+")");
1022		if (this.convChangedListenerCount==0) {
1023			this.convChangedListener = null;
1024		}
1025	}
1026
1027	public void setOnAccountListChangedListener(
1028			OnAccountListChangedListener listener) {
1029		this.accountChangedListener = listener;
1030	}
1031
1032	public void removeOnAccountListChangedListener() {
1033		this.accountChangedListener = null;
1034	}
1035
1036	public void connectMultiModeConversations(Account account) {
1037		List<Conversation> conversations = getConversations();
1038		for (int i = 0; i < conversations.size(); i++) {
1039			Conversation conversation = conversations.get(i);
1040			if ((conversation.getMode() == Conversation.MODE_MULTI)
1041					&& (conversation.getAccount() == account)) {
1042				joinMuc(conversation);
1043			}
1044		}
1045	}
1046
1047	public void joinMuc(Conversation conversation) {
1048		String[] mucParts = conversation.getContactJid().split("/");
1049		String muc;
1050		String nick;
1051		if (mucParts.length == 2) {
1052			muc = mucParts[0];
1053			nick = mucParts[1];
1054		} else {
1055			muc = mucParts[0];
1056			nick = conversation.getAccount().getUsername();
1057		}
1058		PresencePacket packet = new PresencePacket();
1059		packet.setAttribute("to", muc + "/" + nick);
1060		Element x = new Element("x");
1061		x.setAttribute("xmlns", "http://jabber.org/protocol/muc");
1062		if (conversation.getMessages().size() != 0) {
1063			long lastMsgTime = conversation.getLatestMessage().getTimeSent();
1064			long diff = (System.currentTimeMillis() - lastMsgTime) / 1000 - 1;
1065			x.addChild("history").setAttribute("seconds", diff + "");
1066		}
1067		packet.addChild(x);
1068		Log.d(LOGTAG,conversation.getAccount().getJid()+": joining muc "+packet.toString());
1069		conversation.getAccount().getXmppConnection()
1070				.sendPresencePacket(packet);
1071	}
1072
1073	private OnRenameListener renameListener = null;
1074
1075	public void setOnRenameListener(OnRenameListener listener) {
1076		this.renameListener = listener;
1077	}
1078
1079	public void renameInMuc(final Conversation conversation, final String nick) {
1080		final MucOptions options = conversation.getMucOptions();
1081		if (options.online()) {
1082			options.setOnRenameListener(new OnRenameListener() {
1083
1084				@Override
1085				public void onRename(boolean success) {
1086					if (renameListener != null) {
1087						renameListener.onRename(success);
1088					}
1089					if (success) {
1090						databaseBackend.updateConversation(conversation);
1091					}
1092				}
1093			});
1094			options.flagAboutToRename();
1095			PresencePacket packet = new PresencePacket();
1096			packet.setAttribute("to",
1097					conversation.getContactJid().split("/")[0] + "/" + nick);
1098			packet.setAttribute("from", conversation.getAccount().getFullJid());
1099
1100			conversation.getAccount().getXmppConnection()
1101					.sendPresencePacket(packet, null);
1102		} else {
1103			String jid = conversation.getContactJid().split("/")[0] + "/"
1104					+ nick;
1105			conversation.setContactJid(jid);
1106			databaseBackend.updateConversation(conversation);
1107			if (conversation.getAccount().getStatus() == Account.STATUS_ONLINE) {
1108				joinMuc(conversation);
1109			}
1110		}
1111	}
1112
1113	public void leaveMuc(Conversation conversation) {
1114		PresencePacket packet = new PresencePacket();
1115		packet.setAttribute("to", conversation.getContactJid().split("/")[0] + "/" + conversation.getMucOptions().getNick());
1116		packet.setAttribute("from", conversation.getAccount().getFullJid());
1117		packet.setAttribute("type", "unavailable");
1118		Log.d(LOGTAG,"send leaving muc " + packet);
1119		conversation.getAccount().getXmppConnection()
1120				.sendPresencePacket(packet);
1121		conversation.getMucOptions().setOffline();
1122	}
1123
1124	public void disconnect(Account account, boolean force) {
1125		if ((account.getStatus() == Account.STATUS_ONLINE)
1126				|| (account.getStatus() == Account.STATUS_DISABLED)) {
1127			if (!force) {
1128				List<Conversation> conversations = getConversations();
1129				for (int i = 0; i < conversations.size(); i++) {
1130					Conversation conversation = conversations.get(i);
1131					if (conversation.getAccount() == account) {
1132						if (conversation.getMode() == Conversation.MODE_MULTI) {
1133							leaveMuc(conversation);
1134						} else {
1135							conversation.endOtrIfNeeded();
1136						}
1137					}
1138				}
1139			}
1140			account.getXmppConnection().disconnect(force);
1141		}
1142	}
1143
1144	@Override
1145	public IBinder onBind(Intent intent) {
1146		return mBinder;
1147	}
1148
1149	public void updateContact(Contact contact) {
1150		databaseBackend.updateContact(contact);
1151		replaceContactInConversation(contact.getJid(), contact);
1152	}
1153
1154	public void updateMessage(Message message) {
1155		databaseBackend.updateMessage(message);
1156	}
1157
1158	public void createContact(Contact contact) {
1159		SharedPreferences sharedPref = PreferenceManager
1160				.getDefaultSharedPreferences(getApplicationContext());
1161		boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1162		if (autoGrant) {
1163			contact.setSubscriptionOption(Contact.Subscription.PREEMPTIVE_GRANT);
1164			contact.setSubscriptionOption(Contact.Subscription.ASKING);
1165		}
1166		databaseBackend.createContact(contact);
1167		IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
1168		Element query = new Element("query");
1169		query.setAttribute("xmlns", "jabber:iq:roster");
1170		Element item = new Element("item");
1171		item.setAttribute("jid", contact.getJid());
1172		item.setAttribute("name", contact.getJid());
1173		query.addChild(item);
1174		iq.addChild(query);
1175		Account account = contact.getAccount();
1176		account.getXmppConnection().sendIqPacket(iq, null);
1177		if (autoGrant) {
1178			requestPresenceUpdatesFrom(contact);
1179		}
1180		replaceContactInConversation(contact.getJid(), contact);
1181	}
1182
1183	public void requestPresenceUpdatesFrom(Contact contact) {
1184		// Requesting a Subscription type=subscribe
1185		PresencePacket packet = new PresencePacket();
1186		packet.setAttribute("type", "subscribe");
1187		packet.setAttribute("to", contact.getJid());
1188		packet.setAttribute("from", contact.getAccount().getJid());
1189		Log.d(LOGTAG, packet.toString());
1190		contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1191	}
1192
1193	public void stopPresenceUpdatesFrom(Contact contact) {
1194		// Unsubscribing type='unsubscribe'
1195		PresencePacket packet = new PresencePacket();
1196		packet.setAttribute("type", "unsubscribe");
1197		packet.setAttribute("to", contact.getJid());
1198		packet.setAttribute("from", contact.getAccount().getJid());
1199		Log.d(LOGTAG, packet.toString());
1200		contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1201	}
1202
1203	public void stopPresenceUpdatesTo(Contact contact) {
1204		// Canceling a Subscription type=unsubscribed
1205		PresencePacket packet = new PresencePacket();
1206		packet.setAttribute("type", "unsubscribed");
1207		packet.setAttribute("to", contact.getJid());
1208		packet.setAttribute("from", contact.getAccount().getJid());
1209		Log.d(LOGTAG, packet.toString());
1210		contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1211	}
1212
1213	public void sendPresenceUpdatesTo(Contact contact) {
1214		// type='subscribed'
1215		PresencePacket packet = new PresencePacket();
1216		packet.setAttribute("type", "subscribed");
1217		packet.setAttribute("to", contact.getJid());
1218		packet.setAttribute("from", contact.getAccount().getJid());
1219		Log.d(LOGTAG, packet.toString());
1220		contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1221	}
1222
1223	public void sendPgpPresence(Account account, String signature) {
1224		PresencePacket packet = new PresencePacket();
1225		packet.setAttribute("from", account.getFullJid());
1226		Element status = new Element("status");
1227		status.setContent("online");
1228		packet.addChild(status);
1229		Element x = new Element("x");
1230		x.setAttribute("xmlns", "jabber:x:signed");
1231		x.setContent(signature);
1232		packet.addChild(x);
1233		account.getXmppConnection().sendPresencePacket(packet);
1234	}
1235
1236	public void generatePgpAnnouncement(Account account)
1237			throws PgpEngine.UserInputRequiredException {
1238		if (account.getStatus() == Account.STATUS_ONLINE) {
1239			String signature = getPgpEngine().generateSignature("online");
1240			account.setKey("pgp_signature", signature);
1241			databaseBackend.updateAccount(account);
1242			sendPgpPresence(account, signature);
1243		}
1244	}
1245
1246	public void updateConversation(Conversation conversation) {
1247		this.databaseBackend.updateConversation(conversation);
1248	}
1249
1250	public Contact findContact(String uuid) {
1251		Contact contact = this.databaseBackend.getContact(uuid);
1252		for (Account account : getAccounts()) {
1253			if (contact.getAccountUuid().equals(account.getUuid())) {
1254				contact.setAccount(account);
1255			}
1256		}
1257		return contact;
1258	}
1259
1260	public void removeOnTLSExceptionReceivedListener() {
1261		this.tlsException = null;
1262	}
1263
1264	// TODO dont let thread sleep but schedule wake up
1265	public void reconnectAccount(final Account account, final boolean force) {
1266		new Thread(new Runnable() {
1267
1268			@Override
1269			public void run() {
1270				if (account.getXmppConnection() != null) {
1271					disconnect(account, force);
1272				}
1273				if (!account.isOptionSet(Account.OPTION_DISABLED)) {
1274					if (account.getXmppConnection() == null) {
1275						account.setXmppConnection(createConnection(account));
1276					}
1277					Thread thread = new Thread(account.getXmppConnection());
1278					thread.start();
1279					scheduleWakeupCall((int) (CONNECT_TIMEOUT * 1.2), false);
1280				}
1281			}
1282		}).start();
1283	}
1284
1285	public void updateConversationInGui() {
1286		if (convChangedListener != null) {
1287			convChangedListener.onConversationListChanged();
1288		}
1289	}
1290
1291	public void sendConversationSubject(Conversation conversation,
1292			String subject) {
1293		MessagePacket packet = new MessagePacket();
1294		packet.setType(MessagePacket.TYPE_GROUPCHAT);
1295		packet.setTo(conversation.getContactJid().split("/")[0]);
1296		Element subjectChild = new Element("subject");
1297		subjectChild.setContent(subject);
1298		packet.addChild(subjectChild);
1299		packet.setFrom(conversation.getAccount().getJid());
1300		Account account = conversation.getAccount();
1301		if (account.getStatus() == Account.STATUS_ONLINE) {
1302			account.getXmppConnection().sendMessagePacket(packet);
1303		}
1304	}
1305
1306	public void inviteToConference(Conversation conversation,
1307			List<Contact> contacts) {
1308		for (Contact contact : contacts) {
1309			MessagePacket packet = new MessagePacket();
1310			packet.setTo(conversation.getContactJid().split("/")[0]);
1311			packet.setFrom(conversation.getAccount().getFullJid());
1312			Element x = new Element("x");
1313			x.setAttribute("xmlns", "http://jabber.org/protocol/muc#user");
1314			Element invite = new Element("invite");
1315			invite.setAttribute("to", contact.getJid());
1316			x.addChild(invite);
1317			packet.addChild(x);
1318			Log.d(LOGTAG, packet.toString());
1319			conversation.getAccount().getXmppConnection()
1320					.sendMessagePacket(packet);
1321		}
1322
1323	}
1324}