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