XmppConnectionService.java

   1package eu.siacs.conversations.services;
   2
   3import android.annotation.SuppressLint;
   4import android.app.AlarmManager;
   5import android.app.PendingIntent;
   6import android.app.Service;
   7import android.content.Context;
   8import android.content.Intent;
   9import android.content.SharedPreferences;
  10import android.database.ContentObserver;
  11import android.graphics.Bitmap;
  12import android.net.ConnectivityManager;
  13import android.net.NetworkInfo;
  14import android.net.Uri;
  15import android.os.Binder;
  16import android.os.Bundle;
  17import android.os.FileObserver;
  18import android.os.IBinder;
  19import android.os.PowerManager;
  20import android.os.PowerManager.WakeLock;
  21import android.os.SystemClock;
  22import android.preference.PreferenceManager;
  23import android.provider.ContactsContract;
  24import android.util.Log;
  25import android.util.LruCache;
  26
  27import net.java.otr4j.OtrException;
  28import net.java.otr4j.session.Session;
  29import net.java.otr4j.session.SessionID;
  30import net.java.otr4j.session.SessionStatus;
  31
  32import org.openintents.openpgp.util.OpenPgpApi;
  33import org.openintents.openpgp.util.OpenPgpServiceConnection;
  34
  35import java.math.BigInteger;
  36import java.security.SecureRandom;
  37import java.util.ArrayList;
  38import java.util.Collections;
  39import java.util.Comparator;
  40import java.util.Hashtable;
  41import java.util.List;
  42import java.util.Locale;
  43import java.util.concurrent.CopyOnWriteArrayList;
  44
  45import de.duenndns.ssl.MemorizingTrustManager;
  46import eu.siacs.conversations.Config;
  47import eu.siacs.conversations.R;
  48import eu.siacs.conversations.crypto.PgpEngine;
  49import eu.siacs.conversations.entities.Account;
  50import eu.siacs.conversations.entities.Bookmark;
  51import eu.siacs.conversations.entities.Contact;
  52import eu.siacs.conversations.entities.Conversation;
  53import eu.siacs.conversations.entities.Downloadable;
  54import eu.siacs.conversations.entities.DownloadableFile;
  55import eu.siacs.conversations.entities.DownloadablePlaceholder;
  56import eu.siacs.conversations.entities.Message;
  57import eu.siacs.conversations.entities.MucOptions;
  58import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
  59import eu.siacs.conversations.entities.Presences;
  60import eu.siacs.conversations.generator.IqGenerator;
  61import eu.siacs.conversations.generator.MessageGenerator;
  62import eu.siacs.conversations.generator.PresenceGenerator;
  63import eu.siacs.conversations.http.HttpConnectionManager;
  64import eu.siacs.conversations.parser.IqParser;
  65import eu.siacs.conversations.parser.MessageParser;
  66import eu.siacs.conversations.parser.PresenceParser;
  67import eu.siacs.conversations.persistance.DatabaseBackend;
  68import eu.siacs.conversations.persistance.FileBackend;
  69import eu.siacs.conversations.ui.UiCallback;
  70import eu.siacs.conversations.utils.CryptoHelper;
  71import eu.siacs.conversations.utils.ExceptionHelper;
  72import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
  73import eu.siacs.conversations.utils.PRNGFixes;
  74import eu.siacs.conversations.utils.PhoneHelper;
  75import eu.siacs.conversations.xml.Element;
  76import eu.siacs.conversations.xmpp.OnBindListener;
  77import eu.siacs.conversations.xmpp.OnContactStatusChanged;
  78import eu.siacs.conversations.xmpp.OnIqPacketReceived;
  79import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
  80import eu.siacs.conversations.xmpp.OnStatusChanged;
  81import eu.siacs.conversations.xmpp.XmppConnection;
  82import eu.siacs.conversations.xmpp.forms.Data;
  83import eu.siacs.conversations.xmpp.forms.Field;
  84import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  85import eu.siacs.conversations.xmpp.jid.Jid;
  86import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
  87import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
  88import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
  89import eu.siacs.conversations.xmpp.pep.Avatar;
  90import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  91import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
  92import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
  93
  94public class XmppConnectionService extends Service {
  95
  96	public static String ACTION_CLEAR_NOTIFICATION = "clear_notification";
  97	private static String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
  98	public static String ACTION_DISABLE_FOREGROUND = "disable_foreground";
  99	private ContentObserver contactObserver = new ContentObserver(null) {
 100		@Override
 101		public void onChange(boolean selfChange) {
 102			super.onChange(selfChange);
 103			Intent intent = new Intent(getApplicationContext(),
 104					XmppConnectionService.class);
 105			intent.setAction(ACTION_MERGE_PHONE_CONTACTS);
 106			startService(intent);
 107		}
 108	};
 109	private final IBinder mBinder = new XmppConnectionBinder();
 110	public DatabaseBackend databaseBackend;
 111	public OnContactStatusChanged onContactStatusChanged = new OnContactStatusChanged() {
 112
 113		@Override
 114		public void onContactStatusChanged(Contact contact, boolean online) {
 115			Conversation conversation = find(getConversations(), contact);
 116			if (conversation != null) {
 117				if (online && contact.getPresences().size() > 1) {
 118					conversation.endOtrIfNeeded();
 119				} else {
 120					conversation.resetOtrSession();
 121				}
 122				if (online && (contact.getPresences().size() == 1)) {
 123					sendUnsendMessages(conversation);
 124				}
 125			}
 126		}
 127	};
 128	private FileBackend fileBackend = new FileBackend(this);
 129	private MemorizingTrustManager mMemorizingTrustManager;
 130	private NotificationService mNotificationService = new NotificationService(
 131			this);
 132	private MessageParser mMessageParser = new MessageParser(this);
 133	private PresenceParser mPresenceParser = new PresenceParser(this);
 134	private IqParser mIqParser = new IqParser(this);
 135	private MessageGenerator mMessageGenerator = new MessageGenerator(this);
 136	private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
 137	private List<Account> accounts;
 138	private final CopyOnWriteArrayList<Conversation> conversations = new CopyOnWriteArrayList<Conversation>();
 139	private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
 140			this);
 141	private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(
 142			this);
 143	private AvatarService mAvatarService = new AvatarService(this);
 144	private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
 145	private OnConversationUpdate mOnConversationUpdate = null;
 146	private Integer convChangedListenerCount = 0;
 147	private OnAccountUpdate mOnAccountUpdate = null;
 148	private OnStatusChanged statusListener = new OnStatusChanged() {
 149
 150		@Override
 151		public void onStatusChanged(Account account) {
 152			XmppConnection connection = account.getXmppConnection();
 153			if (mOnAccountUpdate != null) {
 154				mOnAccountUpdate.onAccountUpdate();
 155			}
 156			if (account.getStatus() == Account.State.ONLINE) {
 157				for (Conversation conversation : account.pendingConferenceLeaves) {
 158					leaveMuc(conversation);
 159				}
 160				for (Conversation conversation : account.pendingConferenceJoins) {
 161					joinMuc(conversation);
 162				}
 163				mJingleConnectionManager.cancelInTransmission();
 164				List<Conversation> conversations = getConversations();
 165				for (Conversation conversation : conversations) {
 166					if (conversation.getAccount() == account) {
 167						conversation.startOtrIfNeeded();
 168						sendUnsendMessages(conversation);
 169					}
 170				}
 171				if (connection != null && connection.getFeatures().csi()) {
 172					if (checkListeners()) {
 173						Log.d(Config.LOGTAG, account.getJid().toBareJid()
 174								+ " sending csi//inactive");
 175						connection.sendInactive();
 176					} else {
 177						Log.d(Config.LOGTAG, account.getJid().toBareJid()
 178								+ " sending csi//active");
 179						connection.sendActive();
 180					}
 181				}
 182				syncDirtyContacts(account);
 183				scheduleWakeupCall(Config.PING_MAX_INTERVAL, true);
 184			} else if (account.getStatus() == Account.State.OFFLINE) {
 185				resetSendingToWaiting(account);
 186				if (!account.isOptionSet(Account.OPTION_DISABLED)) {
 187					int timeToReconnect = mRandom.nextInt(50) + 10;
 188					scheduleWakeupCall(timeToReconnect, false);
 189				}
 190			} else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
 191				databaseBackend.updateAccount(account);
 192				reconnectAccount(account, true);
 193			} else if ((account.getStatus() != Account.State.CONNECTING)
 194					&& (account.getStatus() != Account.State.NO_INTERNET)) {
 195				if (connection != null) {
 196					int next = connection.getTimeToNextAttempt();
 197					Log.d(Config.LOGTAG, account.getJid().toBareJid()
 198							+ ": error connecting account. try again in "
 199							+ next + "s for the "
 200							+ (connection.getAttempt() + 1) + " time");
 201					scheduleWakeupCall((int) (next * 1.2), false);
 202				}
 203					}
 204			getNotificationService().updateErrorNotification();
 205		}
 206	};
 207
 208	private int accountChangedListenerCount = 0;
 209	private OnRosterUpdate mOnRosterUpdate = null;
 210	private int rosterChangedListenerCount = 0;
 211	private OnMucRosterUpdate mOnMucRosterUpdate = null;
 212	private int mucRosterChangedListenerCount = 0;
 213	private SecureRandom mRandom;
 214	private FileObserver fileObserver = new FileObserver(
 215			FileBackend.getConversationsImageDirectory()) {
 216
 217		@Override
 218		public void onEvent(int event, String path) {
 219			if (event == FileObserver.DELETE) {
 220				markFileDeleted(path.split("\\.")[0]);
 221			}
 222		}
 223	};
 224	private OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
 225
 226		@Override
 227		public void onJinglePacketReceived(Account account, JinglePacket packet) {
 228			mJingleConnectionManager.deliverPacket(account, packet);
 229		}
 230	};
 231
 232	private OpenPgpServiceConnection pgpServiceConnection;
 233	private PgpEngine mPgpEngine = null;
 234	private Intent pingIntent;
 235	private PendingIntent pendingPingIntent = null;
 236	private WakeLock wakeLock;
 237	private PowerManager pm;
 238	private OnBindListener mOnBindListener = new OnBindListener() {
 239
 240		@Override
 241		public void onBind(final Account account) {
 242			account.getRoster().clearPresences();
 243			account.clearPresences(); // self presences
 244			account.pendingConferenceJoins.clear();
 245			account.pendingConferenceLeaves.clear();
 246			fetchRosterFromServer(account);
 247			fetchBookmarks(account);
 248			sendPresencePacket(account,
 249					mPresenceGenerator.sendPresence(account));
 250			connectMultiModeConversations(account);
 251			updateConversationUi();
 252		}
 253	};
 254
 255	private OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
 256
 257		@Override
 258		public void onMessageAcknowledged(Account account, String uuid) {
 259			for (final Conversation conversation : getConversations()) {
 260				if (conversation.getAccount() == account) {
 261					for (final Message message : conversation.getMessages()) {
 262						final int s = message.getStatus();
 263						if ((s == Message.STATUS_UNSEND || s == Message.STATUS_WAITING) && message.getUuid().equals(uuid)) {
 264							markMessage(message, Message.STATUS_SEND);
 265							if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
 266								databaseBackend.updateConversation(conversation);
 267							}
 268							return;
 269						}
 270					}
 271				}
 272			}
 273		}
 274	};
 275	private LruCache<String, Bitmap> mBitmapCache;
 276	private IqGenerator mIqGenerator = new IqGenerator(this);
 277
 278	public PgpEngine getPgpEngine() {
 279		if (pgpServiceConnection.isBound()) {
 280			if (this.mPgpEngine == null) {
 281				this.mPgpEngine = new PgpEngine(new OpenPgpApi(
 282							getApplicationContext(),
 283							pgpServiceConnection.getService()), this);
 284			}
 285			return mPgpEngine;
 286		} else {
 287			return null;
 288		}
 289
 290	}
 291
 292	public FileBackend getFileBackend() {
 293		return this.fileBackend;
 294	}
 295
 296	public AvatarService getAvatarService() {
 297		return this.mAvatarService;
 298	}
 299
 300	public void attachFileToConversation(Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
 301		final Message message;
 302		if (conversation.getNextEncryption(forceEncryption()) == Message.ENCRYPTION_PGP) {
 303			message = new Message(conversation, "",
 304					Message.ENCRYPTION_DECRYPTED);
 305		} else {
 306			message = new Message(conversation, "",
 307					conversation.getNextEncryption(forceEncryption()));
 308		}
 309		message.setCounterpart(conversation.getNextCounterpart());
 310		message.setType(Message.TYPE_FILE);
 311		message.setStatus(Message.STATUS_OFFERED);
 312		String path = getFileBackend().getOriginalPath(uri);
 313		if (path!=null) {
 314			message.setRelativeFilePath(path);
 315			getFileBackend().updateFileParams(message);
 316			if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 317				getPgpEngine().encrypt(message, callback);
 318			} else {
 319				callback.success(message);
 320			}
 321		} else {
 322			new Thread(new Runnable() {
 323				@Override
 324				public void run() {
 325					try {
 326						getFileBackend().copyFileToPrivateStorage(message, uri);
 327						getFileBackend().updateFileParams(message);
 328						if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 329							getPgpEngine().encrypt(message, callback);
 330						} else {
 331							callback.success(message);
 332						}
 333					} catch (FileBackend.FileCopyException e) {
 334						callback.error(e.getResId(),message);
 335					}
 336				}
 337			}).start();
 338
 339		}
 340	}
 341
 342	public void attachImageToConversation(final Conversation conversation,
 343			final Uri uri, final UiCallback<Message> callback) {
 344		final Message message;
 345		if (conversation.getNextEncryption(forceEncryption()) == Message.ENCRYPTION_PGP) {
 346			message = new Message(conversation, "",
 347					Message.ENCRYPTION_DECRYPTED);
 348		} else {
 349			message = new Message(conversation, "",
 350					conversation.getNextEncryption(forceEncryption()));
 351		}
 352		message.setCounterpart(conversation.getNextCounterpart());
 353		message.setType(Message.TYPE_IMAGE);
 354		message.setStatus(Message.STATUS_OFFERED);
 355		new Thread(new Runnable() {
 356
 357			@Override
 358			public void run() {
 359				try {
 360					DownloadableFile file = getFileBackend().copyImageToPrivateStorage(message, uri);
 361					if (conversation.getNextEncryption(forceEncryption()) == Message.ENCRYPTION_PGP) {
 362						getPgpEngine().encrypt(message, callback);
 363					} else {
 364						callback.success(message);
 365					}
 366				} catch (FileBackend.FileCopyException e) {
 367					callback.error(e.getResId(), message);
 368				}
 369			}
 370		}).start();
 371	}
 372
 373	public Conversation find(Bookmark bookmark) {
 374		return find(bookmark.getAccount(), bookmark.getJid());
 375	}
 376
 377	public Conversation find(final Account account, final Jid jid) {
 378		return find(getConversations(), account, jid);
 379	}
 380
 381	@Override
 382	public int onStartCommand(Intent intent, int flags, int startId) {
 383		if (intent != null && intent.getAction() != null) {
 384			if (intent.getAction().equals(ACTION_MERGE_PHONE_CONTACTS)) {
 385				mergePhoneContactsWithRoster();
 386				return START_STICKY;
 387			} else if (intent.getAction().equals(Intent.ACTION_SHUTDOWN)) {
 388				logoutAndSave();
 389				return START_NOT_STICKY;
 390			} else if (intent.getAction().equals(ACTION_CLEAR_NOTIFICATION)) {
 391				mNotificationService.clear();
 392			} else if (intent.getAction().equals(ACTION_DISABLE_FOREGROUND)) {
 393				getPreferences().edit().putBoolean("keep_foreground_service",false).commit();
 394				toggleForegroundService();
 395			}
 396		}
 397		this.wakeLock.acquire();
 398
 399		for (Account account : accounts) {
 400			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
 401				if (!hasInternetConnection()) {
 402					account.setStatus(Account.State.NO_INTERNET);
 403					if (statusListener != null) {
 404						statusListener.onStatusChanged(account);
 405					}
 406				} else {
 407					if (account.getStatus() == Account.State.NO_INTERNET) {
 408						account.setStatus(Account.State.OFFLINE);
 409						if (statusListener != null) {
 410							statusListener.onStatusChanged(account);
 411						}
 412					}
 413					if (account.getStatus() == Account.State.ONLINE) {
 414						long lastReceived = account.getXmppConnection()
 415							.getLastPacketReceived();
 416						long lastSent = account.getXmppConnection()
 417							.getLastPingSent();
 418						if (lastSent - lastReceived >= Config.PING_TIMEOUT * 1000) {
 419							Log.d(Config.LOGTAG, account.getJid()
 420									+ ": ping timeout");
 421							this.reconnectAccount(account, true);
 422						} else if (SystemClock.elapsedRealtime() - lastReceived >= Config.PING_MIN_INTERVAL * 1000) {
 423							account.getXmppConnection().sendPing();
 424							this.scheduleWakeupCall(2, false);
 425						}
 426					} else if (account.getStatus() == Account.State.OFFLINE) {
 427						if (account.getXmppConnection() == null) {
 428							account.setXmppConnection(this
 429									.createConnection(account));
 430						}
 431						new Thread(account.getXmppConnection()).start();
 432					} else if ((account.getStatus() == Account.State.CONNECTING)
 433							&& ((SystemClock.elapsedRealtime() - account
 434									.getXmppConnection().getLastConnect()) / 1000 >= Config.CONNECT_TIMEOUT)) {
 435						Log.d(Config.LOGTAG, account.getJid()
 436								+ ": time out during connect reconnecting");
 437						reconnectAccount(account, true);
 438					} else {
 439						if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
 440							reconnectAccount(account, true);
 441						}
 442					}
 443					// in any case. reschedule wakup call
 444					this.scheduleWakeupCall(Config.PING_MAX_INTERVAL, true);
 445				}
 446				if (mOnAccountUpdate != null) {
 447					mOnAccountUpdate.onAccountUpdate();
 448				}
 449			}
 450		}
 451		/*PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
 452			if (!pm.isScreenOn()) {
 453			removeStaleListeners();
 454			}*/
 455		if (wakeLock.isHeld()) {
 456			try {
 457				wakeLock.release();
 458			} catch (final RuntimeException ignored) {
 459			}
 460		}
 461		return START_STICKY;
 462	}
 463
 464	public boolean hasInternetConnection() {
 465		ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
 466			.getSystemService(Context.CONNECTIVITY_SERVICE);
 467		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
 468		return activeNetwork != null && activeNetwork.isConnected();
 469	}
 470
 471	@SuppressLint("TrulyRandom")
 472	@Override
 473	public void onCreate() {
 474		ExceptionHelper.init(getApplicationContext());
 475		PRNGFixes.apply();
 476		this.mRandom = new SecureRandom();
 477		this.mMemorizingTrustManager = new MemorizingTrustManager(
 478				getApplicationContext());
 479
 480		int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
 481		int cacheSize = maxMemory / 8;
 482		this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
 483			@Override
 484			protected int sizeOf(String key, Bitmap bitmap) {
 485				return bitmap.getByteCount() / 1024;
 486			}
 487		};
 488
 489		this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
 490		this.accounts = databaseBackend.getAccounts();
 491
 492		for (Account account : this.accounts) {
 493			account.initOtrEngine(this);
 494			this.databaseBackend.readRoster(account.getRoster());
 495		}
 496		initConversations();
 497		this.mergePhoneContactsWithRoster();
 498
 499		getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
 500		this.fileObserver.startWatching();
 501		this.pgpServiceConnection = new OpenPgpServiceConnection(getApplicationContext(), "org.sufficientlysecure.keychain");
 502		this.pgpServiceConnection.bindToService();
 503
 504		this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 505		this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"XmppConnectionService");
 506		toggleForegroundService();
 507	}
 508
 509	public void toggleForegroundService() {
 510		if (getPreferences().getBoolean("keep_foreground_service",false)) {
 511			startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
 512		} else {
 513			stopForeground(true);
 514		}
 515	}
 516
 517	@Override
 518	public void onTaskRemoved(Intent rootIntent) {
 519		super.onTaskRemoved(rootIntent);
 520		if (!getPreferences().getBoolean("keep_foreground_service",false)) {
 521			this.logoutAndSave();
 522		}
 523	}
 524
 525	private void logoutAndSave() {
 526		for (Account account : accounts) {
 527			databaseBackend.writeRoster(account.getRoster());
 528			if (account.getXmppConnection() != null) {
 529				disconnect(account, false);
 530			}
 531		}
 532		Context context = getApplicationContext();
 533		AlarmManager alarmManager = (AlarmManager) context
 534			.getSystemService(Context.ALARM_SERVICE);
 535		Intent intent = new Intent(context, EventReceiver.class);
 536		alarmManager.cancel(PendingIntent.getBroadcast(context, 0, intent, 0));
 537		Log.d(Config.LOGTAG, "good bye");
 538		stopSelf();
 539	}
 540
 541	protected void scheduleWakeupCall(int seconds, boolean ping) {
 542		long timeToWake = SystemClock.elapsedRealtime() + seconds * 1000;
 543		Context context = getApplicationContext();
 544		AlarmManager alarmManager = (AlarmManager) context
 545			.getSystemService(Context.ALARM_SERVICE);
 546
 547		if (ping) {
 548			if (this.pingIntent == null) {
 549				this.pingIntent = new Intent(context, EventReceiver.class);
 550				this.pingIntent.setAction("ping");
 551				this.pingIntent.putExtra("time", timeToWake);
 552				this.pendingPingIntent = PendingIntent.getBroadcast(context, 0,
 553						this.pingIntent, 0);
 554				alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
 555						timeToWake, pendingPingIntent);
 556			} else {
 557				long scheduledTime = this.pingIntent.getLongExtra("time", 0);
 558				if (scheduledTime < SystemClock.elapsedRealtime()
 559						|| (scheduledTime > timeToWake)) {
 560					this.pingIntent.putExtra("time", timeToWake);
 561					alarmManager.cancel(this.pendingPingIntent);
 562					this.pendingPingIntent = PendingIntent.getBroadcast(
 563							context, 0, this.pingIntent, 0);
 564					alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
 565							timeToWake, pendingPingIntent);
 566						}
 567			}
 568		} else {
 569			Intent intent = new Intent(context, EventReceiver.class);
 570			intent.setAction("ping_check");
 571			PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0,
 572					intent, 0);
 573			alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake,
 574					alarmIntent);
 575		}
 576
 577	}
 578
 579	public XmppConnection createConnection(Account account) {
 580		SharedPreferences sharedPref = getPreferences();
 581		account.setResource(sharedPref.getString("resource", "mobile")
 582				.toLowerCase(Locale.getDefault()));
 583		XmppConnection connection = new XmppConnection(account, this);
 584		connection.setOnMessagePacketReceivedListener(this.mMessageParser);
 585		connection.setOnStatusChangedListener(this.statusListener);
 586		connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
 587		connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
 588		connection.setOnJinglePacketReceivedListener(this.jingleListener);
 589		connection.setOnBindListener(this.mOnBindListener);
 590		connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
 591		connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
 592		return connection;
 593	}
 594
 595	public void sendMessage(Message message) {
 596		Account account = message.getConversation().getAccount();
 597		account.deactivateGracePeriod();
 598		Conversation conv = message.getConversation();
 599		MessagePacket packet = null;
 600		boolean saveInDb = true;
 601		boolean send = false;
 602		if (account.getStatus() == Account.State.ONLINE
 603				&& account.getXmppConnection() != null) {
 604			if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
 605				if (message.getCounterpart() != null) {
 606					if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 607						if (!conv.hasValidOtrSession()) {
 608							conv.startOtrSession(message.getCounterpart().getResourcepart(),true);
 609							message.setStatus(Message.STATUS_WAITING);
 610						} else if (conv.hasValidOtrSession()
 611								&& conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
 612							mJingleConnectionManager
 613								.createNewConnection(message);
 614								}
 615					} else {
 616						mJingleConnectionManager.createNewConnection(message);
 617					}
 618				} else {
 619					if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 620						conv.startOtrIfNeeded();
 621					}
 622					message.setStatus(Message.STATUS_WAITING);
 623				}
 624			} else {
 625				if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 626					if (!conv.hasValidOtrSession() && (message.getCounterpart() != null)) {
 627						conv.startOtrSession(message.getCounterpart().getResourcepart(), true);
 628						message.setStatus(Message.STATUS_WAITING);
 629					} else if (conv.hasValidOtrSession()) {
 630						if (conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
 631							packet = mMessageGenerator.generateOtrChat(message);
 632							send = true;
 633						} else {
 634							message.setStatus(Message.STATUS_WAITING);
 635							conv.startOtrIfNeeded();
 636						}
 637					} else {
 638						message.setStatus(Message.STATUS_WAITING);
 639					}
 640				} else if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 641					message.getConversation().endOtrIfNeeded();
 642					failWaitingOtrMessages(message.getConversation());
 643					packet = mMessageGenerator.generatePgpChat(message);
 644					send = true;
 645				} else {
 646					message.getConversation().endOtrIfNeeded();
 647					failWaitingOtrMessages(message.getConversation());
 648					packet = mMessageGenerator.generateChat(message);
 649					send = true;
 650				}
 651			}
 652			if (!account.getXmppConnection().getFeatures().sm()
 653					&& conv.getMode() != Conversation.MODE_MULTI) {
 654				message.setStatus(Message.STATUS_SEND);
 655					}
 656		} else {
 657			message.setStatus(Message.STATUS_WAITING);
 658			if (message.getType() == Message.TYPE_TEXT) {
 659				if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 660					String pgpBody = message.getEncryptedBody();
 661					String decryptedBody = message.getBody();
 662					message.setBody(pgpBody);
 663					message.setEncryption(Message.ENCRYPTION_PGP);
 664					databaseBackend.createMessage(message);
 665					saveInDb = false;
 666					message.setBody(decryptedBody);
 667					message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 668				} else if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 669					if (!conv.hasValidOtrSession()
 670							&& message.getCounterpart() != null) {
 671						conv.startOtrSession(message.getCounterpart().getResourcepart(), false);
 672							}
 673				}
 674			}
 675
 676		}
 677		conv.add(message);
 678		if (saveInDb) {
 679			if (message.getEncryption() == Message.ENCRYPTION_NONE
 680					|| saveEncryptedMessages()) {
 681				databaseBackend.createMessage(message);
 682					}
 683		}
 684		if ((send) && (packet != null)) {
 685			sendMessagePacket(account, packet);
 686		}
 687		updateConversationUi();
 688	}
 689
 690	private void sendUnsendMessages(Conversation conversation) {
 691		for (int i = 0; i < conversation.getMessages().size(); ++i) {
 692			int status = conversation.getMessages().get(i).getStatus();
 693			if (status == Message.STATUS_WAITING) {
 694				resendMessage(conversation.getMessages().get(i));
 695			}
 696		}
 697	}
 698
 699	private void resendMessage(Message message) {
 700		Account account = message.getConversation().getAccount();
 701		MessagePacket packet = null;
 702		if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 703			Presences presences = message.getConversation().getContact()
 704				.getPresences();
 705			if (!message.getConversation().hasValidOtrSession()) {
 706				if ((message.getCounterpart() != null)
 707						&& (presences.has(message.getCounterpart().getResourcepart()))) {
 708					message.getConversation().startOtrSession(message.getCounterpart().getResourcepart(), true);
 709				} else {
 710					if (presences.size() == 1) {
 711						String presence = presences.asStringArray()[0];
 712						message.getConversation().startOtrSession(presence, true);
 713					}
 714				}
 715			} else {
 716				if (message.getConversation().getOtrSession()
 717						.getSessionStatus() == SessionStatus.ENCRYPTED) {
 718					try {
 719						message.setCounterpart(Jid.fromSessionID(message.getConversation().getOtrSession().getSessionID()));
 720						if (message.getType() == Message.TYPE_TEXT) {
 721							packet = mMessageGenerator.generateOtrChat(message,
 722									true);
 723						} else if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
 724							mJingleConnectionManager.createNewConnection(message);
 725						}
 726					} catch (InvalidJidException e) {
 727
 728					}
 729						}
 730			}
 731		} else if (message.getType() == Message.TYPE_TEXT) {
 732			if (message.getEncryption() == Message.ENCRYPTION_NONE) {
 733				packet = mMessageGenerator.generateChat(message, true);
 734			} else if ((message.getEncryption() == Message.ENCRYPTION_DECRYPTED)
 735					|| (message.getEncryption() == Message.ENCRYPTION_PGP)) {
 736				packet = mMessageGenerator.generatePgpChat(message, true);
 737					}
 738		} else if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
 739			Contact contact = message.getConversation().getContact();
 740			Presences presences = contact.getPresences();
 741			if ((message.getCounterpart() != null)
 742					&& (presences.has(message.getCounterpart().getResourcepart()))) {
 743				markMessage(message, Message.STATUS_OFFERED);
 744				mJingleConnectionManager.createNewConnection(message);
 745			} else {
 746				if (presences.size() == 1) {
 747					String presence = presences.asStringArray()[0];
 748					try {
 749						message.setCounterpart(Jid.fromParts(contact.getJid().getLocalpart(), contact.getJid().getDomainpart(), presence));
 750					} catch (InvalidJidException e) {
 751						return;
 752					}
 753					markMessage(message, Message.STATUS_OFFERED);
 754					mJingleConnectionManager.createNewConnection(message);
 755				}
 756			}
 757		}
 758		if (packet != null) {
 759			if (!account.getXmppConnection().getFeatures().sm()
 760					&& message.getConversation().getMode() != Conversation.MODE_MULTI) {
 761				markMessage(message, Message.STATUS_SEND);
 762			} else {
 763				markMessage(message, Message.STATUS_UNSEND);
 764			}
 765			sendMessagePacket(account, packet);
 766		}
 767	}
 768
 769	public void fetchRosterFromServer(Account account) {
 770		IqPacket iqPacket = new IqPacket(IqPacket.TYPE_GET);
 771		if (!"".equals(account.getRosterVersion())) {
 772			Log.d(Config.LOGTAG, account.getJid().toBareJid()
 773					+ ": fetching roster version " + account.getRosterVersion());
 774		} else {
 775			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
 776		}
 777		iqPacket.query("jabber:iq:roster").setAttribute("ver",
 778				account.getRosterVersion());
 779		account.getXmppConnection().sendIqPacket(iqPacket,
 780				new OnIqPacketReceived() {
 781
 782					@Override
 783					public void onIqPacketReceived(final Account account,
 784												   IqPacket packet) {
 785						Element query = packet.findChild("query");
 786						if (query != null) {
 787							account.getRoster().markAllAsNotInRoster();
 788							mIqParser.rosterItems(account, query);
 789						}
 790					}
 791				});
 792	}
 793
 794	public void fetchBookmarks(Account account) {
 795		IqPacket iqPacket = new IqPacket(IqPacket.TYPE_GET);
 796		Element query = iqPacket.query("jabber:iq:private");
 797		query.addChild("storage", "storage:bookmarks");
 798		OnIqPacketReceived callback = new OnIqPacketReceived() {
 799
 800			@Override
 801			public void onIqPacketReceived(Account account, IqPacket packet) {
 802				Element query = packet.query();
 803				List<Bookmark> bookmarks = new CopyOnWriteArrayList<>();
 804				Element storage = query.findChild("storage",
 805						"storage:bookmarks");
 806				if (storage != null) {
 807					for (Element item : storage.getChildren()) {
 808						if (item.getName().equals("conference")) {
 809							Bookmark bookmark = Bookmark.parse(item, account);
 810							bookmarks.add(bookmark);
 811							Conversation conversation = find(bookmark);
 812							if (conversation != null) {
 813								conversation.setBookmark(bookmark);
 814							} else if (bookmark.autojoin() && bookmark.getJid() != null) {
 815								conversation = findOrCreateConversation(
 816										account, bookmark.getJid(), true);
 817								conversation.setBookmark(bookmark);
 818								joinMuc(conversation);
 819							}
 820						}
 821					}
 822				}
 823				account.setBookmarks(bookmarks);
 824			}
 825		};
 826		sendIqPacket(account, iqPacket, callback);
 827
 828	}
 829
 830	public void pushBookmarks(Account account) {
 831		IqPacket iqPacket = new IqPacket(IqPacket.TYPE_SET);
 832		Element query = iqPacket.query("jabber:iq:private");
 833		Element storage = query.addChild("storage", "storage:bookmarks");
 834		for (Bookmark bookmark : account.getBookmarks()) {
 835			storage.addChild(bookmark);
 836		}
 837		sendIqPacket(account, iqPacket, null);
 838	}
 839
 840	private void mergePhoneContactsWithRoster() {
 841		PhoneHelper.loadPhoneContacts(getApplicationContext(),
 842				new OnPhoneContactsLoadedListener() {
 843					@Override
 844					public void onPhoneContactsLoaded(List<Bundle> phoneContacts) {
 845						for (Account account : accounts) {
 846							account.getRoster().clearSystemAccounts();
 847						}
 848						for (Bundle phoneContact : phoneContacts) {
 849							for (Account account : accounts) {
 850								Jid jid;
 851								try {
 852									jid = Jid.fromString(phoneContact.getString("jid"));
 853								} catch (final InvalidJidException e) {
 854									// TODO: Warn if contact import fails here?
 855									break;
 856								}
 857								final Contact contact = account.getRoster()
 858										.getContact(jid);
 859								String systemAccount = phoneContact
 860										.getInt("phoneid")
 861										+ "#"
 862										+ phoneContact.getString("lookup");
 863								contact.setSystemAccount(systemAccount);
 864								contact.setPhotoUri(phoneContact
 865										.getString("photouri"));
 866								contact.setSystemName(phoneContact
 867										.getString("displayname"));
 868								getAvatarService().clear(contact);
 869							}
 870						}
 871					}
 872				});
 873	}
 874
 875	private void initConversations() {
 876		synchronized (this.conversations) {
 877			Hashtable<String, Account> accountLookupTable = new Hashtable<>();
 878			for (Account account : this.accounts) {
 879				accountLookupTable.put(account.getUuid(), account);
 880			}
 881			this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
 882			for (Conversation conv : this.conversations) {
 883				Account account = accountLookupTable.get(conv.getAccountUuid());
 884				conv.setAccount(account);
 885				conv.addAll(0, databaseBackend.getMessages(conv, 50));
 886				checkDeletedFiles(conv);
 887			}
 888		}
 889	}
 890
 891	public List<Conversation> getConversations() {
 892		return this.conversations;
 893	}
 894
 895	private void checkDeletedFiles(Conversation conversation) {
 896		for (Message message : conversation.getMessages()) {
 897			if ((message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE)
 898					&& message.getEncryption() != Message.ENCRYPTION_PGP) {
 899				if (!getFileBackend().isFileAvailable(message)) {
 900					message.setDownloadable(new DownloadablePlaceholder(Downloadable.STATUS_DELETED));
 901				}
 902					}
 903		}
 904	}
 905
 906	private void markFileDeleted(String uuid) {
 907		for (Conversation conversation : getConversations()) {
 908			for (Message message : conversation.getMessages()) {
 909				if (message.getType() == Message.TYPE_IMAGE
 910						&& message.getEncryption() != Message.ENCRYPTION_PGP
 911						&& message.getUuid().equals(uuid)) {
 912					if (!getFileBackend().isFileAvailable(message)) {
 913						message.setDownloadable(new DownloadablePlaceholder(Downloadable.STATUS_DELETED));
 914						updateConversationUi();
 915					}
 916					return;
 917						}
 918			}
 919		}
 920	}
 921
 922	public void populateWithOrderedConversations(final List<Conversation> list) {
 923		populateWithOrderedConversations(list, true);
 924	}
 925
 926	public void populateWithOrderedConversations(final List<Conversation> list, boolean includeConferences) {
 927		list.clear();
 928		if (includeConferences) {
 929			list.addAll(getConversations());
 930		} else {
 931			for (Conversation conversation : getConversations()) {
 932				if (conversation.getMode() == Conversation.MODE_SINGLE) {
 933					list.add(conversation);
 934				}
 935			}
 936		}
 937		Collections.sort(list, new Comparator<Conversation>() {
 938			@Override
 939			public int compare(Conversation lhs, Conversation rhs) {
 940				Message left = lhs.getLatestMessage();
 941				Message right = rhs.getLatestMessage();
 942				if (left.getTimeSent() > right.getTimeSent()) {
 943					return -1;
 944				} else if (left.getTimeSent() < right.getTimeSent()) {
 945					return 1;
 946				} else {
 947					return 0;
 948				}
 949			}
 950		});
 951	}
 952
 953	public int loadMoreMessages(Conversation conversation, long timestamp) {
 954		List<Message> messages = databaseBackend.getMessages(conversation, 50,
 955				timestamp);
 956		for (Message message : messages) {
 957			message.setConversation(conversation);
 958		}
 959		conversation.addAll(0, messages);
 960		return messages.size();
 961	}
 962
 963	public List<Account> getAccounts() {
 964		return this.accounts;
 965	}
 966
 967	public Conversation find(List<Conversation> haystack, Contact contact) {
 968		for (Conversation conversation : haystack) {
 969			if (conversation.getContact() == contact) {
 970				return conversation;
 971			}
 972		}
 973		return null;
 974	}
 975
 976	public Conversation find(final List<Conversation> haystack,
 977			final Account account,
 978			final Jid jid) {
 979		if (jid == null ) {
 980			return null;
 981		}
 982		for (Conversation conversation : haystack) {
 983			if ((account == null || conversation.getAccount() == account)
 984					&& (conversation.getContactJid().toBareJid().equals(jid.toBareJid()))) {
 985				return conversation;
 986					}
 987		}
 988		return null;
 989	}
 990
 991	public Conversation findOrCreateConversation(final Account account, final Jid jid,final boolean muc) {
 992		return this.findOrCreateConversation(account,jid,muc,null);
 993	}
 994
 995	public Conversation findOrCreateConversation(final Account account, final Jid jid,final boolean muc, final MessageArchiveService.Query query) {
 996		synchronized (this.conversations) {
 997			Conversation conversation = find(account, jid);
 998			if (conversation != null) {
 999				return conversation;
1000			}
1001			conversation = databaseBackend.findConversation(account, jid);
1002			if (conversation != null) {
1003				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1004				conversation.setAccount(account);
1005				if (muc) {
1006					conversation.setMode(Conversation.MODE_MULTI);
1007				} else {
1008					conversation.setMode(Conversation.MODE_SINGLE);
1009				}
1010				conversation.addAll(0, databaseBackend.getMessages(conversation, 50));
1011				this.databaseBackend.updateConversation(conversation);
1012			} else {
1013				String conversationName;
1014				Contact contact = account.getRoster().getContact(jid);
1015				if (contact != null) {
1016					conversationName = contact.getDisplayName();
1017				} else {
1018					conversationName = jid.getLocalpart();
1019				}
1020				if (muc) {
1021					conversation = new Conversation(conversationName, account, jid,
1022							Conversation.MODE_MULTI);
1023				} else {
1024					conversation = new Conversation(conversationName, account, jid,
1025							Conversation.MODE_SINGLE);
1026				}
1027				this.databaseBackend.createConversation(conversation);
1028			}
1029			if (query == null) {
1030				this.mMessageArchiveService.query(conversation);
1031			} else {
1032				if (query.getConversation() == null) {
1033					this.mMessageArchiveService.query(conversation,query.getStart());
1034				}
1035			}
1036			this.conversations.add(conversation);
1037			updateConversationUi();
1038			return conversation;
1039		}
1040	}
1041
1042	public void archiveConversation(Conversation conversation) {
1043		synchronized (this.conversations) {
1044			if (conversation.getMode() == Conversation.MODE_MULTI) {
1045				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1046					Bookmark bookmark = conversation.getBookmark();
1047					if (bookmark != null && bookmark.autojoin()) {
1048						bookmark.setAutojoin(false);
1049						pushBookmarks(bookmark.getAccount());
1050					}
1051				}
1052				leaveMuc(conversation);
1053			} else {
1054				conversation.endOtrIfNeeded();
1055			}
1056			this.databaseBackend.updateConversation(conversation);
1057			this.conversations.remove(conversation);
1058			updateConversationUi();
1059		}
1060	}
1061
1062	public void clearConversationHistory(Conversation conversation) {
1063		this.databaseBackend.deleteMessagesInConversation(conversation);
1064		conversation.getMessages().clear();
1065		updateConversationUi();
1066	}
1067
1068	public void createAccount(Account account) {
1069		account.initOtrEngine(this);
1070		databaseBackend.createAccount(account);
1071		this.accounts.add(account);
1072		this.reconnectAccount(account, false);
1073		updateAccountUi();
1074	}
1075
1076	public void updateAccount(Account account) {
1077		this.statusListener.onStatusChanged(account);
1078		databaseBackend.updateAccount(account);
1079		reconnectAccount(account, false);
1080		updateAccountUi();
1081		getNotificationService().updateErrorNotification();
1082	}
1083
1084	public void deleteAccount(Account account) {
1085		synchronized (this.conversations) {
1086			for (Conversation conversation : conversations) {
1087				if (conversation.getAccount() == account) {
1088					if (conversation.getMode() == Conversation.MODE_MULTI) {
1089						leaveMuc(conversation);
1090					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1091						conversation.endOtrIfNeeded();
1092					}
1093					conversations.remove(conversation);
1094				}
1095			}
1096			if (account.getXmppConnection() != null) {
1097				this.disconnect(account, true);
1098			}
1099			databaseBackend.deleteAccount(account);
1100			this.accounts.remove(account);
1101			updateAccountUi();
1102			getNotificationService().updateErrorNotification();
1103		}
1104	}
1105
1106	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1107		synchronized (this) {
1108			if (checkListeners()) {
1109				switchToForeground();
1110			}
1111			this.mOnConversationUpdate = listener;
1112			this.mNotificationService.setIsInForeground(true);
1113			if (this.convChangedListenerCount < 2) {
1114				this.convChangedListenerCount++;
1115			}
1116		}
1117	}
1118
1119	public void removeOnConversationListChangedListener() {
1120		synchronized (this) {
1121			this.convChangedListenerCount--;
1122			if (this.convChangedListenerCount <= 0) {
1123				this.convChangedListenerCount = 0;
1124				this.mOnConversationUpdate = null;
1125				this.mNotificationService.setIsInForeground(false);
1126				if (checkListeners()) {
1127					switchToBackground();
1128				}
1129			}
1130		}
1131	}
1132
1133	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1134		synchronized (this) {
1135			if (checkListeners()) {
1136				switchToForeground();
1137			}
1138			this.mOnAccountUpdate = listener;
1139			if (this.accountChangedListenerCount < 2) {
1140				this.accountChangedListenerCount++;
1141			}
1142		}
1143	}
1144
1145	public void removeOnAccountListChangedListener() {
1146		synchronized (this) {
1147			this.accountChangedListenerCount--;
1148			if (this.accountChangedListenerCount <= 0) {
1149				this.mOnAccountUpdate = null;
1150				this.accountChangedListenerCount = 0;
1151				if (checkListeners()) {
1152					switchToBackground();
1153				}
1154			}
1155		}
1156	}
1157
1158	public void setOnRosterUpdateListener(OnRosterUpdate listener) {
1159		synchronized (this) {
1160			if (checkListeners()) {
1161				switchToForeground();
1162			}
1163			this.mOnRosterUpdate = listener;
1164			if (this.rosterChangedListenerCount < 2) {
1165				this.rosterChangedListenerCount++;
1166			}
1167		}
1168	}
1169
1170	public void removeOnRosterUpdateListener() {
1171		synchronized (this) {
1172			this.rosterChangedListenerCount--;
1173			if (this.rosterChangedListenerCount <= 0) {
1174				this.rosterChangedListenerCount = 0;
1175				this.mOnRosterUpdate = null;
1176				if (checkListeners()) {
1177					switchToBackground();
1178				}
1179			}
1180		}
1181	}
1182
1183	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1184		synchronized (this) {
1185			if (checkListeners()) {
1186				switchToForeground();
1187			}
1188			this.mOnMucRosterUpdate = listener;
1189			if (this.mucRosterChangedListenerCount < 2) {
1190				this.mucRosterChangedListenerCount++;
1191			}
1192		}
1193	}
1194
1195	public void removeOnMucRosterUpdateListener() {
1196		synchronized (this) {
1197			this.mucRosterChangedListenerCount--;
1198			if (this.mucRosterChangedListenerCount <= 0) {
1199				this.mucRosterChangedListenerCount = 0;
1200				this.mOnMucRosterUpdate = null;
1201				if (checkListeners()) {
1202					switchToBackground();
1203				}
1204			}
1205		}
1206	}
1207
1208	private boolean checkListeners() {
1209		return (this.mOnAccountUpdate == null
1210				&& this.mOnConversationUpdate == null && this.mOnRosterUpdate == null);
1211	}
1212
1213	private void switchToForeground() {
1214		for (Account account : getAccounts()) {
1215			if (account.getStatus() == Account.State.ONLINE) {
1216				XmppConnection connection = account.getXmppConnection();
1217				if (connection != null && connection.getFeatures().csi()) {
1218					connection.sendActive();
1219				}
1220			}
1221		}
1222		Log.d(Config.LOGTAG, "app switched into foreground");
1223	}
1224
1225	private void switchToBackground() {
1226		for (Account account : getAccounts()) {
1227			if (account.getStatus() == Account.State.ONLINE) {
1228				XmppConnection connection = account.getXmppConnection();
1229				if (connection != null && connection.getFeatures().csi()) {
1230					connection.sendInactive();
1231				}
1232			}
1233		}
1234		this.mNotificationService.setIsInForeground(false);
1235		Log.d(Config.LOGTAG, "app switched into background");
1236	}
1237
1238	public void connectMultiModeConversations(Account account) {
1239		List<Conversation> conversations = getConversations();
1240		for (Conversation conversation : conversations) {
1241			if ((conversation.getMode() == Conversation.MODE_MULTI)
1242					&& (conversation.getAccount() == account)) {
1243				joinMuc(conversation);
1244					}
1245		}
1246	}
1247
1248	public void joinMuc(Conversation conversation) {
1249		Account account = conversation.getAccount();
1250		account.pendingConferenceJoins.remove(conversation);
1251		account.pendingConferenceLeaves.remove(conversation);
1252		if (account.getStatus() == Account.State.ONLINE) {
1253			final String nick = conversation.getMucOptions().getProposedNick();
1254			final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1255			if (joinJid == null) {
1256				return; //safety net
1257			}
1258			Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1259			PresencePacket packet = new PresencePacket();
1260			packet.setFrom(conversation.getAccount().getJid());
1261			packet.setTo(joinJid);
1262			Element x = packet.addChild("x","http://jabber.org/protocol/muc");
1263			if (conversation.getMucOptions().getPassword() != null) {
1264				x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1265			}
1266			x.addChild("history").setAttribute("since",PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1267			String sig = account.getPgpSignature();
1268			if (sig != null) {
1269				packet.addChild("status").setContent("online");
1270				packet.addChild("x", "jabber:x:signed").setContent(sig);
1271			}
1272			sendPresencePacket(account, packet);
1273			if (!joinJid.equals(conversation.getContactJid())) {
1274				conversation.setContactJid(joinJid);
1275				databaseBackend.updateConversation(conversation);
1276			}
1277		} else {
1278			account.pendingConferenceJoins.add(conversation);
1279		}
1280	}
1281
1282	public void providePasswordForMuc(Conversation conversation, String password) {
1283		if (conversation.getMode() == Conversation.MODE_MULTI) {
1284			conversation.getMucOptions().setPassword(password);
1285			if (conversation.getBookmark() != null) {
1286				conversation.getBookmark().setAutojoin(true);
1287				pushBookmarks(conversation.getAccount());
1288			}
1289			databaseBackend.updateConversation(conversation);
1290			joinMuc(conversation);
1291		}
1292	}
1293
1294	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1295		final MucOptions options = conversation.getMucOptions();
1296		final Jid joinJid = options.createJoinJid(nick);
1297		if (options.online()) {
1298			Account account = conversation.getAccount();
1299			options.setOnRenameListener(new OnRenameListener() {
1300
1301				@Override
1302				public void onSuccess() {
1303					conversation.setContactJid(joinJid);
1304					databaseBackend.updateConversation(conversation);
1305					Bookmark bookmark = conversation.getBookmark();
1306					if (bookmark != null) {
1307						bookmark.setNick(nick);
1308						pushBookmarks(bookmark.getAccount());
1309					}
1310					callback.success(conversation);
1311				}
1312
1313				@Override
1314				public void onFailure() {
1315					callback.error(R.string.nick_in_use, conversation);
1316				}
1317			});
1318
1319			PresencePacket packet = new PresencePacket();
1320			packet.setTo(joinJid);
1321			packet.setFrom(conversation.getAccount().getJid());
1322
1323			String sig = account.getPgpSignature();
1324			if (sig != null) {
1325				packet.addChild("status").setContent("online");
1326				packet.addChild("x", "jabber:x:signed").setContent(sig);
1327			}
1328			sendPresencePacket(account, packet);
1329		} else {
1330			conversation.setContactJid(joinJid);
1331			databaseBackend.updateConversation(conversation);
1332			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1333				Bookmark bookmark = conversation.getBookmark();
1334				if (bookmark != null) {
1335					bookmark.setNick(nick);
1336					pushBookmarks(bookmark.getAccount());
1337				}
1338				joinMuc(conversation);
1339			}
1340		}
1341	}
1342
1343	public void leaveMuc(Conversation conversation) {
1344		Account account = conversation.getAccount();
1345		account.pendingConferenceJoins.remove(conversation);
1346		account.pendingConferenceLeaves.remove(conversation);
1347		if (account.getStatus() == Account.State.ONLINE) {
1348			PresencePacket packet = new PresencePacket();
1349			packet.setTo(conversation.getContactJid());
1350			packet.setFrom(conversation.getAccount().getJid());
1351			packet.setAttribute("type", "unavailable");
1352			sendPresencePacket(conversation.getAccount(), packet);
1353			conversation.getMucOptions().setOffline();
1354			conversation.deregisterWithBookmark();
1355			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1356					+ ": leaving muc " + conversation.getContactJid());
1357		} else {
1358			account.pendingConferenceLeaves.add(conversation);
1359		}
1360	}
1361
1362	private String findConferenceServer(final Account account) {
1363		String server;
1364		if (account.getXmppConnection() != null) {
1365			server = account.getXmppConnection().getMucServer();
1366			if (server != null) {
1367				return server;
1368			}
1369		}
1370		for(Account other : getAccounts()) {
1371			if (other != account && other.getXmppConnection() != null) {
1372				server = other.getXmppConnection().getMucServer();
1373				if (server != null) {
1374					return server;
1375				}
1376			}
1377		}
1378		return null;
1379	}
1380
1381	public void createAdhocConference(final Account account, final List<Jid> jids, final UiCallback<Conversation> callback) {
1382		Log.d(Config.LOGTAG,account.getJid().toBareJid().toString()+": creating adhoc conference with "+ jids.toString());
1383		if (account.getStatus() == Account.State.ONLINE) {
1384			try {
1385				String server = findConferenceServer(account);
1386				if (server == null) {
1387					if (callback != null) {
1388						callback.error(R.string.no_conference_server_found,null);
1389					}
1390					return;
1391				}
1392				String name = new BigInteger(75,getRNG()).toString(32);
1393				Jid jid = Jid.fromParts(name,server,null);
1394				final Conversation conversation = findOrCreateConversation(account, jid, true);
1395				joinMuc(conversation);
1396				Bundle options = new Bundle();
1397				options.putString("muc#roomconfig_persistentroom", "1");
1398				options.putString("muc#roomconfig_membersonly", "1");
1399				options.putString("muc#roomconfig_publicroom", "0");
1400				options.putString("muc#roomconfig_whois", "anyone");
1401				pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1402					@Override
1403					public void onPushSucceeded() {
1404						for(Jid invite : jids) {
1405							invite(conversation,invite);
1406						}
1407						if (callback != null) {
1408							callback.success(conversation);
1409						}
1410					}
1411
1412					@Override
1413					public void onPushFailed() {
1414						if (callback != null) {
1415							callback.error(R.string.conference_creation_failed, conversation);
1416						}
1417					}
1418				});
1419
1420			} catch (InvalidJidException e) {
1421				if (callback != null) {
1422					callback.error(R.string.conference_creation_failed, null);
1423				}
1424			}
1425		} else {
1426			if (callback != null) {
1427				callback.error(R.string.not_connected_try_again,null);
1428			}
1429		}
1430	}
1431
1432	public void pushConferenceConfiguration(final Conversation conversation,final Bundle options, final OnConferenceOptionsPushed callback) {
1433		IqPacket request = new IqPacket(IqPacket.TYPE_GET);
1434		request.setTo(conversation.getContactJid().toBareJid());
1435		request.query("http://jabber.org/protocol/muc#owner");
1436		sendIqPacket(conversation.getAccount(),request,new OnIqPacketReceived() {
1437			@Override
1438			public void onIqPacketReceived(Account account, IqPacket packet) {
1439				if (packet.getType() != IqPacket.TYPE_ERROR) {
1440					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1441					for (Field field : data.getFields()) {
1442						if (options.containsKey(field.getName())) {
1443							field.setValue(options.getString(field.getName()));
1444						}
1445					}
1446					data.submit();
1447					IqPacket set = new IqPacket(IqPacket.TYPE_SET);
1448					set.setTo(conversation.getContactJid().toBareJid());
1449					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1450					sendIqPacket(account, set, new OnIqPacketReceived() {
1451						@Override
1452						public void onIqPacketReceived(Account account, IqPacket packet) {
1453							if (packet.getType() == IqPacket.TYPE_RESULT) {
1454								if (callback != null) {
1455									callback.onPushSucceeded();
1456								}
1457							} else {
1458								if (callback != null) {
1459									callback.onPushFailed();
1460								}
1461							}
1462						}
1463					});
1464				} else {
1465					if (callback != null) {
1466						callback.onPushFailed();
1467					}
1468				}
1469			}
1470		});
1471	}
1472
1473	public void disconnect(Account account, boolean force) {
1474		if ((account.getStatus() == Account.State.ONLINE)
1475				|| (account.getStatus() == Account.State.DISABLED)) {
1476			if (!force) {
1477				List<Conversation> conversations = getConversations();
1478				for (Conversation conversation : conversations) {
1479					if (conversation.getAccount() == account) {
1480						if (conversation.getMode() == Conversation.MODE_MULTI) {
1481							leaveMuc(conversation);
1482						} else {
1483							if (conversation.endOtrIfNeeded()) {
1484								Log.d(Config.LOGTAG, account.getJid().toBareJid()
1485										+ ": ended otr session with "
1486										+ conversation.getContactJid());
1487							}
1488						}
1489					}
1490				}
1491			}
1492			account.getXmppConnection().disconnect(force);
1493				}
1494	}
1495
1496	@Override
1497	public IBinder onBind(Intent intent) {
1498		return mBinder;
1499	}
1500
1501	public void updateMessage(Message message) {
1502		databaseBackend.updateMessage(message);
1503		updateConversationUi();
1504	}
1505
1506	protected void syncDirtyContacts(Account account) {
1507		for (Contact contact : account.getRoster().getContacts()) {
1508			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1509				pushContactToServer(contact);
1510			}
1511			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1512				deleteContactOnServer(contact);
1513			}
1514		}
1515	}
1516
1517	public void createContact(Contact contact) {
1518		SharedPreferences sharedPref = getPreferences();
1519		boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1520		if (autoGrant) {
1521			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1522			contact.setOption(Contact.Options.ASKING);
1523		}
1524		pushContactToServer(contact);
1525	}
1526
1527	public void onOtrSessionEstablished(Conversation conversation) {
1528		Account account = conversation.getAccount();
1529		List<Message> messages = conversation.getMessages();
1530		Session otrSession = conversation.getOtrSession();
1531		Log.d(Config.LOGTAG,
1532				account.getJid().toBareJid() + " otr session established with "
1533				+ conversation.getContactJid() + "/"
1534				+ otrSession.getSessionID().getUserID());
1535		for (Message msg : messages) {
1536			if ((msg.getStatus() == Message.STATUS_UNSEND || msg.getStatus() == Message.STATUS_WAITING)
1537					&& (msg.getEncryption() == Message.ENCRYPTION_OTR)) {
1538				SessionID id = otrSession.getSessionID();
1539				try {
1540					msg.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
1541				} catch (InvalidJidException e) {
1542					break;
1543				}
1544				if (msg.getType() == Message.TYPE_TEXT) {
1545					MessagePacket outPacket = mMessageGenerator
1546						.generateOtrChat(msg, true);
1547					if (outPacket != null) {
1548						msg.setStatus(Message.STATUS_SEND);
1549						databaseBackend.updateMessage(msg);
1550						sendMessagePacket(account, outPacket);
1551					}
1552				} else if (msg.getType() == Message.TYPE_IMAGE || msg.getType() == Message.TYPE_FILE) {
1553					mJingleConnectionManager.createNewConnection(msg);
1554				}
1555					}
1556		}
1557		updateConversationUi();
1558	}
1559
1560	public boolean renewSymmetricKey(Conversation conversation) {
1561		Account account = conversation.getAccount();
1562		byte[] symmetricKey = new byte[32];
1563		this.mRandom.nextBytes(symmetricKey);
1564		Session otrSession = conversation.getOtrSession();
1565		if (otrSession != null) {
1566			MessagePacket packet = new MessagePacket();
1567			packet.setType(MessagePacket.TYPE_CHAT);
1568			packet.setFrom(account.getJid());
1569			packet.addChild("private", "urn:xmpp:carbons:2");
1570			packet.addChild("no-copy", "urn:xmpp:hints");
1571			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
1572					+ otrSession.getSessionID().getUserID());
1573			try {
1574				packet.setBody(otrSession
1575						.transformSending(CryptoHelper.FILETRANSFER
1576							+ CryptoHelper.bytesToHex(symmetricKey)));
1577				sendMessagePacket(account, packet);
1578				conversation.setSymmetricKey(symmetricKey);
1579				return true;
1580			} catch (OtrException e) {
1581				return false;
1582			}
1583		}
1584		return false;
1585	}
1586
1587	public void pushContactToServer(Contact contact) {
1588		contact.resetOption(Contact.Options.DIRTY_DELETE);
1589		contact.setOption(Contact.Options.DIRTY_PUSH);
1590		Account account = contact.getAccount();
1591		if (account.getStatus() == Account.State.ONLINE) {
1592			boolean ask = contact.getOption(Contact.Options.ASKING);
1593			boolean sendUpdates = contact
1594				.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
1595				&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
1596			IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
1597			iq.query("jabber:iq:roster").addChild(contact.asElement());
1598			account.getXmppConnection().sendIqPacket(iq, null);
1599			if (sendUpdates) {
1600				sendPresencePacket(account,
1601						mPresenceGenerator.sendPresenceUpdatesTo(contact));
1602			}
1603			if (ask) {
1604				sendPresencePacket(account,
1605						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
1606			}
1607		}
1608	}
1609
1610	public void publishAvatar(Account account, Uri image,
1611			final UiCallback<Avatar> callback) {
1612		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
1613		final int size = Config.AVATAR_SIZE;
1614		final Avatar avatar = getFileBackend()
1615			.getPepAvatar(image, size, format);
1616		if (avatar != null) {
1617			avatar.height = size;
1618			avatar.width = size;
1619			if (format.equals(Bitmap.CompressFormat.WEBP)) {
1620				avatar.type = "image/webp";
1621			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1622				avatar.type = "image/jpeg";
1623			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
1624				avatar.type = "image/png";
1625			}
1626			if (!getFileBackend().save(avatar)) {
1627				callback.error(R.string.error_saving_avatar, avatar);
1628				return;
1629			}
1630			IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
1631			this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1632
1633				@Override
1634				public void onIqPacketReceived(Account account, IqPacket result) {
1635					if (result.getType() == IqPacket.TYPE_RESULT) {
1636						IqPacket packet = XmppConnectionService.this.mIqGenerator
1637							.publishAvatarMetadata(avatar);
1638						sendIqPacket(account, packet, new OnIqPacketReceived() {
1639
1640							@Override
1641							public void onIqPacketReceived(Account account,
1642									IqPacket result) {
1643								if (result.getType() == IqPacket.TYPE_RESULT) {
1644									if (account.setAvatar(avatar.getFilename())) {
1645										databaseBackend.updateAccount(account);
1646									}
1647									callback.success(avatar);
1648								} else {
1649									callback.error(
1650											R.string.error_publish_avatar_server_reject,
1651											avatar);
1652								}
1653							}
1654						});
1655					} else {
1656						callback.error(
1657								R.string.error_publish_avatar_server_reject,
1658								avatar);
1659					}
1660				}
1661			});
1662		} else {
1663			callback.error(R.string.error_publish_avatar_converting, null);
1664		}
1665	}
1666
1667	public void fetchAvatar(Account account, Avatar avatar) {
1668		fetchAvatar(account, avatar, null);
1669	}
1670
1671	public void fetchAvatar(Account account, final Avatar avatar,
1672			final UiCallback<Avatar> callback) {
1673		IqPacket packet = this.mIqGenerator.retrieveAvatar(avatar);
1674		sendIqPacket(account, packet, new OnIqPacketReceived() {
1675
1676			@Override
1677			public void onIqPacketReceived(Account account, IqPacket result) {
1678				final String ERROR = account.getJid().toBareJid()
1679						+ ": fetching avatar for " + avatar.owner + " failed ";
1680				if (result.getType() == IqPacket.TYPE_RESULT) {
1681					avatar.image = mIqParser.avatarData(result);
1682					if (avatar.image != null) {
1683						if (getFileBackend().save(avatar)) {
1684							if (account.getJid().toBareJid().equals(avatar.owner)) {
1685								if (account.setAvatar(avatar.getFilename())) {
1686									databaseBackend.updateAccount(account);
1687								}
1688								getAvatarService().clear(account);
1689								updateConversationUi();
1690								updateAccountUi();
1691							} else {
1692								Contact contact = account.getRoster()
1693										.getContact(avatar.owner);
1694								contact.setAvatar(avatar.getFilename());
1695								getAvatarService().clear(contact);
1696								updateConversationUi();
1697								updateRosterUi();
1698							}
1699							if (callback != null) {
1700								callback.success(avatar);
1701							}
1702							Log.d(Config.LOGTAG, account.getJid().toBareJid()
1703									+ ": succesfully fetched avatar for "
1704									+ avatar.owner);
1705							return;
1706						}
1707					} else {
1708
1709						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
1710					}
1711				} else {
1712					Element error = result.findChild("error");
1713					if (error == null) {
1714						Log.d(Config.LOGTAG, ERROR + "(server error)");
1715					} else {
1716						Log.d(Config.LOGTAG, ERROR + error.toString());
1717					}
1718				}
1719				if (callback != null) {
1720					callback.error(0, null);
1721				}
1722
1723			}
1724		});
1725	}
1726
1727	public void checkForAvatar(Account account,
1728			final UiCallback<Avatar> callback) {
1729		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
1730		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1731
1732			@Override
1733			public void onIqPacketReceived(Account account, IqPacket packet) {
1734				if (packet.getType() == IqPacket.TYPE_RESULT) {
1735					Element pubsub = packet.findChild("pubsub",
1736							"http://jabber.org/protocol/pubsub");
1737					if (pubsub != null) {
1738						Element items = pubsub.findChild("items");
1739						if (items != null) {
1740							Avatar avatar = Avatar.parseMetadata(items);
1741							if (avatar != null) {
1742								avatar.owner = account.getJid().toBareJid();
1743								if (fileBackend.isAvatarCached(avatar)) {
1744									if (account.setAvatar(avatar.getFilename())) {
1745										databaseBackend.updateAccount(account);
1746									}
1747									getAvatarService().clear(account);
1748									callback.success(avatar);
1749								} else {
1750									fetchAvatar(account, avatar, callback);
1751								}
1752								return;
1753							}
1754						}
1755					}
1756				}
1757				callback.error(0, null);
1758			}
1759		});
1760	}
1761
1762	public void deleteContactOnServer(Contact contact) {
1763		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
1764		contact.resetOption(Contact.Options.DIRTY_PUSH);
1765		contact.setOption(Contact.Options.DIRTY_DELETE);
1766		Account account = contact.getAccount();
1767		if (account.getStatus() == Account.State.ONLINE) {
1768			IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
1769			Element item = iq.query("jabber:iq:roster").addChild("item");
1770			item.setAttribute("jid", contact.getJid().toString());
1771			item.setAttribute("subscription", "remove");
1772			account.getXmppConnection().sendIqPacket(iq, null);
1773		}
1774	}
1775
1776	public void updateConversation(Conversation conversation) {
1777		this.databaseBackend.updateConversation(conversation);
1778	}
1779
1780	public void reconnectAccount(final Account account, final boolean force) {
1781		new Thread(new Runnable() {
1782
1783			@Override
1784			public void run() {
1785				if (account.getXmppConnection() != null) {
1786					disconnect(account, force);
1787				}
1788				if (!account.isOptionSet(Account.OPTION_DISABLED)) {
1789					if (account.getXmppConnection() == null) {
1790						account.setXmppConnection(createConnection(account));
1791					}
1792					Thread thread = new Thread(account.getXmppConnection());
1793					thread.start();
1794					scheduleWakeupCall((int) (Config.CONNECT_TIMEOUT * 1.2),
1795							false);
1796				} else {
1797					account.getRoster().clearPresences();
1798					account.setXmppConnection(null);
1799				}
1800			}
1801		}).start();
1802	}
1803
1804	public void invite(Conversation conversation, Jid contact) {
1805		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
1806		sendMessagePacket(conversation.getAccount(), packet);
1807	}
1808
1809	public void resetSendingToWaiting(Account account) {
1810		for (Conversation conversation : getConversations()) {
1811			if (conversation.getAccount() == account) {
1812				for (Message message : conversation.getMessages()) {
1813					if (message.getType() != Message.TYPE_IMAGE
1814							&& message.getStatus() == Message.STATUS_UNSEND) {
1815						markMessage(message, Message.STATUS_WAITING);
1816							}
1817				}
1818			}
1819		}
1820	}
1821
1822	public boolean markMessage(final Account account, final Jid recipient, final String uuid,
1823			final int status) {
1824		if (uuid == null) {
1825			return false;
1826		} else {
1827			for (Conversation conversation : getConversations()) {
1828				if (conversation.getContactJid().equals(recipient)
1829						&& conversation.getAccount().equals(account)) {
1830					return markMessage(conversation, uuid, status);
1831						}
1832			}
1833			return false;
1834		}
1835	}
1836
1837	public boolean markMessage(Conversation conversation, String uuid,
1838			int status) {
1839		if (uuid == null) {
1840			return false;
1841		} else {
1842			for (Message message : conversation.getMessages()) {
1843				if (uuid.equals(message.getUuid())
1844						|| (message.getStatus() >= Message.STATUS_SEND && uuid
1845							.equals(message.getRemoteMsgId()))) {
1846					markMessage(message, status);
1847					return true;
1848							}
1849			}
1850			return false;
1851		}
1852	}
1853
1854	public void markMessage(Message message, int status) {
1855		if (status == Message.STATUS_SEND_FAILED
1856				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
1857					.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
1858			return;
1859					}
1860		message.setStatus(status);
1861		databaseBackend.updateMessage(message);
1862		updateConversationUi();
1863	}
1864
1865	public SharedPreferences getPreferences() {
1866		return PreferenceManager
1867			.getDefaultSharedPreferences(getApplicationContext());
1868	}
1869
1870	public boolean forceEncryption() {
1871		return getPreferences().getBoolean("force_encryption", false);
1872	}
1873
1874	public boolean confirmMessages() {
1875		return getPreferences().getBoolean("confirm_messages", true);
1876	}
1877
1878	public boolean saveEncryptedMessages() {
1879		return !getPreferences().getBoolean("dont_save_encrypted", false);
1880	}
1881
1882	public boolean indicateReceived() {
1883		return getPreferences().getBoolean("indicate_received", false);
1884	}
1885
1886	public void updateConversationUi() {
1887		if (mOnConversationUpdate != null) {
1888			mOnConversationUpdate.onConversationUpdate();
1889		}
1890	}
1891
1892	public void updateAccountUi() {
1893		if (mOnAccountUpdate != null) {
1894			mOnAccountUpdate.onAccountUpdate();
1895		}
1896	}
1897
1898	public void updateRosterUi() {
1899		if (mOnRosterUpdate != null) {
1900			mOnRosterUpdate.onRosterUpdate();
1901		}
1902	}
1903
1904	public void updateMucRosterUi() {
1905		if (mOnMucRosterUpdate != null) {
1906			mOnMucRosterUpdate.onMucRosterUpdate();
1907		}
1908	}
1909
1910	public Account findAccountByJid(final Jid accountJid) {
1911		for (Account account : this.accounts) {
1912			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
1913				return account;
1914			}
1915		}
1916		return null;
1917	}
1918
1919	public Conversation findConversationByUuid(String uuid) {
1920		for (Conversation conversation : getConversations()) {
1921			if (conversation.getUuid().equals(uuid)) {
1922				return conversation;
1923			}
1924		}
1925		return null;
1926	}
1927
1928	public void markRead(Conversation conversation, boolean calledByUi) {
1929		mNotificationService.clear(conversation);
1930		final Message markable = conversation.getLatestMarkableMessage();
1931		conversation.markRead();
1932		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null && calledByUi) {
1933			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()+ ": sending read marker to " + markable.getCounterpart().toString());
1934			Account account = conversation.getAccount();
1935			final Jid to = markable.getCounterpart();
1936			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
1937			this.sendMessagePacket(conversation.getAccount(),packet);
1938		}
1939		if (!calledByUi) {
1940			updateConversationUi();
1941		}
1942	}
1943
1944	public void failWaitingOtrMessages(Conversation conversation) {
1945		for (Message message : conversation.getMessages()) {
1946			if (message.getEncryption() == Message.ENCRYPTION_OTR
1947					&& message.getStatus() == Message.STATUS_WAITING) {
1948				markMessage(message, Message.STATUS_SEND_FAILED);
1949					}
1950		}
1951	}
1952
1953	public SecureRandom getRNG() {
1954		return this.mRandom;
1955	}
1956
1957	public MemorizingTrustManager getMemorizingTrustManager() {
1958		return this.mMemorizingTrustManager;
1959	}
1960
1961	public PowerManager getPowerManager() {
1962		return this.pm;
1963	}
1964
1965	public LruCache<String, Bitmap> getBitmapCache() {
1966		return this.mBitmapCache;
1967	}
1968
1969	public void syncRosterToDisk(final Account account) {
1970		new Thread(new Runnable() {
1971
1972			@Override
1973			public void run() {
1974				databaseBackend.writeRoster(account.getRoster());
1975			}
1976		}).start();
1977
1978	}
1979
1980	public List<String> getKnownHosts() {
1981		List<String> hosts = new ArrayList<>();
1982		for (Account account : getAccounts()) {
1983			if (!hosts.contains(account.getServer().toString())) {
1984				hosts.add(account.getServer().toString());
1985			}
1986			for (Contact contact : account.getRoster().getContacts()) {
1987				if (contact.showInRoster()) {
1988					final String server = contact.getServer().toString();
1989					if (server != null && !hosts.contains(server)) {
1990						hosts.add(server);
1991					}
1992				}
1993			}
1994		}
1995		return hosts;
1996	}
1997
1998	public List<String> getKnownConferenceHosts() {
1999		ArrayList<String> mucServers = new ArrayList<>();
2000		for (Account account : accounts) {
2001			if (account.getXmppConnection() != null) {
2002				String server = account.getXmppConnection().getMucServer();
2003				if (server != null && !mucServers.contains(server)) {
2004					mucServers.add(server);
2005				}
2006			}
2007		}
2008		return mucServers;
2009	}
2010
2011	public void sendMessagePacket(Account account, MessagePacket packet) {
2012		XmppConnection connection = account.getXmppConnection();
2013		if (connection != null) {
2014			connection.sendMessagePacket(packet);
2015		}
2016	}
2017
2018	public void sendPresencePacket(Account account, PresencePacket packet) {
2019		XmppConnection connection = account.getXmppConnection();
2020		if (connection != null) {
2021			connection.sendPresencePacket(packet);
2022		}
2023	}
2024
2025	public void sendIqPacket(Account account, IqPacket packet,
2026			OnIqPacketReceived callback) {
2027		XmppConnection connection = account.getXmppConnection();
2028		if (connection != null) {
2029			connection.sendIqPacket(packet, callback);
2030		}
2031	}
2032
2033	public MessageGenerator getMessageGenerator() {
2034		return this.mMessageGenerator;
2035	}
2036
2037	public PresenceGenerator getPresenceGenerator() {
2038		return this.mPresenceGenerator;
2039	}
2040
2041	public IqGenerator getIqGenerator() {
2042		return this.mIqGenerator;
2043	}
2044
2045	public JingleConnectionManager getJingleConnectionManager() {
2046		return this.mJingleConnectionManager;
2047	}
2048
2049	public MessageArchiveService getMessageArchiveService() {
2050		return this.mMessageArchiveService;
2051	}
2052
2053	public List<Contact> findContacts(Jid jid) {
2054		ArrayList<Contact> contacts = new ArrayList<>();
2055		for (Account account : getAccounts()) {
2056			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2057				Contact contact = account.getRoster().getContactFromRoster(jid);
2058				if (contact != null) {
2059					contacts.add(contact);
2060				}
2061			}
2062		}
2063		return contacts;
2064	}
2065
2066	public NotificationService getNotificationService() {
2067		return this.mNotificationService;
2068	}
2069
2070	public HttpConnectionManager getHttpConnectionManager() {
2071		return this.mHttpConnectionManager;
2072	}
2073
2074	public void resendFailedMessages(Message message) {
2075		List<Message> messages = new ArrayList<>();
2076		Message current = message;
2077		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2078			messages.add(current);
2079			if (current.mergeable(current.next())) {
2080				current = current.next();
2081			} else {
2082				break;
2083			}
2084		}
2085		for (Message msg : messages) {
2086			markMessage(msg, Message.STATUS_WAITING);
2087			this.resendMessage(msg);
2088		}
2089	}
2090
2091	public interface OnConversationUpdate {
2092		public void onConversationUpdate();
2093	}
2094
2095	public interface OnAccountUpdate {
2096		public void onAccountUpdate();
2097	}
2098
2099	public interface OnRosterUpdate {
2100		public void onRosterUpdate();
2101	}
2102
2103	public interface OnMucRosterUpdate {
2104		public void onMucRosterUpdate();
2105	}
2106
2107	private interface OnConferenceOptionsPushed {
2108		public void onPushSucceeded();
2109		public void onPushFailed();
2110	}
2111
2112	public class XmppConnectionBinder extends Binder {
2113		public XmppConnectionService getService() {
2114			return XmppConnectionService.this;
2115		}
2116	}
2117}