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 = 30;
  73	private static final int PING_MIN_INTERVAL = 10;
  74	private static final int PING_TIMEOUT = 2;
  75
  76	private List<Account> accounts;
  77	private List<Conversation> conversations = null;
  78
  79	public OnConversationListChangedListener convChangedListener = null;
  80	private OnAccountListChangedListener accountChangedListener = null;
  81	private OnTLSExceptionReceived tlsException = null;
  82	
  83	public void setOnTLSExceptionReceivedListener(
  84			OnTLSExceptionReceived listener) {
  85		tlsException = listener;
  86	}
  87
  88	private Random mRandom = new Random(System.currentTimeMillis());
  89
  90	private ContentObserver contactObserver = new ContentObserver(null) {
  91		@Override
  92		public void onChange(boolean selfChange) {
  93			super.onChange(selfChange);
  94			Log.d(LOGTAG, "contact list has changed");
  95			mergePhoneContactsWithRoster(null);
  96		}
  97	};
  98
  99	private XmppConnectionService service = this;
 100
 101	private final IBinder mBinder = new XmppConnectionBinder();
 102	private OnMessagePacketReceived messageListener = new OnMessagePacketReceived() {
 103
 104		@Override
 105		public void onMessagePacketReceived(Account account,
 106				MessagePacket packet) {
 107			Message message = null;
 108			boolean notify = true;
 109			if ((packet.getType() == MessagePacket.TYPE_CHAT)) {
 110				String pgpBody = MessageParser.getPgpBody(packet);
 111				if (pgpBody != null) {
 112					message = MessageParser.parsePgpChat(pgpBody, packet,
 113							account, service);
 114					message.markUnread();
 115				} else if (packet.hasChild("body")
 116						&& (packet.getBody().startsWith("?OTR"))) {
 117					message = MessageParser.parseOtrChat(packet, account,
 118							service);
 119					if (message != null) {
 120						message.markUnread();
 121					}
 122				} else if (packet.hasChild("body")) {
 123					message = MessageParser.parsePlainTextChat(packet, account,
 124							service);
 125					message.markUnread();
 126				} else if (packet.hasChild("received")
 127						|| (packet.hasChild("sent"))) {
 128					message = MessageParser.parseCarbonMessage(packet, account,
 129							service);
 130					if (message != null) {
 131						message.getConversation().markRead();
 132					}
 133					notify = false;
 134				}
 135
 136			} else if (packet.getType() == MessagePacket.TYPE_GROUPCHAT) {
 137				message = MessageParser
 138						.parseGroupchat(packet, account, service);
 139				if (message != null) {
 140					if (message.getStatus() == Message.STATUS_RECIEVED) {
 141						message.markUnread();
 142					} else {
 143						message.getConversation().markRead();
 144						notify = false;
 145					}
 146				}
 147			} else if (packet.getType() == MessagePacket.TYPE_ERROR) {
 148				message = MessageParser.parseError(packet, account, service);
 149			} else {
 150				// Log.d(LOGTAG, "unparsed message " + packet.toString());
 151			}
 152			if (message == null) {
 153				return;
 154			}
 155			if (packet.hasChild("delay")) {
 156				try {
 157					String stamp = packet.findChild("delay").getAttribute(
 158							"stamp");
 159					stamp = stamp.replace("Z", "+0000");
 160					Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
 161							.parse(stamp);
 162					message.setTime(date.getTime());
 163				} catch (ParseException e) {
 164					Log.d(LOGTAG, "error trying to parse date" + e.getMessage());
 165				}
 166			}
 167			Conversation conversation = message.getConversation();
 168			conversation.getMessages().add(message);
 169			if (packet.getType() != MessagePacket.TYPE_ERROR) {
 170				databaseBackend.createMessage(message);
 171			}
 172			if (convChangedListener != null) {
 173				convChangedListener.onConversationListChanged();
 174			} else {
 175				UIHelper.updateNotification(getApplicationContext(),
 176						getConversations(), notify);
 177			}
 178		}
 179	};
 180	private OnStatusChanged statusListener = new OnStatusChanged() {
 181
 182		@Override
 183		public void onStatusChanged(Account account) {
 184			if (accountChangedListener != null) {
 185				accountChangedListener.onAccountListChangedListener();
 186			}
 187			if (account.getStatus() == Account.STATUS_ONLINE) {
 188				databaseBackend.clearPresences(account);
 189				if (account.getXmppConnection().hasFeatureRosterManagment()) {
 190					updateRoster(account, null);
 191				}
 192				connectMultiModeConversations(account);
 193				List<Conversation> conversations = getConversations();
 194				for (int i = 0; i < conversations.size(); ++i) {
 195					if (conversations.get(i).getAccount() == account) {
 196						sendUnsendMessages(conversations.get(i));
 197					}
 198				}
 199				if (convChangedListener != null) {
 200					convChangedListener.onConversationListChanged();
 201				}
 202				scheduleWakeupCall(PING_MAX_INTERVAL, true);
 203			} else if (account.getStatus() == Account.STATUS_OFFLINE) {
 204				Log.d(LOGTAG, "onStatusChanged 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		
 401		// internet and online last_received - list_ping >= max_ping : ping
 402		// internet and online last_ping - last_received >= ping_timeout :
 403		// reconnect
 404		// internet and offline and enabled : connect (Threat start)
 405
 406		// no internet - set no internet
 407
 408		ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
 409				.getSystemService(Context.CONNECTIVITY_SERVICE);
 410		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
 411		boolean isConnected = activeNetwork != null
 412				&& activeNetwork.isConnected();
 413
 414		for (Account account : accounts) {
 415			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
 416				if (!isConnected) {
 417					account.setStatus(Account.STATUS_NO_INTERNET);
 418				} else {
 419					if (account.getStatus() == Account.STATUS_NO_INTERNET) {
 420						account.setStatus(Account.STATUS_OFFLINE);
 421					}
 422
 423					// TODO 3 remaining cases
 424					if (account.getStatus() == Account.STATUS_ONLINE) {
 425						long lastReceived = account.getXmppConnection().lastPaketReceived;
 426						long lastSent = account.getXmppConnection().lastPingSent;
 427						if (lastSent - lastReceived >= PING_TIMEOUT * 1000) {
 428							Log.d(LOGTAG, account.getJid() + ": ping timeout");
 429							this.reconnectAccount(account);
 430						} else if (SystemClock.elapsedRealtime() - lastReceived >= PING_MIN_INTERVAL * 1000) {
 431							account.getXmppConnection().sendPing();
 432							account.getXmppConnection().lastPingSent = SystemClock.elapsedRealtime();
 433							this.scheduleWakeupCall(2, false);
 434						}
 435					} else if (account.getStatus() == Account.STATUS_OFFLINE) {
 436						if (account.getXmppConnection() == null) {
 437							account.setXmppConnection(this
 438									.createConnection(account));
 439						}
 440						account.getXmppConnection().lastPingSent = SystemClock.elapsedRealtime();
 441						new Thread(account.getXmppConnection()).start();
 442					} else {
 443						Log.d(LOGTAG,account.getJid()+": status="+account.getStatus());
 444					}
 445					//in any case. reschedule wakup call
 446					this.scheduleWakeupCall(PING_MAX_INTERVAL, true);
 447				}
 448				if (accountChangedListener != null) {
 449					accountChangedListener.onAccountListChangedListener();
 450				}
 451			}
 452		}
 453		return START_STICKY;
 454	}
 455
 456	@Override
 457	public void onCreate() {
 458		ExceptionHelper.init(getApplicationContext());
 459		databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
 460		this.accounts = databaseBackend.getAccounts();
 461
 462		getContentResolver().registerContentObserver(
 463				ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
 464		this.pgpServiceConnection = new OpenPgpServiceConnection(
 465				getApplicationContext(), "org.sufficientlysecure.keychain");
 466		this.pgpServiceConnection.bindToService();
 467
 468	}
 469
 470	@Override
 471	public void onDestroy() {
 472		super.onDestroy();
 473		for (Account account : accounts) {
 474			if (account.getXmppConnection() != null) {
 475				disconnect(account, true);
 476			}
 477		}
 478	}
 479
 480	protected void scheduleWakeupCall(int seconds, boolean ping) {
 481		long timeToWake = SystemClock.elapsedRealtime() + seconds * 1000;
 482		Context context = getApplicationContext();
 483		AlarmManager alarmManager = (AlarmManager) context
 484				.getSystemService(Context.ALARM_SERVICE);
 485		
 486		
 487		
 488		if (ping) {
 489			if (this.pingIntent==null) {
 490				this.pingIntent = new Intent(context, EventReceiver.class);
 491				this.pingIntent.setAction("ping");
 492				this.pingIntent.putExtra("time", timeToWake);
 493				this.pendingPingIntent = PendingIntent.getBroadcast(context, 0,
 494						this.pingIntent, 0);
 495				alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,timeToWake, pendingPingIntent);
 496				Log.d(LOGTAG,"schedule ping in "+seconds+" seconds");
 497			} else {
 498				long scheduledTime = this.pingIntent.getLongExtra("time", 0);
 499				if (scheduledTime<SystemClock.elapsedRealtime() || (scheduledTime > timeToWake)) {
 500					this.pingIntent.putExtra("time", timeToWake);
 501					alarmManager.cancel(this.pendingPingIntent);
 502					this.pendingPingIntent = PendingIntent.getBroadcast(context, 0,
 503							this.pingIntent, 0);
 504					alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,timeToWake, pendingPingIntent);
 505					Log.d(LOGTAG,"reschedule old ping to ping in "+seconds+" seconds");
 506				}
 507			}
 508		} else {
 509			Intent intent = new Intent(context, EventReceiver.class);
 510			intent.setAction("ping_check");
 511			PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0,
 512					intent, 0);
 513			alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,timeToWake, alarmIntent);
 514		}
 515
 516	}
 517
 518	public XmppConnection createConnection(Account account) {
 519		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 520		XmppConnection connection = new XmppConnection(account, pm);
 521		connection.setOnMessagePacketReceivedListener(this.messageListener);
 522		connection.setOnStatusChangedListener(this.statusListener);
 523		connection.setOnPresencePacketReceivedListener(this.presenceListener);
 524		connection
 525				.setOnUnregisteredIqPacketReceivedListener(this.unknownIqListener);
 526		connection
 527				.setOnTLSExceptionReceivedListener(new OnTLSExceptionReceived() {
 528
 529					@Override
 530					public void onTLSExceptionReceived(String fingerprint,
 531							Account account) {
 532						Log.d(LOGTAG, "tls exception arrived in service");
 533						if (tlsException != null) {
 534							tlsException.onTLSExceptionReceived(fingerprint,
 535									account);
 536						}
 537					}
 538				});
 539		return connection;
 540	}
 541
 542	public void sendMessage(Message message, String presence) {
 543		Account account = message.getConversation().getAccount();
 544		Conversation conv = message.getConversation();
 545		boolean saveInDb = false;
 546		boolean addToConversation = false;
 547		if (account.getStatus() == Account.STATUS_ONLINE) {
 548			MessagePacket packet;
 549			if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 550				if (!conv.hasValidOtrSession()) {
 551					// starting otr session. messages will be send later
 552					conv.startOtrSession(getApplicationContext(), presence);
 553				} else if (conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
 554					// otr session aleary exists, creating message packet
 555					// accordingly
 556					packet = prepareMessagePacket(account, message,
 557							conv.getOtrSession());
 558					account.getXmppConnection().sendMessagePacket(packet);
 559					message.setStatus(Message.STATUS_SEND);
 560				}
 561				saveInDb = true;
 562				addToConversation = true;
 563			} else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
 564				long keyId = message.getConversation().getContact()
 565						.getPgpKeyId();
 566				packet = new MessagePacket();
 567				packet.setType(MessagePacket.TYPE_CHAT);
 568				packet.setFrom(message.getConversation().getAccount()
 569						.getFullJid());
 570				packet.setTo(message.getCounterpart());
 571				packet.setBody("This is an XEP-0027 encryted message");
 572				Element x = new Element("x");
 573				x.setAttribute("xmlns", "jabber:x:encrypted");
 574				x.setContent(this.getPgpEngine().encrypt(keyId,
 575						message.getBody()));
 576				packet.addChild(x);
 577				account.getXmppConnection().sendMessagePacket(packet);
 578				message.setStatus(Message.STATUS_SEND);
 579				message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 580				saveInDb = true;
 581				addToConversation = true;
 582			} else {
 583				// don't encrypt
 584				if (message.getConversation().getMode() == Conversation.MODE_SINGLE) {
 585					message.setStatus(Message.STATUS_SEND);
 586					saveInDb = true;
 587					addToConversation = true;
 588				}
 589
 590				packet = prepareMessagePacket(account, message, null);
 591				account.getXmppConnection().sendMessagePacket(packet);
 592			}
 593		} else {
 594			// account is offline
 595			saveInDb = true;
 596			addToConversation = true;
 597
 598		}
 599		if (saveInDb) {
 600			databaseBackend.createMessage(message);
 601		}
 602		if (addToConversation) {
 603			conv.getMessages().add(message);
 604			if (convChangedListener != null) {
 605				convChangedListener.onConversationListChanged();
 606			}
 607		}
 608
 609	}
 610
 611	private void sendUnsendMessages(Conversation conversation) {
 612		for (int i = 0; i < conversation.getMessages().size(); ++i) {
 613			if (conversation.getMessages().get(i).getStatus() == Message.STATUS_UNSEND) {
 614				Message message = conversation.getMessages().get(i);
 615				MessagePacket packet = prepareMessagePacket(
 616						conversation.getAccount(), message, null);
 617				conversation.getAccount().getXmppConnection()
 618						.sendMessagePacket(packet);
 619				message.setStatus(Message.STATUS_SEND);
 620				if (conversation.getMode() == Conversation.MODE_SINGLE) {
 621					databaseBackend.updateMessage(message);
 622				} else {
 623					databaseBackend.deleteMessage(message);
 624					conversation.getMessages().remove(i);
 625					i--;
 626				}
 627			}
 628		}
 629	}
 630
 631	public MessagePacket prepareMessagePacket(Account account, Message message,
 632			Session otrSession) {
 633		MessagePacket packet = new MessagePacket();
 634		if (message.getConversation().getMode() == Conversation.MODE_SINGLE) {
 635			packet.setType(MessagePacket.TYPE_CHAT);
 636			if (otrSession != null) {
 637				try {
 638					packet.setBody(otrSession.transformSending(message
 639							.getBody()));
 640				} catch (OtrException e) {
 641					Log.d(LOGTAG,
 642							account.getJid()
 643									+ ": could not encrypt message to "
 644									+ message.getCounterpart());
 645				}
 646				Element privateMarker = new Element("private");
 647				privateMarker.setAttribute("xmlns", "urn:xmpp:carbons:2");
 648				packet.addChild(privateMarker);
 649				packet.setTo(otrSession.getSessionID().getAccountID() + "/"
 650						+ otrSession.getSessionID().getUserID());
 651				packet.setFrom(account.getFullJid());
 652			} else {
 653				packet.setBody(message.getBody());
 654				packet.setTo(message.getCounterpart());
 655				packet.setFrom(account.getJid());
 656			}
 657		} else if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
 658			packet.setType(MessagePacket.TYPE_GROUPCHAT);
 659			packet.setBody(message.getBody());
 660			packet.setTo(message.getCounterpart().split("/")[0]);
 661			packet.setFrom(account.getJid());
 662		}
 663		return packet;
 664	}
 665
 666	public void getRoster(Account account,
 667			final OnRosterFetchedListener listener) {
 668		List<Contact> contacts = databaseBackend.getContactsByAccount(account);
 669		for (int i = 0; i < contacts.size(); ++i) {
 670			contacts.get(i).setAccount(account);
 671		}
 672		if (listener != null) {
 673			listener.onRosterFetched(contacts);
 674		}
 675	}
 676
 677	public void updateRoster(final Account account,
 678			final OnRosterFetchedListener listener) {
 679		IqPacket iqPacket = new IqPacket(IqPacket.TYPE_GET);
 680		Element query = new Element("query");
 681		query.setAttribute("xmlns", "jabber:iq:roster");
 682		if (!"".equals(account.getRosterVersion())) {
 683			Log.d(LOGTAG, account.getJid() + ": fetching roster version "
 684					+ account.getRosterVersion());
 685		} else {
 686			Log.d(LOGTAG, account.getJid() + ": fetching roster");
 687		}
 688		query.setAttribute("ver", account.getRosterVersion());
 689		iqPacket.addChild(query);
 690		account.getXmppConnection().sendIqPacket(iqPacket,
 691				new OnIqPacketReceived() {
 692
 693					@Override
 694					public void onIqPacketReceived(final Account account,
 695							IqPacket packet) {
 696						Element roster = packet.findChild("query");
 697						if (roster != null) {
 698							Log.d(LOGTAG, account.getJid()
 699									+ ": processing roster");
 700							processRosterItems(account, roster);
 701							StringBuilder mWhere = new StringBuilder();
 702							mWhere.append("jid NOT IN(");
 703							List<Element> items = roster.getChildren();
 704							for (int i = 0; i < items.size(); ++i) {
 705								mWhere.append(DatabaseUtils
 706										.sqlEscapeString(items.get(i)
 707												.getAttribute("jid")));
 708								if (i != items.size() - 1) {
 709									mWhere.append(",");
 710								}
 711							}
 712							mWhere.append(") and accountUuid = \"");
 713							mWhere.append(account.getUuid());
 714							mWhere.append("\"");
 715							List<Contact> contactsToDelete = databaseBackend
 716									.getContacts(mWhere.toString());
 717							for (Contact contact : contactsToDelete) {
 718								databaseBackend.deleteContact(contact);
 719								replaceContactInConversation(contact.getJid(),
 720										null);
 721							}
 722
 723						} else {
 724							Log.d(LOGTAG, account.getJid()
 725									+ ": empty roster returend");
 726						}
 727						mergePhoneContactsWithRoster(new OnPhoneContactsMerged() {
 728
 729							@Override
 730							public void phoneContactsMerged() {
 731								if (listener != null) {
 732									getRoster(account, listener);
 733								}
 734							}
 735						});
 736					}
 737				});
 738	}
 739
 740	public void mergePhoneContactsWithRoster(
 741			final OnPhoneContactsMerged listener) {
 742		PhoneHelper.loadPhoneContacts(getApplicationContext(),
 743				new OnPhoneContactsLoadedListener() {
 744					@Override
 745					public void onPhoneContactsLoaded(
 746							Hashtable<String, Bundle> phoneContacts) {
 747						List<Contact> contacts = databaseBackend
 748								.getContactsByAccount(null);
 749						for (int i = 0; i < contacts.size(); ++i) {
 750							Contact contact = contacts.get(i);
 751							if (phoneContacts.containsKey(contact.getJid())) {
 752								Bundle phoneContact = phoneContacts.get(contact
 753										.getJid());
 754								String systemAccount = phoneContact
 755										.getInt("phoneid")
 756										+ "#"
 757										+ phoneContact.getString("lookup");
 758								contact.setSystemAccount(systemAccount);
 759								contact.setPhotoUri(phoneContact
 760										.getString("photouri"));
 761								contact.setDisplayName(phoneContact
 762										.getString("displayname"));
 763								databaseBackend.updateContact(contact);
 764								replaceContactInConversation(contact.getJid(),
 765										contact);
 766							} else {
 767								if ((contact.getSystemAccount() != null)
 768										|| (contact.getProfilePhoto() != null)) {
 769									contact.setSystemAccount(null);
 770									contact.setPhotoUri(null);
 771									databaseBackend.updateContact(contact);
 772									replaceContactInConversation(
 773											contact.getJid(), contact);
 774								}
 775							}
 776						}
 777						if (listener != null) {
 778							listener.phoneContactsMerged();
 779						}
 780					}
 781				});
 782	}
 783
 784	public List<Conversation> getConversations() {
 785		if (this.conversations == null) {
 786			Hashtable<String, Account> accountLookupTable = new Hashtable<String, Account>();
 787			for (Account account : this.accounts) {
 788				accountLookupTable.put(account.getUuid(), account);
 789			}
 790			this.conversations = databaseBackend
 791					.getConversations(Conversation.STATUS_AVAILABLE);
 792			for (Conversation conv : this.conversations) {
 793				Account account = accountLookupTable.get(conv.getAccountUuid());
 794				conv.setAccount(account);
 795				conv.setContact(findContact(account, conv.getContactJid()));
 796				conv.setMessages(databaseBackend.getMessages(conv, 50));
 797			}
 798		}
 799		return this.conversations;
 800	}
 801
 802	public List<Account> getAccounts() {
 803		return this.accounts;
 804	}
 805
 806	public Contact findContact(Account account, String jid) {
 807		Contact contact = databaseBackend.findContact(account, jid);
 808		if (contact != null) {
 809			contact.setAccount(account);
 810		}
 811		return contact;
 812	}
 813
 814	public Conversation findOrCreateConversation(Account account, String jid,
 815			boolean muc) {
 816		for (Conversation conv : this.getConversations()) {
 817			if ((conv.getAccount().equals(account))
 818					&& (conv.getContactJid().split("/")[0].equals(jid))) {
 819				return conv;
 820			}
 821		}
 822		Conversation conversation = databaseBackend.findConversation(account,
 823				jid);
 824		if (conversation != null) {
 825			conversation.setStatus(Conversation.STATUS_AVAILABLE);
 826			conversation.setAccount(account);
 827			if (muc) {
 828				conversation.setMode(Conversation.MODE_MULTI);
 829				if (account.getStatus() == Account.STATUS_ONLINE) {
 830					joinMuc(conversation);
 831				}
 832			} else {
 833				conversation.setMode(Conversation.MODE_SINGLE);
 834			}
 835			this.databaseBackend.updateConversation(conversation);
 836			conversation.setContact(findContact(account,
 837					conversation.getContactJid()));
 838		} else {
 839			String conversationName;
 840			Contact contact = findContact(account, jid);
 841			if (contact != null) {
 842				conversationName = contact.getDisplayName();
 843			} else {
 844				conversationName = jid.split("@")[0];
 845			}
 846			if (muc) {
 847				conversation = new Conversation(conversationName, account, jid,
 848						Conversation.MODE_MULTI);
 849				if (account.getStatus() == Account.STATUS_ONLINE) {
 850					joinMuc(conversation);
 851				}
 852			} else {
 853				conversation = new Conversation(conversationName, account, jid,
 854						Conversation.MODE_SINGLE);
 855			}
 856			conversation.setContact(contact);
 857			this.databaseBackend.createConversation(conversation);
 858		}
 859		this.conversations.add(conversation);
 860		if (this.convChangedListener != null) {
 861			this.convChangedListener.onConversationListChanged();
 862		}
 863		return conversation;
 864	}
 865
 866	public void archiveConversation(Conversation conversation) {
 867		if (conversation.getMode() == Conversation.MODE_MULTI) {
 868			leaveMuc(conversation);
 869		} else {
 870			try {
 871				conversation.endOtrIfNeeded();
 872			} catch (OtrException e) {
 873				Log.d(LOGTAG,
 874						"error ending otr session for "
 875								+ conversation.getName());
 876			}
 877		}
 878		this.databaseBackend.updateConversation(conversation);
 879		this.conversations.remove(conversation);
 880		if (this.convChangedListener != null) {
 881			this.convChangedListener.onConversationListChanged();
 882		}
 883	}
 884
 885	public int getConversationCount() {
 886		return this.databaseBackend.getConversationCount();
 887	}
 888
 889	public void createAccount(Account account) {
 890		databaseBackend.createAccount(account);
 891		this.accounts.add(account);
 892		account.setXmppConnection(this.createConnection(account));
 893		if (accountChangedListener != null)
 894			accountChangedListener.onAccountListChangedListener();
 895	}
 896
 897	public void deleteContact(Contact contact) {
 898		IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
 899		Element query = new Element("query");
 900		query.setAttribute("xmlns", "jabber:iq:roster");
 901		Element item = new Element("item");
 902		item.setAttribute("jid", contact.getJid());
 903		item.setAttribute("subscription", "remove");
 904		query.addChild(item);
 905		iq.addChild(query);
 906		contact.getAccount().getXmppConnection().sendIqPacket(iq, null);
 907		replaceContactInConversation(contact.getJid(), null);
 908		databaseBackend.deleteContact(contact);
 909	}
 910
 911	public void updateAccount(Account account) {
 912		databaseBackend.updateAccount(account);
 913		reconnectAccount(account);
 914		if (accountChangedListener != null)
 915			accountChangedListener.onAccountListChangedListener();
 916	}
 917
 918	public void deleteAccount(Account account) {
 919		Log.d(LOGTAG, "called delete account");
 920		if (account.getXmppConnection() != null) {
 921			this.disconnect(account, false);
 922		}
 923		databaseBackend.deleteAccount(account);
 924		this.accounts.remove(account);
 925		if (accountChangedListener != null)
 926			accountChangedListener.onAccountListChangedListener();
 927	}
 928
 929	public void setOnConversationListChangedListener(
 930			OnConversationListChangedListener listener) {
 931		this.convChangedListener = listener;
 932	}
 933
 934	public void removeOnConversationListChangedListener() {
 935		this.convChangedListener = null;
 936	}
 937
 938	public void setOnAccountListChangedListener(
 939			OnAccountListChangedListener listener) {
 940		this.accountChangedListener = listener;
 941	}
 942
 943	public void removeOnAccountListChangedListener() {
 944		this.accountChangedListener = null;
 945	}
 946
 947	public void connectMultiModeConversations(Account account) {
 948		List<Conversation> conversations = getConversations();
 949		for (int i = 0; i < conversations.size(); i++) {
 950			Conversation conversation = conversations.get(i);
 951			if ((conversation.getMode() == Conversation.MODE_MULTI)
 952					&& (conversation.getAccount() == account)) {
 953				joinMuc(conversation);
 954			}
 955		}
 956	}
 957
 958	public void joinMuc(Conversation conversation) {
 959		String[] mucParts = conversation.getContactJid().split("/");
 960		String muc;
 961		String nick;
 962		if (mucParts.length == 2) {
 963			muc = mucParts[0];
 964			nick = mucParts[1];
 965		} else {
 966			muc = mucParts[0];
 967			nick = conversation.getAccount().getUsername();
 968		}
 969		PresencePacket packet = new PresencePacket();
 970		packet.setAttribute("to", muc + "/" + nick);
 971		Element x = new Element("x");
 972		x.setAttribute("xmlns", "http://jabber.org/protocol/muc");
 973		if (conversation.getMessages().size() != 0) {
 974			Element history = new Element("history");
 975			long lastMsgTime = conversation.getLatestMessage().getTimeSent();
 976			long diff = (System.currentTimeMillis() - lastMsgTime) / 1000 - 1;
 977			history.setAttribute("seconds", diff + "");
 978			x.addChild(history);
 979		}
 980		packet.addChild(x);
 981		conversation.getAccount().getXmppConnection()
 982				.sendPresencePacket(packet);
 983	}
 984
 985	private OnRenameListener renameListener = null;
 986	private boolean pongReceived;
 987
 988	public void setOnRenameListener(OnRenameListener listener) {
 989		this.renameListener = listener;
 990	}
 991
 992	public void renameInMuc(final Conversation conversation, final String nick) {
 993		final MucOptions options = conversation.getMucOptions();
 994		if (options.online()) {
 995			options.setOnRenameListener(new OnRenameListener() {
 996
 997				@Override
 998				public void onRename(boolean success) {
 999					if (renameListener != null) {
1000						renameListener.onRename(success);
1001					}
1002					if (success) {
1003						databaseBackend.updateConversation(conversation);
1004					}
1005				}
1006			});
1007			PresencePacket packet = new PresencePacket();
1008			packet.setAttribute("to",
1009					conversation.getContactJid().split("/")[0] + "/" + nick);
1010			packet.setAttribute("from", conversation.getAccount().getFullJid());
1011
1012			conversation.getAccount().getXmppConnection()
1013					.sendPresencePacket(packet, new OnPresencePacketReceived() {
1014
1015						@Override
1016						public void onPresencePacketReceived(Account account,
1017								PresencePacket packet) {
1018							final boolean changed;
1019							String type = packet.getAttribute("type");
1020							changed = (!"error".equals(type));
1021							if (!changed) {
1022								options.getOnRenameListener().onRename(false);
1023							} else {
1024								if (type == null) {
1025									options.getOnRenameListener()
1026											.onRename(true);
1027									options.setNick(packet.getAttribute("from")
1028											.split("/")[1]);
1029								} else {
1030									options.processPacket(packet);
1031								}
1032							}
1033						}
1034					});
1035		} else {
1036			String jid = conversation.getContactJid().split("/")[0] + "/"
1037					+ nick;
1038			conversation.setContactJid(jid);
1039			databaseBackend.updateConversation(conversation);
1040			if (conversation.getAccount().getStatus() == Account.STATUS_ONLINE) {
1041				joinMuc(conversation);
1042			}
1043		}
1044	}
1045
1046	public void leaveMuc(Conversation conversation) {
1047		PresencePacket packet = new PresencePacket();
1048		packet.setAttribute("to", conversation.getContactJid());
1049		packet.setAttribute("from", conversation.getAccount().getFullJid());
1050		packet.setAttribute("type", "unavailable");
1051		conversation.getAccount().getXmppConnection()
1052				.sendPresencePacket(packet);
1053		conversation.getMucOptions().setOffline();
1054	}
1055
1056	public void disconnect(final Account account, boolean blocking) {
1057		if (account.getStatus() == Account.STATUS_ONLINE) {
1058			List<Conversation> conversations = getConversations();
1059			for (int i = 0; i < conversations.size(); i++) {
1060				Conversation conversation = conversations.get(i);
1061				if (conversation.getAccount() == account) {
1062					if (conversation.getMode() == Conversation.MODE_MULTI) {
1063						leaveMuc(conversation);
1064					} else {
1065						try {
1066							conversation.endOtrIfNeeded();
1067						} catch (OtrException e) {
1068							Log.d(LOGTAG, "error ending otr session for "
1069									+ conversation.getName());
1070						}
1071					}
1072				}
1073			}
1074			if (!blocking) {
1075				new Thread(new Runnable() {
1076	
1077					@Override
1078					public void run() {
1079						account.getXmppConnection().disconnect(false);
1080						Log.d(LOGTAG, "disconnected account: " + account.getJid());
1081						account.setXmppConnection(null);
1082					}
1083				}).start();
1084			} else {
1085				account.getXmppConnection().disconnect(false);
1086				Log.d(LOGTAG, "disconnected account: " + account.getJid());
1087				account.setXmppConnection(null);
1088			}
1089		}
1090	}
1091
1092	@Override
1093	public IBinder onBind(Intent intent) {
1094		return mBinder;
1095	}
1096
1097	public void updateContact(Contact contact) {
1098		databaseBackend.updateContact(contact);
1099		replaceContactInConversation(contact.getJid(), contact);
1100	}
1101
1102	public void updateMessage(Message message) {
1103		databaseBackend.updateMessage(message);
1104	}
1105
1106	public void createContact(Contact contact) {
1107		SharedPreferences sharedPref = PreferenceManager
1108				.getDefaultSharedPreferences(getApplicationContext());
1109		boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1110		if (autoGrant) {
1111			contact.setSubscriptionOption(Contact.Subscription.PREEMPTIVE_GRANT);
1112			contact.setSubscriptionOption(Contact.Subscription.ASKING);
1113		}
1114		databaseBackend.createContact(contact);
1115		IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
1116		Element query = new Element("query");
1117		query.setAttribute("xmlns", "jabber:iq:roster");
1118		Element item = new Element("item");
1119		item.setAttribute("jid", contact.getJid());
1120		item.setAttribute("name", contact.getJid());
1121		query.addChild(item);
1122		iq.addChild(query);
1123		Account account = contact.getAccount();
1124		account.getXmppConnection().sendIqPacket(iq, null);
1125		if (autoGrant) {
1126			requestPresenceUpdatesFrom(contact);
1127		}
1128		replaceContactInConversation(contact.getJid(), contact);
1129	}
1130
1131	public void requestPresenceUpdatesFrom(Contact contact) {
1132		// Requesting a Subscription type=subscribe
1133		PresencePacket packet = new PresencePacket();
1134		packet.setAttribute("type", "subscribe");
1135		packet.setAttribute("to", contact.getJid());
1136		packet.setAttribute("from", contact.getAccount().getJid());
1137		Log.d(LOGTAG, packet.toString());
1138		contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1139	}
1140
1141	public void stopPresenceUpdatesFrom(Contact contact) {
1142		// Unsubscribing type='unsubscribe'
1143		PresencePacket packet = new PresencePacket();
1144		packet.setAttribute("type", "unsubscribe");
1145		packet.setAttribute("to", contact.getJid());
1146		packet.setAttribute("from", contact.getAccount().getJid());
1147		Log.d(LOGTAG, packet.toString());
1148		contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1149	}
1150
1151	public void stopPresenceUpdatesTo(Contact contact) {
1152		// Canceling a Subscription type=unsubscribed
1153		PresencePacket packet = new PresencePacket();
1154		packet.setAttribute("type", "unsubscribed");
1155		packet.setAttribute("to", contact.getJid());
1156		packet.setAttribute("from", contact.getAccount().getJid());
1157		Log.d(LOGTAG, packet.toString());
1158		contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1159	}
1160
1161	public void sendPresenceUpdatesTo(Contact contact) {
1162		// type='subscribed'
1163		PresencePacket packet = new PresencePacket();
1164		packet.setAttribute("type", "subscribed");
1165		packet.setAttribute("to", contact.getJid());
1166		packet.setAttribute("from", contact.getAccount().getJid());
1167		Log.d(LOGTAG, packet.toString());
1168		contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1169	}
1170
1171	public void sendPgpPresence(Account account, String signature) {
1172		PresencePacket packet = new PresencePacket();
1173		packet.setAttribute("from", account.getFullJid());
1174		Element status = new Element("status");
1175		status.setContent("online");
1176		packet.addChild(status);
1177		Element x = new Element("x");
1178		x.setAttribute("xmlns", "jabber:x:signed");
1179		x.setContent(signature);
1180		packet.addChild(x);
1181		account.getXmppConnection().sendPresencePacket(packet);
1182	}
1183
1184	public void generatePgpAnnouncement(Account account)
1185			throws PgpEngine.UserInputRequiredException {
1186		if (account.getStatus() == Account.STATUS_ONLINE) {
1187			String signature = getPgpEngine().generateSignature("online");
1188			account.setKey("pgp_signature", signature);
1189			databaseBackend.updateAccount(account);
1190			sendPgpPresence(account, signature);
1191		}
1192	}
1193
1194	public void updateConversation(Conversation conversation) {
1195		this.databaseBackend.updateConversation(conversation);
1196	}
1197
1198	public Contact findContact(String uuid) {
1199		Contact contact = this.databaseBackend.getContact(uuid);
1200		for (Account account : getAccounts()) {
1201			if (contact.getAccountUuid().equals(account.getUuid())) {
1202				contact.setAccount(account);
1203			}
1204		}
1205		return contact;
1206	}
1207
1208	public void removeOnTLSExceptionReceivedListener() {
1209		this.tlsException = null;
1210	}
1211
1212	//TODO dont let thread sleep but schedule wake up
1213	public void reconnectAccount(final Account account) {
1214		new Thread(new Runnable() {
1215
1216			@Override
1217			public void run() {
1218				if (account.getXmppConnection() != null) {
1219					disconnect(account, true);
1220				}
1221				if (!account.isOptionSet(Account.OPTION_DISABLED)) {
1222					if (account.getXmppConnection() == null) {
1223						account.setXmppConnection(createConnection(account));
1224					}
1225					Thread thread = new Thread(account.getXmppConnection());
1226					thread.start();
1227				}
1228			}
1229		}).start();
1230	}
1231}