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