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