XmppConnectionService.java

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