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