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