XmppConnectionService.java

   1package eu.siacs.conversations.services;
   2
   3import java.util.Collections;
   4import java.util.Comparator;
   5import java.util.Hashtable;
   6import java.util.List;
   7import java.util.Locale;
   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;
  16import eu.siacs.conversations.crypto.PgpEngine;
  17import eu.siacs.conversations.entities.Account;
  18import eu.siacs.conversations.entities.Contact;
  19import eu.siacs.conversations.entities.Conversation;
  20import eu.siacs.conversations.entities.Message;
  21import eu.siacs.conversations.entities.MucOptions;
  22import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
  23import eu.siacs.conversations.entities.Presences;
  24import eu.siacs.conversations.parser.MessageParser;
  25import eu.siacs.conversations.parser.PresenceParser;
  26import eu.siacs.conversations.persistance.DatabaseBackend;
  27import eu.siacs.conversations.persistance.FileBackend;
  28import eu.siacs.conversations.ui.OnAccountListChangedListener;
  29import eu.siacs.conversations.ui.OnConversationListChangedListener;
  30import eu.siacs.conversations.ui.UiCallback;
  31import eu.siacs.conversations.utils.ExceptionHelper;
  32import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
  33import eu.siacs.conversations.utils.PhoneHelper;
  34import eu.siacs.conversations.utils.UIHelper;
  35import eu.siacs.conversations.xml.Element;
  36import eu.siacs.conversations.xmpp.OnBindListener;
  37import eu.siacs.conversations.xmpp.OnContactStatusChanged;
  38import eu.siacs.conversations.xmpp.OnIqPacketReceived;
  39import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
  40import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
  41import eu.siacs.conversations.xmpp.OnStatusChanged;
  42import eu.siacs.conversations.xmpp.OnTLSExceptionReceived;
  43import eu.siacs.conversations.xmpp.XmppConnection;
  44import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
  45import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
  46import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
  47import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  48import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
  49import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
  50import android.app.AlarmManager;
  51import android.app.PendingIntent;
  52import android.app.Service;
  53import android.content.Context;
  54import android.content.Intent;
  55import android.content.SharedPreferences;
  56import android.database.ContentObserver;
  57import android.net.ConnectivityManager;
  58import android.net.NetworkInfo;
  59import android.net.Uri;
  60import android.os.Binder;
  61import android.os.Bundle;
  62import android.os.IBinder;
  63import android.os.PowerManager;
  64import android.os.PowerManager.WakeLock;
  65import android.os.SystemClock;
  66import android.preference.PreferenceManager;
  67import android.provider.ContactsContract;
  68import android.util.Log;
  69
  70public class XmppConnectionService extends Service {
  71
  72	protected static final String LOGTAG = "xmppService";
  73	public DatabaseBackend databaseBackend;
  74	private FileBackend fileBackend;
  75
  76	public long startDate;
  77
  78	private static final int PING_MAX_INTERVAL = 300;
  79	private static final int PING_MIN_INTERVAL = 10;
  80	private static final int PING_TIMEOUT = 5;
  81	private static final int CONNECT_TIMEOUT = 60;
  82	private static final long CARBON_GRACE_PERIOD = 60000L;
  83
  84	private static String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
  85
  86	private MessageParser mMessageParser = new MessageParser(this);
  87	private PresenceParser mPresenceParser = new PresenceParser(this);
  88
  89	private List<Account> accounts;
  90	private List<Conversation> conversations = null;
  91	private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
  92			this);
  93
  94	private OnConversationListChangedListener convChangedListener = null;
  95	private int convChangedListenerCount = 0;
  96	private OnAccountListChangedListener accountChangedListener = null;
  97	private OnTLSExceptionReceived tlsException = null;
  98	public OnContactStatusChanged onContactStatusChanged = new OnContactStatusChanged() {
  99
 100		@Override
 101		public void onContactStatusChanged(Contact contact, boolean online) {
 102			Conversation conversation = findActiveConversation(contact);
 103			if (conversation != null) {
 104				conversation.endOtrIfNeeded();
 105				if (online && (contact.getPresences().size() == 1)) {
 106					sendUnsendMessages(conversation);
 107				}
 108			}
 109		}
 110	};
 111
 112	public void setOnTLSExceptionReceivedListener(
 113			OnTLSExceptionReceived listener) {
 114		tlsException = listener;
 115	}
 116
 117	private Random mRandom = new Random(System.currentTimeMillis());
 118
 119	private long lastCarbonMessageReceived = -CARBON_GRACE_PERIOD;
 120
 121	private ContentObserver contactObserver = new ContentObserver(null) {
 122		@Override
 123		public void onChange(boolean selfChange) {
 124			super.onChange(selfChange);
 125			Intent intent = new Intent(getApplicationContext(),
 126					XmppConnectionService.class);
 127			intent.setAction(ACTION_MERGE_PHONE_CONTACTS);
 128			startService(intent);
 129		}
 130	};
 131
 132	private final IBinder mBinder = new XmppConnectionBinder();
 133	private OnMessagePacketReceived messageListener = new OnMessagePacketReceived() {
 134
 135		@Override
 136		public void onMessagePacketReceived(Account account,
 137				MessagePacket packet) {
 138			Message message = null;
 139			boolean notify = true;
 140			if (getPreferences().getBoolean(
 141					"notification_grace_period_after_carbon_received", true)) {
 142				notify = (SystemClock.elapsedRealtime() - lastCarbonMessageReceived) > CARBON_GRACE_PERIOD;
 143			}
 144
 145			if ((packet.getType() == MessagePacket.TYPE_CHAT)) {
 146				if ((packet.getBody() != null)
 147						&& (packet.getBody().startsWith("?OTR"))) {
 148					message = mMessageParser.parseOtrChat(packet, account);
 149					if (message != null) {
 150						message.markUnread();
 151					}
 152				} else if (packet.hasChild("body")) {
 153					message = mMessageParser.parseChat(packet, account);
 154					message.markUnread();
 155				} else if (packet.hasChild("received")
 156						|| (packet.hasChild("sent"))) {
 157					message = mMessageParser
 158							.parseCarbonMessage(packet, account);
 159					if (message != null) {
 160						if (message.getStatus() == Message.STATUS_SEND) {
 161							lastCarbonMessageReceived = SystemClock
 162									.elapsedRealtime();
 163							notify = false;
 164							message.getConversation().markRead();
 165						} else {
 166							message.markUnread();
 167						}
 168					}
 169				}
 170
 171			} else if (packet.getType() == MessagePacket.TYPE_GROUPCHAT) {
 172				message = mMessageParser.parseGroupchat(packet, account);
 173				if (message != null) {
 174					if (message.getStatus() == Message.STATUS_RECIEVED) {
 175						message.markUnread();
 176					} else {
 177						message.getConversation().markRead();
 178						notify = false;
 179					}
 180				}
 181			} else if (packet.getType() == MessagePacket.TYPE_ERROR) {
 182				mMessageParser.parseError(packet, account);
 183				return;
 184			} else if (packet.getType() == MessagePacket.TYPE_NORMAL) {
 185				mMessageParser.parseNormal(packet, account);
 186			}
 187			if ((message == null) || (message.getBody() == null)) {
 188				return;
 189			}
 190			if ((confirmMessages()) && ((packet.getId() != null))) {
 191				MessagePacket receivedPacket = new MessagePacket();
 192				receivedPacket.setType(MessagePacket.TYPE_NORMAL);
 193				receivedPacket.setTo(message.getCounterpart());
 194				receivedPacket.setFrom(account.getFullJid());
 195				if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
 196					Element received = receivedPacket.addChild("received",
 197							"urn:xmpp:chat-markers:0");
 198					received.setAttribute("id", packet.getId());
 199					account.getXmppConnection().sendMessagePacket(
 200							receivedPacket);
 201				} else if (packet.hasChild("request", "urn:xmpp:receipts")) {
 202					Element received = receivedPacket.addChild("received",
 203							"urn:xmpp:receipts");
 204					received.setAttribute("id", packet.getId());
 205					account.getXmppConnection().sendMessagePacket(
 206							receivedPacket);
 207				}
 208			}
 209			Conversation conversation = message.getConversation();
 210			conversation.getMessages().add(message);
 211			if (packet.getType() != MessagePacket.TYPE_ERROR) {
 212				databaseBackend.createMessage(message);
 213			}
 214			if (convChangedListener != null) {
 215				convChangedListener.onConversationListChanged();
 216			} else {
 217				UIHelper.updateNotification(getApplicationContext(),
 218						getConversations(), message.getConversation(), notify);
 219			}
 220		}
 221	};
 222	private OnStatusChanged statusListener = new OnStatusChanged() {
 223
 224		@Override
 225		public void onStatusChanged(Account account) {
 226			if (accountChangedListener != null) {
 227				accountChangedListener.onAccountListChangedListener();
 228			}
 229			if (account.getStatus() == Account.STATUS_ONLINE) {
 230				List<Conversation> conversations = getConversations();
 231				for (int i = 0; i < conversations.size(); ++i) {
 232					if (conversations.get(i).getAccount() == account) {
 233						conversations.get(i).endOtrIfNeeded();
 234						sendUnsendMessages(conversations.get(i));
 235					}
 236				}
 237				syncDirtyContacts(account);
 238				scheduleWakeupCall(PING_MAX_INTERVAL, true);
 239			} else if (account.getStatus() == Account.STATUS_OFFLINE) {
 240				if (!account.isOptionSet(Account.OPTION_DISABLED)) {
 241					int timeToReconnect = mRandom.nextInt(50) + 10;
 242					scheduleWakeupCall(timeToReconnect, false);
 243				}
 244
 245			} else if (account.getStatus() == Account.STATUS_REGISTRATION_SUCCESSFULL) {
 246				databaseBackend.updateAccount(account);
 247				reconnectAccount(account, true);
 248			} else if ((account.getStatus() != Account.STATUS_CONNECTING)
 249					&& (account.getStatus() != Account.STATUS_NO_INTERNET)) {
 250				int next = account.getXmppConnection().getTimeToNextAttempt();
 251				Log.d(LOGTAG, account.getJid()
 252						+ ": error connecting account. try again in " + next
 253						+ "s for the "
 254						+ (account.getXmppConnection().getAttempt() + 1)
 255						+ " time");
 256				scheduleWakeupCall(next, false);
 257			}
 258			UIHelper.showErrorNotification(getApplicationContext(),
 259					getAccounts());
 260		}
 261	};
 262
 263	private OnPresencePacketReceived presenceListener = new OnPresencePacketReceived() {
 264
 265		@Override
 266		public void onPresencePacketReceived(final Account account,
 267				PresencePacket packet) {
 268			if (packet.hasChild("x", "http://jabber.org/protocol/muc#user")) {
 269				mPresenceParser.parseConferencePresence(packet, account);
 270			} else if (packet.hasChild("x", "http://jabber.org/protocol/muc")) {
 271				mPresenceParser.parseConferencePresence(packet, account);
 272			} else {
 273				mPresenceParser.parseContactPresence(packet, account);
 274			}
 275		}
 276	};
 277
 278	private OnIqPacketReceived unknownIqListener = new OnIqPacketReceived() {
 279
 280		@Override
 281		public void onIqPacketReceived(Account account, IqPacket packet) {
 282			if (packet.hasChild("query", "jabber:iq:roster")) {
 283				String from = packet.getFrom();
 284				if ((from == null) || (from.equals(account.getJid()))) {
 285					Element query = packet.findChild("query");
 286					processRosterItems(account, query);
 287				} else {
 288					Log.d(LOGTAG, "unauthorized roster push from: " + from);
 289				}
 290			} else if (packet
 291					.hasChild("open", "http://jabber.org/protocol/ibb")
 292					|| packet
 293							.hasChild("data", "http://jabber.org/protocol/ibb")) {
 294				XmppConnectionService.this.mJingleConnectionManager
 295						.deliverIbbPacket(account, packet);
 296			} else if (packet.hasChild("query",
 297					"http://jabber.org/protocol/disco#info")) {
 298				IqPacket iqResponse = packet
 299						.generateRespone(IqPacket.TYPE_RESULT);
 300				Element query = iqResponse.addChild("query",
 301						"http://jabber.org/protocol/disco#info");
 302				query.addChild("feature").setAttribute("var",
 303						"urn:xmpp:jingle:1");
 304				query.addChild("feature").setAttribute("var",
 305						"urn:xmpp:jingle:apps:file-transfer:3");
 306				query.addChild("feature").setAttribute("var",
 307						"urn:xmpp:jingle:transports:s5b:1");
 308				query.addChild("feature").setAttribute("var",
 309						"urn:xmpp:jingle:transports:ibb:1");
 310				if (confirmMessages()) {
 311					query.addChild("feature").setAttribute("var",
 312							"urn:xmpp:receipts");
 313				}
 314				account.getXmppConnection().sendIqPacket(iqResponse, null);
 315			} else {
 316				if ((packet.getType() == IqPacket.TYPE_GET)
 317						|| (packet.getType() == IqPacket.TYPE_SET)) {
 318					IqPacket response = packet
 319							.generateRespone(IqPacket.TYPE_ERROR);
 320					Element error = response.addChild("error");
 321					error.setAttribute("type", "cancel");
 322					error.addChild("feature-not-implemented",
 323							"urn:ietf:params:xml:ns:xmpp-stanzas");
 324					account.getXmppConnection().sendIqPacket(response, null);
 325				}
 326			}
 327		}
 328	};
 329
 330	private OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
 331
 332		@Override
 333		public void onJinglePacketReceived(Account account, JinglePacket packet) {
 334			mJingleConnectionManager.deliverPacket(account, packet);
 335		}
 336	};
 337
 338	private OpenPgpServiceConnection pgpServiceConnection;
 339	private PgpEngine mPgpEngine = null;
 340	private Intent pingIntent;
 341	private PendingIntent pendingPingIntent = null;
 342	private WakeLock wakeLock;
 343	private PowerManager pm;
 344
 345	public PgpEngine getPgpEngine() {
 346		if (pgpServiceConnection.isBound()) {
 347			if (this.mPgpEngine == null) {
 348				this.mPgpEngine = new PgpEngine(new OpenPgpApi(
 349						getApplicationContext(),
 350						pgpServiceConnection.getService()), this);
 351			}
 352			return mPgpEngine;
 353		} else {
 354			return null;
 355		}
 356
 357	}
 358
 359	public FileBackend getFileBackend() {
 360		return this.fileBackend;
 361	}
 362
 363	public Message attachImageToConversation(final Conversation conversation,
 364			final Uri uri, final UiCallback<Message> callback) {
 365		final Message message;
 366		if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 367			message = new Message(conversation, "",
 368					Message.ENCRYPTION_DECRYPTED);
 369		} else {
 370			message = new Message(conversation, "", Message.ENCRYPTION_NONE);
 371		}
 372		message.setPresence(conversation.getNextPresence());
 373		message.setType(Message.TYPE_IMAGE);
 374		message.setStatus(Message.STATUS_OFFERED);
 375		new Thread(new Runnable() {
 376
 377			@Override
 378			public void run() {
 379				try {
 380					getFileBackend().copyImageToPrivateStorage(message, uri);
 381					if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 382						getPgpEngine().encrypt(message, callback);
 383					} else {
 384						callback.success(message);
 385					}
 386				} catch (FileBackend.ImageCopyException e) {
 387					callback.error(e.getResId(), message);
 388				}
 389			}
 390		}).start();
 391		return message;
 392	}
 393
 394	public Conversation findMuc(String name, Account account) {
 395		for (Conversation conversation : this.conversations) {
 396			if (conversation.getContactJid().split("/")[0].equals(name)
 397					&& (conversation.getAccount() == account)) {
 398				return conversation;
 399			}
 400		}
 401		return null;
 402	}
 403
 404	private void processRosterItems(Account account, Element elements) {
 405		String version = elements.getAttribute("ver");
 406		if (version != null) {
 407			account.getRoster().setVersion(version);
 408		}
 409		for (Element item : elements.getChildren()) {
 410			if (item.getName().equals("item")) {
 411				String jid = item.getAttribute("jid");
 412				String name = item.getAttribute("name");
 413				String subscription = item.getAttribute("subscription");
 414				Contact contact = account.getRoster().getContact(jid);
 415				if (!contact.getOption(Contact.Options.DIRTY_PUSH)) {
 416					contact.setServerName(name);
 417				}
 418				if (subscription.equals("remove")) {
 419					contact.resetOption(Contact.Options.IN_ROSTER);
 420					contact.resetOption(Contact.Options.DIRTY_DELETE);
 421				} else {
 422					contact.setOption(Contact.Options.IN_ROSTER);
 423					contact.parseSubscriptionFromElement(item);
 424				}
 425			}
 426		}
 427	}
 428
 429	public class XmppConnectionBinder extends Binder {
 430		public XmppConnectionService getService() {
 431			return XmppConnectionService.this;
 432		}
 433	}
 434
 435	@Override
 436	public int onStartCommand(Intent intent, int flags, int startId) {
 437		if ((intent != null)
 438				&& (ACTION_MERGE_PHONE_CONTACTS.equals(intent.getAction()))) {
 439			mergePhoneContactsWithRoster();
 440			return START_STICKY;
 441		} else if ((intent != null)
 442				&& (Intent.ACTION_SHUTDOWN.equals(intent.getAction()))) {
 443			logoutAndSave();
 444			return START_NOT_STICKY;
 445		}
 446		this.wakeLock.acquire();
 447		ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
 448				.getSystemService(Context.CONNECTIVITY_SERVICE);
 449		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
 450		boolean isConnected = activeNetwork != null
 451				&& activeNetwork.isConnected();
 452
 453		for (Account account : accounts) {
 454			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
 455				if (!isConnected) {
 456					account.setStatus(Account.STATUS_NO_INTERNET);
 457					if (statusListener != null) {
 458						statusListener.onStatusChanged(account);
 459					}
 460				} else {
 461					if (account.getStatus() == Account.STATUS_NO_INTERNET) {
 462						account.setStatus(Account.STATUS_OFFLINE);
 463						if (statusListener != null) {
 464							statusListener.onStatusChanged(account);
 465						}
 466					}
 467					if (account.getStatus() == Account.STATUS_ONLINE) {
 468						long lastReceived = account.getXmppConnection().lastPaketReceived;
 469						long lastSent = account.getXmppConnection().lastPingSent;
 470						if (lastSent - lastReceived >= PING_TIMEOUT * 1000) {
 471							Log.d(LOGTAG, account.getJid() + ": ping timeout");
 472							this.reconnectAccount(account, true);
 473						} else if (SystemClock.elapsedRealtime() - lastReceived >= PING_MIN_INTERVAL * 1000) {
 474							account.getXmppConnection().sendPing();
 475							account.getXmppConnection().lastPingSent = SystemClock
 476									.elapsedRealtime();
 477							this.scheduleWakeupCall(2, false);
 478						}
 479					} else if (account.getStatus() == Account.STATUS_OFFLINE) {
 480						if (account.getXmppConnection() == null) {
 481							account.setXmppConnection(this
 482									.createConnection(account));
 483						}
 484						account.getXmppConnection().lastPingSent = SystemClock
 485								.elapsedRealtime();
 486						new Thread(account.getXmppConnection()).start();
 487					} else if ((account.getStatus() == Account.STATUS_CONNECTING)
 488							&& ((SystemClock.elapsedRealtime() - account
 489									.getXmppConnection().lastConnect) / 1000 >= CONNECT_TIMEOUT)) {
 490						Log.d(LOGTAG, account.getJid()
 491								+ ": time out during connect reconnecting");
 492						reconnectAccount(account, true);
 493					} else {
 494						if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
 495							reconnectAccount(account, true);
 496						}
 497					}
 498					// in any case. reschedule wakup call
 499					this.scheduleWakeupCall(PING_MAX_INTERVAL, true);
 500				}
 501				if (accountChangedListener != null) {
 502					accountChangedListener.onAccountListChangedListener();
 503				}
 504			}
 505		}
 506		if (wakeLock.isHeld()) {
 507			wakeLock.release();
 508		}
 509		return START_STICKY;
 510	}
 511
 512	@Override
 513	public void onCreate() {
 514		ExceptionHelper.init(getApplicationContext());
 515		this.databaseBackend = DatabaseBackend
 516				.getInstance(getApplicationContext());
 517		this.fileBackend = new FileBackend(getApplicationContext());
 518		this.accounts = databaseBackend.getAccounts();
 519
 520		for (Account account : this.accounts) {
 521			this.databaseBackend.readRoster(account.getRoster());
 522		}
 523		this.mergePhoneContactsWithRoster();
 524		this.getConversations();
 525
 526		getContentResolver().registerContentObserver(
 527				ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
 528		this.pgpServiceConnection = new OpenPgpServiceConnection(
 529				getApplicationContext(), "org.sufficientlysecure.keychain");
 530		this.pgpServiceConnection.bindToService();
 531
 532		this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 533		this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
 534				"XmppConnectionService");
 535	}
 536
 537	@Override
 538	public void onDestroy() {
 539		super.onDestroy();
 540		this.logoutAndSave();
 541	}
 542
 543	@Override
 544	public void onTaskRemoved(Intent rootIntent) {
 545		super.onTaskRemoved(rootIntent);
 546		this.logoutAndSave();
 547	}
 548
 549	private void logoutAndSave() {
 550		for (Account account : accounts) {
 551			databaseBackend.writeRoster(account.getRoster());
 552			if (account.getXmppConnection() != null) {
 553				disconnect(account, false);
 554			}
 555		}
 556		Context context = getApplicationContext();
 557		AlarmManager alarmManager = (AlarmManager) context
 558				.getSystemService(Context.ALARM_SERVICE);
 559		Intent intent = new Intent(context, EventReceiver.class);
 560		alarmManager.cancel(PendingIntent.getBroadcast(context, 0, intent, 0));
 561		Log.d(LOGTAG, "good bye");
 562		stopSelf();
 563	}
 564
 565	protected void scheduleWakeupCall(int seconds, boolean ping) {
 566		long timeToWake = SystemClock.elapsedRealtime() + seconds * 1000;
 567		Context context = getApplicationContext();
 568		AlarmManager alarmManager = (AlarmManager) context
 569				.getSystemService(Context.ALARM_SERVICE);
 570
 571		if (ping) {
 572			if (this.pingIntent == null) {
 573				this.pingIntent = new Intent(context, EventReceiver.class);
 574				this.pingIntent.setAction("ping");
 575				this.pingIntent.putExtra("time", timeToWake);
 576				this.pendingPingIntent = PendingIntent.getBroadcast(context, 0,
 577						this.pingIntent, 0);
 578				alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
 579						timeToWake, pendingPingIntent);
 580			} else {
 581				long scheduledTime = this.pingIntent.getLongExtra("time", 0);
 582				if (scheduledTime < SystemClock.elapsedRealtime()
 583						|| (scheduledTime > timeToWake)) {
 584					this.pingIntent.putExtra("time", timeToWake);
 585					alarmManager.cancel(this.pendingPingIntent);
 586					this.pendingPingIntent = PendingIntent.getBroadcast(
 587							context, 0, this.pingIntent, 0);
 588					alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
 589							timeToWake, pendingPingIntent);
 590				}
 591			}
 592		} else {
 593			Intent intent = new Intent(context, EventReceiver.class);
 594			intent.setAction("ping_check");
 595			PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0,
 596					intent, 0);
 597			alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake,
 598					alarmIntent);
 599		}
 600
 601	}
 602
 603	public XmppConnection createConnection(Account account) {
 604		SharedPreferences sharedPref = getPreferences();
 605		account.setResource(sharedPref.getString("resource", "mobile")
 606				.toLowerCase(Locale.getDefault()));
 607		XmppConnection connection = new XmppConnection(account, this.pm);
 608		connection.setOnMessagePacketReceivedListener(this.messageListener);
 609		connection.setOnStatusChangedListener(this.statusListener);
 610		connection.setOnPresencePacketReceivedListener(this.presenceListener);
 611		connection
 612				.setOnUnregisteredIqPacketReceivedListener(this.unknownIqListener);
 613		connection.setOnJinglePacketReceivedListener(this.jingleListener);
 614		connection
 615				.setOnTLSExceptionReceivedListener(new OnTLSExceptionReceived() {
 616
 617					@Override
 618					public void onTLSExceptionReceived(String fingerprint,
 619							Account account) {
 620						Log.d(LOGTAG, "tls exception arrived in service");
 621						if (tlsException != null) {
 622							tlsException.onTLSExceptionReceived(fingerprint,
 623									account);
 624						}
 625					}
 626				});
 627		connection.setOnBindListener(new OnBindListener() {
 628
 629			@Override
 630			public void onBind(final Account account) {
 631				account.getRoster().clearPresences();
 632				account.clearPresences(); // self presences
 633				fetchRosterFromServer(account);
 634				sendPresence(account);
 635				connectMultiModeConversations(account);
 636				if (convChangedListener != null) {
 637					convChangedListener.onConversationListChanged();
 638				}
 639			}
 640		});
 641		return connection;
 642	}
 643
 644	synchronized public void sendMessage(Message message) {
 645		Account account = message.getConversation().getAccount();
 646		Conversation conv = message.getConversation();
 647		MessagePacket packet = null;
 648		boolean saveInDb = false;
 649		boolean addToConversation = false;
 650		boolean send = false;
 651		if (account.getStatus() == Account.STATUS_ONLINE) {
 652			if (message.getType() == Message.TYPE_IMAGE) {
 653				mJingleConnectionManager.createNewConnection(message);
 654			} else {
 655				if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 656					if (!conv.hasValidOtrSession()&&(message.getPresence() != null)) {
 657						// starting otr session. messages will be send later
 658						conv.startOtrSession(getApplicationContext(),
 659								message.getPresence(), true);
 660					} else if (conv.hasValidOtrSession() && conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
 661						// otr session aleary exists, creating message packet
 662						// accordingly
 663						packet = prepareMessagePacket(account, message,
 664								conv.getOtrSession());
 665						send = true;
 666						message.setStatus(Message.STATUS_SEND);
 667					}  else if (message.getPresence() == null) {
 668						message.setStatus(Message.STATUS_WAITING);
 669					}
 670					saveInDb = true;
 671					addToConversation = true;
 672				} else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
 673					message.getConversation().endOtrIfNeeded();
 674					packet = prepareMessagePacket(account, message, null);
 675					packet.setBody("This is an XEP-0027 encryted message");
 676					packet.addChild("x", "jabber:x:encrypted").setContent(
 677							message.getEncryptedBody());
 678					message.setStatus(Message.STATUS_SEND);
 679					message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 680					saveInDb = true;
 681					addToConversation = true;
 682					send = true;
 683				} else {
 684					message.getConversation().endOtrIfNeeded();
 685					// don't encrypt
 686					if (message.getConversation().getMode() == Conversation.MODE_SINGLE) {
 687						message.setStatus(Message.STATUS_SEND);
 688					}
 689					packet = prepareMessagePacket(account, message, null);
 690					send = true;
 691					saveInDb = true;
 692					addToConversation = true;
 693				}
 694			}
 695		} else {
 696			if (message.getEncryption() == Message.ENCRYPTION_PGP) {
 697				String pgpBody = message.getEncryptedBody();
 698				String decryptedBody = message.getBody();
 699				message.setBody(pgpBody);
 700				databaseBackend.createMessage(message);
 701				message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 702				message.setBody(decryptedBody);
 703				addToConversation = true;
 704			} else if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 705				if (conv.hasValidOtrSession()) {
 706					message.setPresence(conv.getOtrSession().getSessionID()
 707							.getUserID());
 708				} else if (!conv.hasValidOtrSession() && message.getPresence() != null) {
 709					conv.startOtrSession(getApplicationContext(),
 710							message.getPresence(), false);
 711				} else if (message.getPresence() == null) {
 712					message.setStatus(Message.STATUS_WAITING);
 713				}
 714				saveInDb = true;
 715				addToConversation = true;
 716			} else {
 717				saveInDb = true;
 718				addToConversation = true;
 719			}
 720
 721		}
 722		if (saveInDb) {
 723			databaseBackend.createMessage(message);
 724		}
 725		if (addToConversation) {
 726			conv.getMessages().add(message);
 727			if (convChangedListener != null) {
 728				convChangedListener.onConversationListChanged();
 729			}
 730		}
 731		if ((send) && (packet != null)) {
 732			account.getXmppConnection().sendMessagePacket(packet);
 733		}
 734
 735	}
 736
 737	private void sendUnsendMessages(Conversation conversation) {
 738		for (int i = 0; i < conversation.getMessages().size(); ++i) {
 739			int status = conversation.getMessages().get(i).getStatus();
 740			if ((status == Message.STATUS_UNSEND)
 741					|| (status == Message.STATUS_WAITING)) {
 742				resendMessage(conversation.getMessages().get(i));
 743			}
 744		}
 745	}
 746
 747	private void resendMessage(Message message) {
 748		Account account = message.getConversation().getAccount();
 749		if (message.getType() == Message.TYPE_TEXT) {
 750			MessagePacket packet = null;
 751			if (message.getEncryption() == Message.ENCRYPTION_NONE) {
 752				packet = prepareMessagePacket(account, message, null);
 753			} else if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 754				packet = prepareMessagePacket(account, message, null);
 755				packet.setBody("This is an XEP-0027 encryted message");
 756				if (message.getEncryptedBody() == null) {
 757					markMessage(message, Message.STATUS_SEND_FAILED);
 758					return;
 759				}
 760				packet.addChild("x", "jabber:x:encrypted").setContent(
 761						message.getEncryptedBody());
 762			} else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
 763				packet = prepareMessagePacket(account, message, null);
 764				packet.setBody("This is an XEP-0027 encryted message");
 765				packet.addChild("x", "jabber:x:encrypted").setContent(
 766						message.getBody());
 767			} else if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 768				Presences presences = message.getConversation().getContact()
 769						.getPresences();
 770				if (!message.getConversation().hasValidOtrSession()) {
 771					if ((message.getPresence() != null)
 772							&& (presences.has(message.getPresence()))) {
 773						message.getConversation().startOtrSession(
 774								getApplicationContext(), message.getPresence(),
 775								true);
 776					} else {
 777						if (presences.size() == 1) {
 778							String presence = presences.asStringArray()[0];
 779							message.getConversation().startOtrSession(
 780									getApplicationContext(), presence, true);
 781						}
 782					}
 783				}
 784			}
 785			if (packet != null) {
 786				account.getXmppConnection().sendMessagePacket(packet);
 787				markMessage(message, Message.STATUS_SEND);
 788			}
 789		} else if (message.getType() == Message.TYPE_IMAGE) {
 790			// TODO: send images
 791
 792		}
 793	}
 794
 795	public MessagePacket prepareMessagePacket(Account account, Message message,
 796			Session otrSession) {
 797		MessagePacket packet = new MessagePacket();
 798		if (message.getConversation().getMode() == Conversation.MODE_SINGLE) {
 799			packet.setType(MessagePacket.TYPE_CHAT);
 800			if (otrSession != null) {
 801				try {
 802					packet.setBody(otrSession.transformSending(message
 803							.getBody()));
 804				} catch (OtrException e) {
 805					Log.d(LOGTAG,
 806							account.getJid()
 807									+ ": could not encrypt message to "
 808									+ message.getCounterpart());
 809				}
 810				packet.addChild("private", "urn:xmpp:carbons:2");
 811				packet.addChild("no-copy", "urn:xmpp:hints");
 812				packet.setTo(otrSession.getSessionID().getAccountID() + "/"
 813						+ otrSession.getSessionID().getUserID());
 814				packet.setFrom(account.getFullJid());
 815			} else {
 816				packet.setBody(message.getBody());
 817				packet.setTo(message.getCounterpart());
 818				packet.setFrom(account.getJid());
 819			}
 820			packet.addChild("markable", "urn:xmpp:chat-markers:0");
 821		} else if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
 822			packet.setType(MessagePacket.TYPE_GROUPCHAT);
 823			packet.setBody(message.getBody());
 824			packet.setTo(message.getCounterpart().split("/")[0]);
 825			packet.setFrom(account.getJid());
 826		}
 827		packet.setId(message.getUuid());
 828		return packet;
 829	}
 830
 831	public void fetchRosterFromServer(Account account) {
 832		IqPacket iqPacket = new IqPacket(IqPacket.TYPE_GET);
 833		if (!"".equals(account.getRosterVersion())) {
 834			Log.d(LOGTAG, account.getJid() + ": fetching roster version "
 835					+ account.getRosterVersion());
 836		} else {
 837			Log.d(LOGTAG, account.getJid() + ": fetching roster");
 838		}
 839		iqPacket.query("jabber:iq:roster").setAttribute("ver",
 840				account.getRosterVersion());
 841		account.getXmppConnection().sendIqPacket(iqPacket,
 842				new OnIqPacketReceived() {
 843
 844					@Override
 845					public void onIqPacketReceived(final Account account,
 846							IqPacket packet) {
 847						Element roster = packet.findChild("query");
 848						if (roster != null) {
 849							account.getRoster().markAllAsNotInRoster();
 850							processRosterItems(account, roster);
 851						}
 852					}
 853				});
 854	}
 855
 856	private void mergePhoneContactsWithRoster() {
 857		PhoneHelper.loadPhoneContacts(getApplicationContext(),
 858				new OnPhoneContactsLoadedListener() {
 859					@Override
 860					public void onPhoneContactsLoaded(List<Bundle> phoneContacts) {
 861						for (Account account : accounts) {
 862							account.getRoster().clearSystemAccounts();
 863						}
 864						for (Bundle phoneContact : phoneContacts) {
 865							for (Account account : accounts) {
 866								String jid = phoneContact.getString("jid");
 867								Contact contact = account.getRoster()
 868										.getContact(jid);
 869								String systemAccount = phoneContact
 870										.getInt("phoneid")
 871										+ "#"
 872										+ phoneContact.getString("lookup");
 873								contact.setSystemAccount(systemAccount);
 874								contact.setPhotoUri(phoneContact
 875										.getString("photouri"));
 876								contact.setSystemName(phoneContact
 877										.getString("displayname"));
 878							}
 879						}
 880					}
 881				});
 882	}
 883
 884	public List<Conversation> getConversations() {
 885		if (this.conversations == null) {
 886			Hashtable<String, Account> accountLookupTable = new Hashtable<String, Account>();
 887			for (Account account : this.accounts) {
 888				accountLookupTable.put(account.getUuid(), account);
 889			}
 890			this.conversations = databaseBackend
 891					.getConversations(Conversation.STATUS_AVAILABLE);
 892			for (Conversation conv : this.conversations) {
 893				Account account = accountLookupTable.get(conv.getAccountUuid());
 894				conv.setAccount(account);
 895				conv.setMessages(databaseBackend.getMessages(conv, 50));
 896			}
 897		}
 898		Collections.sort(this.conversations, new Comparator<Conversation>() {
 899			@Override
 900			public int compare(Conversation lhs, Conversation rhs) {
 901				Message left = lhs.getLatestMessage();
 902				Message right = rhs.getLatestMessage();
 903				if (left.getTimeSent() > right.getTimeSent()) {
 904					return -1;
 905				} else if (left.getTimeSent() < right.getTimeSent()) {
 906					return 1;
 907				} else {
 908					return 0;
 909				}
 910			}
 911		});
 912		return this.conversations;
 913	}
 914
 915	public List<Account> getAccounts() {
 916		return this.accounts;
 917	}
 918
 919	public Conversation findActiveConversation(Contact contact) {
 920		for (Conversation conversation : this.getConversations()) {
 921			if (conversation.getContact() == contact) {
 922				return conversation;
 923			}
 924		}
 925		return null;
 926	}
 927
 928	public Conversation findOrCreateConversation(Account account, String jid,
 929			boolean muc) {
 930		for (Conversation conv : this.getConversations()) {
 931			if ((conv.getAccount().equals(account))
 932					&& (conv.getContactJid().split("/")[0].equals(jid))) {
 933				return conv;
 934			}
 935		}
 936		Conversation conversation = databaseBackend.findConversation(account,
 937				jid);
 938		if (conversation != null) {
 939			conversation.setStatus(Conversation.STATUS_AVAILABLE);
 940			conversation.setAccount(account);
 941			if (muc) {
 942				conversation.setMode(Conversation.MODE_MULTI);
 943			} else {
 944				conversation.setMode(Conversation.MODE_SINGLE);
 945			}
 946			conversation.setMessages(databaseBackend.getMessages(conversation,
 947					50));
 948			this.databaseBackend.updateConversation(conversation);
 949		} else {
 950			String conversationName;
 951			Contact contact = account.getRoster().getContact(jid);
 952			if (contact != null) {
 953				conversationName = contact.getDisplayName();
 954			} else {
 955				conversationName = jid.split("@")[0];
 956			}
 957			if (muc) {
 958				conversation = new Conversation(conversationName, account, jid,
 959						Conversation.MODE_MULTI);
 960			} else {
 961				conversation = new Conversation(conversationName, account, jid,
 962						Conversation.MODE_SINGLE);
 963			}
 964			this.databaseBackend.createConversation(conversation);
 965		}
 966		this.conversations.add(conversation);
 967		if ((account.getStatus() == Account.STATUS_ONLINE)
 968				&& (conversation.getMode() == Conversation.MODE_MULTI)) {
 969			joinMuc(conversation);
 970		}
 971		if (this.convChangedListener != null) {
 972			this.convChangedListener.onConversationListChanged();
 973		}
 974		return conversation;
 975	}
 976
 977	public void archiveConversation(Conversation conversation) {
 978		if (conversation.getMode() == Conversation.MODE_MULTI) {
 979			leaveMuc(conversation);
 980		} else {
 981			conversation.endOtrIfNeeded();
 982		}
 983		this.databaseBackend.updateConversation(conversation);
 984		this.conversations.remove(conversation);
 985		if (this.convChangedListener != null) {
 986			this.convChangedListener.onConversationListChanged();
 987		}
 988	}
 989
 990	public void clearConversationHistory(Conversation conversation) {
 991		this.databaseBackend.deleteMessagesInConversation(conversation);
 992		this.fileBackend.removeFiles(conversation);
 993		conversation.getMessages().clear();
 994		if (this.convChangedListener != null) {
 995			this.convChangedListener.onConversationListChanged();
 996		}
 997	}
 998
 999	public int getConversationCount() {
1000		return this.databaseBackend.getConversationCount();
1001	}
1002
1003	public void createAccount(Account account) {
1004		databaseBackend.createAccount(account);
1005		this.accounts.add(account);
1006		this.reconnectAccount(account, false);
1007		if (accountChangedListener != null)
1008			accountChangedListener.onAccountListChangedListener();
1009	}
1010
1011	public void updateAccount(Account account) {
1012		this.statusListener.onStatusChanged(account);
1013		databaseBackend.updateAccount(account);
1014		reconnectAccount(account, false);
1015		if (accountChangedListener != null) {
1016			accountChangedListener.onAccountListChangedListener();
1017		}
1018		UIHelper.showErrorNotification(getApplicationContext(), getAccounts());
1019	}
1020
1021	public void deleteAccount(Account account) {
1022		if (account.getXmppConnection() != null) {
1023			this.disconnect(account, true);
1024		}
1025		databaseBackend.deleteAccount(account);
1026		this.accounts.remove(account);
1027		if (accountChangedListener != null) {
1028			accountChangedListener.onAccountListChangedListener();
1029		}
1030		UIHelper.showErrorNotification(getApplicationContext(), getAccounts());
1031	}
1032
1033	public void setOnConversationListChangedListener(
1034			OnConversationListChangedListener listener) {
1035		this.convChangedListener = listener;
1036		this.convChangedListenerCount++;
1037	}
1038
1039	public void removeOnConversationListChangedListener() {
1040		this.convChangedListenerCount--;
1041		if (this.convChangedListenerCount == 0) {
1042			this.convChangedListener = null;
1043		}
1044	}
1045
1046	public void setOnAccountListChangedListener(
1047			OnAccountListChangedListener listener) {
1048		this.accountChangedListener = listener;
1049	}
1050
1051	public void removeOnAccountListChangedListener() {
1052		this.accountChangedListener = null;
1053	}
1054
1055	public void connectMultiModeConversations(Account account) {
1056		List<Conversation> conversations = getConversations();
1057		for (int i = 0; i < conversations.size(); i++) {
1058			Conversation conversation = conversations.get(i);
1059			if ((conversation.getMode() == Conversation.MODE_MULTI)
1060					&& (conversation.getAccount() == account)) {
1061				joinMuc(conversation);
1062			}
1063		}
1064	}
1065
1066	public void joinMuc(Conversation conversation) {
1067		Account account = conversation.getAccount();
1068		String[] mucParts = conversation.getContactJid().split("/");
1069		String muc;
1070		String nick;
1071		if (mucParts.length == 2) {
1072			muc = mucParts[0];
1073			nick = mucParts[1];
1074		} else {
1075			muc = mucParts[0];
1076			nick = account.getUsername();
1077		}
1078		PresencePacket packet = new PresencePacket();
1079		packet.setAttribute("to", muc + "/" + nick);
1080		Element x = new Element("x");
1081		x.setAttribute("xmlns", "http://jabber.org/protocol/muc");
1082		String sig = account.getPgpSignature();
1083		if (sig != null) {
1084			packet.addChild("status").setContent("online");
1085			packet.addChild("x", "jabber:x:signed").setContent(sig);
1086		}
1087		if (conversation.getMessages().size() != 0) {
1088			long lastMsgTime = conversation.getLatestMessage().getTimeSent();
1089			long diff = (System.currentTimeMillis() - lastMsgTime) / 1000 - 1;
1090			x.addChild("history").setAttribute("seconds", diff + "");
1091		}
1092		packet.addChild(x);
1093		account.getXmppConnection().sendPresencePacket(packet);
1094	}
1095
1096	private OnRenameListener renameListener = null;
1097
1098	public void setOnRenameListener(OnRenameListener listener) {
1099		this.renameListener = listener;
1100	}
1101
1102	public void renameInMuc(final Conversation conversation, final String nick) {
1103		final MucOptions options = conversation.getMucOptions();
1104		if (options.online()) {
1105			Account account = conversation.getAccount();
1106			options.setOnRenameListener(new OnRenameListener() {
1107
1108				@Override
1109				public void onRename(boolean success) {
1110					if (renameListener != null) {
1111						renameListener.onRename(success);
1112					}
1113					if (success) {
1114						String jid = conversation.getContactJid().split("/")[0]
1115								+ "/" + nick;
1116						conversation.setContactJid(jid);
1117						databaseBackend.updateConversation(conversation);
1118					}
1119				}
1120			});
1121			options.flagAboutToRename();
1122			PresencePacket packet = new PresencePacket();
1123			packet.setAttribute("to",
1124					conversation.getContactJid().split("/")[0] + "/" + nick);
1125			packet.setAttribute("from", conversation.getAccount().getFullJid());
1126
1127			String sig = account.getPgpSignature();
1128			if (sig != null) {
1129				packet.addChild("status").setContent("online");
1130				packet.addChild("x", "jabber:x:signed").setContent(sig);
1131			}
1132
1133			account.getXmppConnection().sendPresencePacket(packet, null);
1134		} else {
1135			String jid = conversation.getContactJid().split("/")[0] + "/"
1136					+ nick;
1137			conversation.setContactJid(jid);
1138			databaseBackend.updateConversation(conversation);
1139			if (conversation.getAccount().getStatus() == Account.STATUS_ONLINE) {
1140				joinMuc(conversation);
1141			}
1142		}
1143	}
1144
1145	public void leaveMuc(Conversation conversation) {
1146		PresencePacket packet = new PresencePacket();
1147		packet.setAttribute("to", conversation.getContactJid().split("/")[0]
1148				+ "/" + conversation.getMucOptions().getNick());
1149		packet.setAttribute("from", conversation.getAccount().getFullJid());
1150		packet.setAttribute("type", "unavailable");
1151		Log.d(LOGTAG, "send leaving muc " + packet);
1152		conversation.getAccount().getXmppConnection()
1153				.sendPresencePacket(packet);
1154		conversation.getMucOptions().setOffline();
1155	}
1156
1157	public void disconnect(Account account, boolean force) {
1158		if ((account.getStatus() == Account.STATUS_ONLINE)
1159				|| (account.getStatus() == Account.STATUS_DISABLED)) {
1160			if (!force) {
1161				List<Conversation> conversations = getConversations();
1162				for (int i = 0; i < conversations.size(); i++) {
1163					Conversation conversation = conversations.get(i);
1164					if (conversation.getAccount() == account) {
1165						if (conversation.getMode() == Conversation.MODE_MULTI) {
1166							leaveMuc(conversation);
1167						} else {
1168							conversation.endOtrIfNeeded();
1169						}
1170					}
1171				}
1172			}
1173			account.getXmppConnection().disconnect(force);
1174		}
1175	}
1176
1177	@Override
1178	public IBinder onBind(Intent intent) {
1179		return mBinder;
1180	}
1181
1182	public void updateMessage(Message message) {
1183		databaseBackend.updateMessage(message);
1184	}
1185
1186	protected void syncDirtyContacts(Account account) {
1187		for (Contact contact : account.getRoster().getContacts()) {
1188			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1189				pushContactToServer(contact);
1190			}
1191			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1192				Log.d(LOGTAG, "dirty delete");
1193				deleteContactOnServer(contact);
1194			}
1195		}
1196	}
1197
1198	public void createContact(Contact contact) {
1199		SharedPreferences sharedPref = getPreferences();
1200		boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1201		if (autoGrant) {
1202			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1203			contact.setOption(Contact.Options.ASKING);
1204		}
1205		pushContactToServer(contact);
1206	}
1207
1208	public void onOtrSessionEstablished(Conversation conversation) {
1209		Account account = conversation.getAccount();
1210		List<Message> messages = conversation.getMessages();
1211		Session otrSession = conversation.getOtrSession();
1212		Log.d(LOGTAG, account.getJid() + " otr session established with "
1213				+ conversation.getContactJid() + "/"
1214				+ otrSession.getSessionID().getUserID());
1215		for (int i = 0; i < messages.size(); ++i) {
1216			Message msg = messages.get(i);
1217			if ((msg.getStatus() == Message.STATUS_UNSEND || msg.getStatus() == Message.STATUS_WAITING)
1218					&& (msg.getEncryption() == Message.ENCRYPTION_OTR)) {
1219				MessagePacket outPacket = prepareMessagePacket(account, msg,
1220						otrSession);
1221				msg.setStatus(Message.STATUS_SEND);
1222				databaseBackend.updateMessage(msg);
1223				account.getXmppConnection().sendMessagePacket(outPacket);
1224			}
1225		}
1226		updateUi(conversation, false);
1227	}
1228
1229	public void pushContactToServer(Contact contact) {
1230		contact.resetOption(Contact.Options.DIRTY_DELETE);
1231		Account account = contact.getAccount();
1232		if (account.getStatus() == Account.STATUS_ONLINE) {
1233			IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
1234			iq.query("jabber:iq:roster").addChild(contact.asElement());
1235			account.getXmppConnection().sendIqPacket(iq, null);
1236			if (contact.getOption(Contact.Options.ASKING)) {
1237				requestPresenceUpdatesFrom(contact);
1238			}
1239			if (contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1240				Log.d("xmppService", "contact had pending subscription");
1241				sendPresenceUpdatesTo(contact);
1242			}
1243			contact.resetOption(Contact.Options.DIRTY_PUSH);
1244		} else {
1245			contact.setOption(Contact.Options.DIRTY_PUSH);
1246		}
1247	}
1248
1249	public void deleteContactOnServer(Contact contact) {
1250		contact.resetOption(Contact.Options.DIRTY_PUSH);
1251		Account account = contact.getAccount();
1252		if (account.getStatus() == Account.STATUS_ONLINE) {
1253			IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
1254			Element item = iq.query("jabber:iq:roster").addChild("item");
1255			item.setAttribute("jid", contact.getJid());
1256			item.setAttribute("subscription", "remove");
1257			account.getXmppConnection().sendIqPacket(iq, null);
1258			contact.resetOption(Contact.Options.DIRTY_DELETE);
1259		} else {
1260			contact.setOption(Contact.Options.DIRTY_DELETE);
1261		}
1262	}
1263
1264	public void requestPresenceUpdatesFrom(Contact contact) {
1265		PresencePacket packet = new PresencePacket();
1266		packet.setAttribute("type", "subscribe");
1267		packet.setAttribute("to", contact.getJid());
1268		packet.setAttribute("from", contact.getAccount().getJid());
1269		contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1270	}
1271
1272	public void stopPresenceUpdatesFrom(Contact contact) {
1273		PresencePacket packet = new PresencePacket();
1274		packet.setAttribute("type", "unsubscribe");
1275		packet.setAttribute("to", contact.getJid());
1276		packet.setAttribute("from", contact.getAccount().getJid());
1277		contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1278	}
1279
1280	public void stopPresenceUpdatesTo(Contact contact) {
1281		PresencePacket packet = new PresencePacket();
1282		packet.setAttribute("type", "unsubscribed");
1283		packet.setAttribute("to", contact.getJid());
1284		packet.setAttribute("from", contact.getAccount().getJid());
1285		contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1286	}
1287
1288	public void sendPresenceUpdatesTo(Contact contact) {
1289		PresencePacket packet = new PresencePacket();
1290		packet.setAttribute("type", "subscribed");
1291		packet.setAttribute("to", contact.getJid());
1292		packet.setAttribute("from", contact.getAccount().getJid());
1293		contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1294	}
1295
1296	public void sendPresence(Account account) {
1297		PresencePacket packet = new PresencePacket();
1298		packet.setAttribute("from", account.getFullJid());
1299		String sig = account.getPgpSignature();
1300		if (sig != null) {
1301			packet.addChild("status").setContent("online");
1302			packet.addChild("x", "jabber:x:signed").setContent(sig);
1303		}
1304		account.getXmppConnection().sendPresencePacket(packet);
1305	}
1306
1307	public void updateConversation(Conversation conversation) {
1308		this.databaseBackend.updateConversation(conversation);
1309	}
1310
1311	public void removeOnTLSExceptionReceivedListener() {
1312		this.tlsException = null;
1313	}
1314
1315	public void reconnectAccount(final Account account, final boolean force) {
1316		new Thread(new Runnable() {
1317
1318			@Override
1319			public void run() {
1320				if (account.getXmppConnection() != null) {
1321					disconnect(account, force);
1322				}
1323				if (!account.isOptionSet(Account.OPTION_DISABLED)) {
1324					if (account.getXmppConnection() == null) {
1325						account.setXmppConnection(createConnection(account));
1326					}
1327					Thread thread = new Thread(account.getXmppConnection());
1328					thread.start();
1329					scheduleWakeupCall((int) (CONNECT_TIMEOUT * 1.2), false);
1330				}
1331			}
1332		}).start();
1333	}
1334
1335	public void sendConversationSubject(Conversation conversation,
1336			String subject) {
1337		MessagePacket packet = new MessagePacket();
1338		packet.setType(MessagePacket.TYPE_GROUPCHAT);
1339		packet.setTo(conversation.getContactJid().split("/")[0]);
1340		Element subjectChild = new Element("subject");
1341		subjectChild.setContent(subject);
1342		packet.addChild(subjectChild);
1343		packet.setFrom(conversation.getAccount().getJid());
1344		Account account = conversation.getAccount();
1345		if (account.getStatus() == Account.STATUS_ONLINE) {
1346			account.getXmppConnection().sendMessagePacket(packet);
1347		}
1348	}
1349
1350	public void inviteToConference(Conversation conversation,
1351			List<Contact> contacts) {
1352		for (Contact contact : contacts) {
1353			MessagePacket packet = new MessagePacket();
1354			packet.setTo(conversation.getContactJid().split("/")[0]);
1355			packet.setFrom(conversation.getAccount().getFullJid());
1356			Element x = new Element("x");
1357			x.setAttribute("xmlns", "http://jabber.org/protocol/muc#user");
1358			Element invite = new Element("invite");
1359			invite.setAttribute("to", contact.getJid());
1360			x.addChild(invite);
1361			packet.addChild(x);
1362			Log.d(LOGTAG, packet.toString());
1363			conversation.getAccount().getXmppConnection()
1364					.sendMessagePacket(packet);
1365		}
1366
1367	}
1368
1369	public boolean markMessage(Account account, String recipient, String uuid,
1370			int status) {
1371		for (Conversation conversation : getConversations()) {
1372			if (conversation.getContactJid().equals(recipient)
1373					&& conversation.getAccount().equals(account)) {
1374				return markMessage(conversation, uuid, status);
1375			}
1376		}
1377		return false;
1378	}
1379
1380	public boolean markMessage(Conversation conversation, String uuid,
1381			int status) {
1382		for (Message message : conversation.getMessages()) {
1383			if (message.getUuid().equals(uuid)) {
1384				markMessage(message, status);
1385				return true;
1386			}
1387		}
1388		return false;
1389	}
1390
1391	public void markMessage(Message message, int status) {
1392		message.setStatus(status);
1393		databaseBackend.updateMessage(message);
1394		if (convChangedListener != null) {
1395			convChangedListener.onConversationListChanged();
1396		}
1397	}
1398
1399	public SharedPreferences getPreferences() {
1400		return PreferenceManager
1401				.getDefaultSharedPreferences(getApplicationContext());
1402	}
1403
1404	public boolean confirmMessages() {
1405		return getPreferences().getBoolean("confirm_messages", true);
1406	}
1407
1408	public void updateUi(Conversation conversation, boolean notify) {
1409		if (convChangedListener != null) {
1410			convChangedListener.onConversationListChanged();
1411		} else {
1412			UIHelper.updateNotification(getApplicationContext(),
1413					getConversations(), conversation, notify);
1414		}
1415	}
1416
1417	public Account findAccountByJid(String accountJid) {
1418		for (Account account : this.accounts) {
1419			if (account.getJid().equals(accountJid)) {
1420				return account;
1421			}
1422		}
1423		return null;
1424	}
1425
1426	public void markRead(Conversation conversation) {
1427		conversation.markRead(this);
1428	}
1429
1430	public void sendConfirmMessage(Account account, String to, String id) {
1431		MessagePacket receivedPacket = new MessagePacket();
1432		receivedPacket.setType(MessagePacket.TYPE_NORMAL);
1433		receivedPacket.setTo(to);
1434		receivedPacket.setFrom(account.getFullJid());
1435		Element received = receivedPacket.addChild("displayed",
1436				"urn:xmpp:chat-markers:0");
1437		received.setAttribute("id", id);
1438		account.getXmppConnection().sendMessagePacket(receivedPacket);
1439	}
1440}