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		updateMemorizingTrustmanager();
 536		final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
 537		final int cacheSize = maxMemory / 8;
 538		this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
 539			@Override
 540			protected int sizeOf(final String key, final Bitmap bitmap) {
 541				return bitmap.getByteCount() / 1024;
 542			}
 543		};
 544
 545		this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
 546		this.accounts = databaseBackend.getAccounts();
 547
 548		for (final Account account : this.accounts) {
 549			account.initOtrEngine(this);
 550		}
 551		restoreFromDatabase();
 552
 553		getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
 554		this.fileObserver.startWatching();
 555		this.pgpServiceConnection = new OpenPgpServiceConnection(getApplicationContext(), "org.sufficientlysecure.keychain");
 556		this.pgpServiceConnection.bindToService();
 557
 558		this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 559		this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"XmppConnectionService");
 560		toggleForegroundService();
 561	}
 562
 563	public void toggleForegroundService() {
 564		if (getPreferences().getBoolean("keep_foreground_service",false)) {
 565			startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
 566		} else {
 567			stopForeground(true);
 568		}
 569	}
 570
 571	@Override
 572	public void onTaskRemoved(final Intent rootIntent) {
 573		super.onTaskRemoved(rootIntent);
 574		if (!getPreferences().getBoolean("keep_foreground_service",false)) {
 575			this.logoutAndSave();
 576		}
 577	}
 578
 579	private void logoutAndSave() {
 580		for (final Account account : accounts) {
 581			databaseBackend.writeRoster(account.getRoster());
 582			if (account.getXmppConnection() != null) {
 583				disconnect(account, false);
 584			}
 585		}
 586		Context context = getApplicationContext();
 587		AlarmManager alarmManager = (AlarmManager) context
 588			.getSystemService(Context.ALARM_SERVICE);
 589		Intent intent = new Intent(context, EventReceiver.class);
 590		alarmManager.cancel(PendingIntent.getBroadcast(context, 0, intent, 0));
 591		Log.d(Config.LOGTAG, "good bye");
 592		stopSelf();
 593	}
 594
 595	protected void scheduleWakeUpCall(int seconds, int requestCode) {
 596		final long timeToWake = SystemClock.elapsedRealtime() + (seconds + 1) * 1000;
 597
 598		Context context = getApplicationContext();
 599		AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
 600
 601		Intent intent = new Intent(context, EventReceiver.class);
 602		intent.setAction("ping");
 603		PendingIntent alarmIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0);
 604		alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, alarmIntent);
 605	}
 606
 607	public XmppConnection createConnection(final Account account) {
 608		final SharedPreferences sharedPref = getPreferences();
 609		account.setResource(sharedPref.getString("resource", "mobile")
 610				.toLowerCase(Locale.getDefault()));
 611		final XmppConnection connection = new XmppConnection(account, this);
 612		connection.setOnMessagePacketReceivedListener(this.mMessageParser);
 613		connection.setOnStatusChangedListener(this.statusListener);
 614		connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
 615		connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
 616		connection.setOnJinglePacketReceivedListener(this.jingleListener);
 617		connection.setOnBindListener(this.mOnBindListener);
 618		connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
 619		connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
 620		return connection;
 621	}
 622
 623	public void sendChatState(Conversation conversation) {
 624		if (sendChatStates()) {
 625			MessagePacket packet = mMessageGenerator.generateChatState(conversation);
 626			sendMessagePacket(conversation.getAccount(), packet);
 627		}
 628	}
 629
 630	public void sendMessage(final Message message) {
 631		final Account account = message.getConversation().getAccount();
 632		account.deactivateGracePeriod();
 633		final Conversation conv = message.getConversation();
 634		MessagePacket packet = null;
 635		boolean saveInDb = true;
 636		boolean send = false;
 637		if (account.getStatus() == Account.State.ONLINE
 638				&& account.getXmppConnection() != null) {
 639			if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
 640				if (message.getCounterpart() != null) {
 641					if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 642						if (!conv.hasValidOtrSession()) {
 643							conv.startOtrSession(message.getCounterpart().getResourcepart(),true);
 644							message.setStatus(Message.STATUS_WAITING);
 645						} else if (conv.hasValidOtrSession()
 646								&& conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
 647							mJingleConnectionManager
 648								.createNewConnection(message);
 649								}
 650					} else {
 651						mJingleConnectionManager.createNewConnection(message);
 652					}
 653				} else {
 654					if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 655						conv.startOtrIfNeeded();
 656					}
 657					message.setStatus(Message.STATUS_WAITING);
 658				}
 659			} else {
 660				if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 661					if (!conv.hasValidOtrSession() && (message.getCounterpart() != null)) {
 662						conv.startOtrSession(message.getCounterpart().getResourcepart(), true);
 663						message.setStatus(Message.STATUS_WAITING);
 664					} else if (conv.hasValidOtrSession()) {
 665						if (conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
 666							packet = mMessageGenerator.generateOtrChat(message);
 667							send = true;
 668						} else {
 669							message.setStatus(Message.STATUS_WAITING);
 670							conv.startOtrIfNeeded();
 671						}
 672					} else {
 673						message.setStatus(Message.STATUS_WAITING);
 674					}
 675				} else if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 676					message.getConversation().endOtrIfNeeded();
 677					message.getConversation().findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
 678						@Override
 679						public void onMessageFound(Message message) {
 680							markMessage(message,Message.STATUS_SEND_FAILED);
 681						}
 682					});
 683					packet = mMessageGenerator.generatePgpChat(message);
 684					send = true;
 685				} else {
 686					message.getConversation().endOtrIfNeeded();
 687					message.getConversation().findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
 688						@Override
 689						public void onMessageFound(Message message) {
 690							markMessage(message,Message.STATUS_SEND_FAILED);
 691						}
 692					});
 693					packet = mMessageGenerator.generateChat(message);
 694					send = true;
 695				}
 696			}
 697			if (!account.getXmppConnection().getFeatures().sm()
 698					&& conv.getMode() != Conversation.MODE_MULTI) {
 699				message.setStatus(Message.STATUS_SEND);
 700					}
 701		} else {
 702			message.setStatus(Message.STATUS_WAITING);
 703			if (message.getType() == Message.TYPE_TEXT) {
 704				if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 705					String pgpBody = message.getEncryptedBody();
 706					String decryptedBody = message.getBody();
 707					message.setBody(pgpBody);
 708					message.setEncryption(Message.ENCRYPTION_PGP);
 709					databaseBackend.createMessage(message);
 710					saveInDb = false;
 711					message.setBody(decryptedBody);
 712					message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 713				} else if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 714					if (!conv.hasValidOtrSession()
 715							&& message.getCounterpart() != null) {
 716						conv.startOtrSession(message.getCounterpart().getResourcepart(), false);
 717							}
 718				}
 719			}
 720
 721		}
 722		conv.add(message);
 723		if (saveInDb) {
 724			if (message.getEncryption() == Message.ENCRYPTION_NONE
 725					|| saveEncryptedMessages()) {
 726				databaseBackend.createMessage(message);
 727					}
 728		}
 729		if ((send) && (packet != null)) {
 730			if (conv.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
 731				if (this.sendChatStates()) {
 732					packet.addChild(ChatState.toElement(conv.getOutgoingChatState()));
 733				}
 734			}
 735			sendMessagePacket(account, packet);
 736		}
 737		updateConversationUi();
 738	}
 739
 740	private void sendUnsentMessages(final Conversation conversation) {
 741		conversation.findWaitingMessages(new Conversation.OnMessageFound() {
 742
 743			@Override
 744			public void onMessageFound(Message message) {
 745				resendMessage(message);
 746			}
 747		});
 748	}
 749
 750	private void resendMessage(final Message message) {
 751		Account account = message.getConversation().getAccount();
 752		MessagePacket packet = null;
 753		if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 754			Presences presences = message.getConversation().getContact()
 755				.getPresences();
 756			if (!message.getConversation().hasValidOtrSession()) {
 757				if ((message.getCounterpart() != null)
 758						&& (presences.has(message.getCounterpart().getResourcepart()))) {
 759					message.getConversation().startOtrSession(message.getCounterpart().getResourcepart(), true);
 760				} else {
 761					if (presences.size() == 1) {
 762						String presence = presences.asStringArray()[0];
 763						message.getConversation().startOtrSession(presence, true);
 764					}
 765				}
 766			} else {
 767				if (message.getConversation().getOtrSession()
 768						.getSessionStatus() == SessionStatus.ENCRYPTED) {
 769					try {
 770						message.setCounterpart(Jid.fromSessionID(message.getConversation().getOtrSession().getSessionID()));
 771						if (message.getType() == Message.TYPE_TEXT) {
 772							packet = mMessageGenerator.generateOtrChat(message,
 773									true);
 774						} else if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
 775							mJingleConnectionManager.createNewConnection(message);
 776						}
 777					} catch (final InvalidJidException ignored) {
 778
 779					}
 780						}
 781			}
 782		} else if (message.getType() == Message.TYPE_TEXT) {
 783			if (message.getEncryption() == Message.ENCRYPTION_NONE) {
 784				packet = mMessageGenerator.generateChat(message, true);
 785			} else if ((message.getEncryption() == Message.ENCRYPTION_DECRYPTED)
 786					|| (message.getEncryption() == Message.ENCRYPTION_PGP)) {
 787				packet = mMessageGenerator.generatePgpChat(message, true);
 788					}
 789		} else if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
 790			Contact contact = message.getConversation().getContact();
 791			Presences presences = contact.getPresences();
 792			if ((message.getCounterpart() != null)
 793					&& (presences.has(message.getCounterpart().getResourcepart()))) {
 794				markMessage(message, Message.STATUS_OFFERED);
 795				mJingleConnectionManager.createNewConnection(message);
 796			} else {
 797				if (presences.size() == 1) {
 798					String presence = presences.asStringArray()[0];
 799					try {
 800						message.setCounterpart(Jid.fromParts(contact.getJid().getLocalpart(), contact.getJid().getDomainpart(), presence));
 801					} catch (InvalidJidException e) {
 802						return;
 803					}
 804					markMessage(message, Message.STATUS_OFFERED);
 805					mJingleConnectionManager.createNewConnection(message);
 806				}
 807			}
 808		}
 809		if (packet != null) {
 810			if (!account.getXmppConnection().getFeatures().sm()
 811					&& message.getConversation().getMode() != Conversation.MODE_MULTI) {
 812				markMessage(message, Message.STATUS_SEND);
 813			} else {
 814				markMessage(message, Message.STATUS_UNSEND);
 815			}
 816			if (message.getConversation().setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
 817				if (this.sendChatStates()) {
 818					packet.addChild(ChatState.toElement(message.getConversation().getOutgoingChatState()));
 819				}
 820			}
 821			sendMessagePacket(account, packet);
 822		}
 823	}
 824
 825	public void fetchRosterFromServer(final Account account) {
 826		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
 827		if (!"".equals(account.getRosterVersion())) {
 828			Log.d(Config.LOGTAG, account.getJid().toBareJid()
 829					+ ": fetching roster version " + account.getRosterVersion());
 830		} else {
 831			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
 832		}
 833		iqPacket.query(Xmlns.ROSTER).setAttribute("ver",
 834				account.getRosterVersion());
 835		account.getXmppConnection().sendIqPacket(iqPacket, mIqParser);
 836	}
 837
 838	public void fetchBookmarks(final Account account) {
 839		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
 840		final Element query = iqPacket.query("jabber:iq:private");
 841		query.addChild("storage", "storage:bookmarks");
 842		final OnIqPacketReceived callback = new OnIqPacketReceived() {
 843
 844			@Override
 845			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 846				final Element query = packet.query();
 847				final List<Bookmark> bookmarks = new CopyOnWriteArrayList<>();
 848				final Element storage = query.findChild("storage",
 849						"storage:bookmarks");
 850				if (storage != null) {
 851					for (final Element item : storage.getChildren()) {
 852						if (item.getName().equals("conference")) {
 853							final Bookmark bookmark = Bookmark.parse(item, account);
 854							bookmarks.add(bookmark);
 855							Conversation conversation = find(bookmark);
 856							if (conversation != null) {
 857								conversation.setBookmark(bookmark);
 858							} else if (bookmark.autojoin() && bookmark.getJid() != null) {
 859								conversation = findOrCreateConversation(
 860										account, bookmark.getJid(), true);
 861								conversation.setBookmark(bookmark);
 862								joinMuc(conversation);
 863							}
 864						}
 865					}
 866				}
 867				account.setBookmarks(bookmarks);
 868			}
 869		};
 870		sendIqPacket(account, iqPacket, callback);
 871	}
 872
 873	public void pushBookmarks(Account account) {
 874		IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
 875		Element query = iqPacket.query("jabber:iq:private");
 876		Element storage = query.addChild("storage", "storage:bookmarks");
 877		for (Bookmark bookmark : account.getBookmarks()) {
 878			storage.addChild(bookmark);
 879		}
 880		sendIqPacket(account, iqPacket, null);
 881	}
 882
 883	public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
 884		if (mPhoneContactMergerThread != null) {
 885			mPhoneContactMergerThread.interrupt();
 886		}
 887		mPhoneContactMergerThread = new Thread(new Runnable() {
 888			@Override
 889			public void run() {
 890				Log.d(Config.LOGTAG,"start merging phone contacts with roster");
 891				for (Account account : accounts) {
 892					account.getRoster().clearSystemAccounts();
 893					for (Bundle phoneContact : phoneContacts) {
 894						if (Thread.interrupted()) {
 895							Log.d(Config.LOGTAG,"interrupted merging phone contacts");
 896							return;
 897						}
 898						Jid jid;
 899						try {
 900							jid = Jid.fromString(phoneContact.getString("jid"));
 901						} catch (final InvalidJidException e) {
 902							continue;
 903						}
 904						final Contact contact = account.getRoster().getContact(jid);
 905						String systemAccount = phoneContact.getInt("phoneid")
 906							+ "#"
 907							+ phoneContact.getString("lookup");
 908						contact.setSystemAccount(systemAccount);
 909						contact.setPhotoUri(phoneContact.getString("photouri"));
 910						getAvatarService().clear(contact);
 911						contact.setSystemName(phoneContact.getString("displayname"));
 912					}
 913				}
 914				Log.d(Config.LOGTAG,"finished merging phone contacts");
 915				updateAccountUi();
 916			}
 917		});
 918		mPhoneContactMergerThread.start();
 919	}
 920
 921	private void restoreFromDatabase() {
 922		synchronized (this.conversations) {
 923			final Map<String, Account> accountLookupTable = new Hashtable<>();
 924			for (Account account : this.accounts) {
 925				accountLookupTable.put(account.getUuid(), account);
 926			}
 927			this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
 928			for (Conversation conversation : this.conversations) {
 929				Account account = accountLookupTable.get(conversation.getAccountUuid());
 930				conversation.setAccount(account);
 931			}
 932			new Thread(new Runnable() {
 933				@Override
 934				public void run() {
 935					Log.d(Config.LOGTAG,"restoring roster");
 936					for(Account account : accounts) {
 937						databaseBackend.readRoster(account.getRoster());
 938					}
 939					getBitmapCache().evictAll();
 940					Looper.prepare();
 941					PhoneHelper.loadPhoneContacts(getApplicationContext(),
 942							new CopyOnWriteArrayList<Bundle>(),
 943							XmppConnectionService.this);
 944					Log.d(Config.LOGTAG,"restoring messages");
 945					for (Conversation conversation : conversations) {
 946						conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
 947						checkDeletedFiles(conversation);
 948					}
 949					mRestoredFromDatabase = true;
 950					Log.d(Config.LOGTAG,"restored all messages");
 951					updateConversationUi();
 952				}
 953			}).start();
 954		}
 955	}
 956
 957	public List<Conversation> getConversations() {
 958		return this.conversations;
 959	}
 960
 961	private void checkDeletedFiles(Conversation conversation) {
 962		conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
 963
 964			@Override
 965			public void onMessageFound(Message message) {
 966				if (!getFileBackend().isFileAvailable(message)) {
 967					message.setDownloadable(new DownloadablePlaceholder(Downloadable.STATUS_DELETED));
 968				}
 969			}
 970		});
 971	}
 972
 973	private void markFileDeleted(String uuid) {
 974		for (Conversation conversation : getConversations()) {
 975			Message message = conversation.findMessageWithFileAndUuid(uuid);
 976			if (message != null) {
 977				if (!getFileBackend().isFileAvailable(message)) {
 978					message.setDownloadable(new DownloadablePlaceholder(Downloadable.STATUS_DELETED));
 979					updateConversationUi();
 980				}
 981				return;
 982			}
 983		}
 984	}
 985
 986	public void populateWithOrderedConversations(final List<Conversation> list) {
 987		populateWithOrderedConversations(list, true);
 988	}
 989
 990	public void populateWithOrderedConversations(final List<Conversation> list, boolean includeConferences) {
 991		list.clear();
 992		if (includeConferences) {
 993			list.addAll(getConversations());
 994		} else {
 995			for (Conversation conversation : getConversations()) {
 996				if (conversation.getMode() == Conversation.MODE_SINGLE) {
 997					list.add(conversation);
 998				}
 999			}
1000		}
1001		Collections.sort(list, new Comparator<Conversation>() {
1002			@Override
1003			public int compare(Conversation lhs, Conversation rhs) {
1004				Message left = lhs.getLatestMessage();
1005				Message right = rhs.getLatestMessage();
1006				if (left.getTimeSent() > right.getTimeSent()) {
1007					return -1;
1008				} else if (left.getTimeSent() < right.getTimeSent()) {
1009					return 1;
1010				} else {
1011					return 0;
1012				}
1013			}
1014		});
1015	}
1016
1017	public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1018		Log.d(Config.LOGTAG,"load more messages for "+conversation.getName() + " prior to "+MessageGenerator.getTimestamp(timestamp));
1019		if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation,callback)) {
1020			return;
1021		}
1022		new Thread(new Runnable() {
1023			@Override
1024			public void run() {
1025				final Account account = conversation.getAccount();
1026				List<Message> messages = databaseBackend.getMessages(conversation, 50,timestamp);
1027				if (messages.size() > 0) {
1028					conversation.addAll(0, messages);
1029					checkDeletedFiles(conversation);
1030					callback.onMoreMessagesLoaded(messages.size(), conversation);
1031				} else if (conversation.hasMessagesLeftOnServer()
1032						&& account.isOnlineAndConnected()
1033						&& account.getXmppConnection().getFeatures().mam()) {
1034					MessageArchiveService.Query query = getMessageArchiveService().query(conversation,0,timestamp - 1);
1035					if (query != null) {
1036						query.setCallback(callback);
1037					}
1038					callback.informUser(R.string.fetching_history_from_server);
1039				}
1040			}
1041		}).start();
1042	}
1043
1044	public List<Account> getAccounts() {
1045		return this.accounts;
1046	}
1047
1048	public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1049		for (final Conversation conversation : haystack) {
1050			if (conversation.getContact() == contact) {
1051				return conversation;
1052			}
1053		}
1054		return null;
1055	}
1056
1057	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1058		if (jid == null) {
1059			return null;
1060		}
1061		for (final Conversation conversation : haystack) {
1062			if ((account == null || conversation.getAccount() == account)
1063					&& (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1064				return conversation;
1065			}
1066		}
1067		return null;
1068	}
1069
1070	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1071		return this.findOrCreateConversation(account, jid, muc, null);
1072	}
1073
1074	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1075		synchronized (this.conversations) {
1076			Conversation conversation = find(account, jid);
1077			if (conversation != null) {
1078				return conversation;
1079			}
1080			conversation = databaseBackend.findConversation(account, jid);
1081			if (conversation != null) {
1082				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1083				conversation.setAccount(account);
1084				if (muc) {
1085					conversation.setMode(Conversation.MODE_MULTI);
1086					conversation.setContactJid(jid);
1087				} else {
1088					conversation.setMode(Conversation.MODE_SINGLE);
1089					conversation.setContactJid(jid.toBareJid());
1090				}
1091				conversation.setNextEncryption(-1);
1092				conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1093				this.databaseBackend.updateConversation(conversation);
1094			} else {
1095				String conversationName;
1096				Contact contact = account.getRoster().getContact(jid);
1097				if (contact != null) {
1098					conversationName = contact.getDisplayName();
1099				} else {
1100					conversationName = jid.getLocalpart();
1101				}
1102				if (muc) {
1103					conversation = new Conversation(conversationName, account, jid,
1104							Conversation.MODE_MULTI);
1105				} else {
1106					conversation = new Conversation(conversationName, account, jid.toBareJid(),
1107							Conversation.MODE_SINGLE);
1108				}
1109				this.databaseBackend.createConversation(conversation);
1110			}
1111			if (account.getXmppConnection() != null
1112					&& account.getXmppConnection().getFeatures().mam()
1113					&& !muc) {
1114				if (query == null) {
1115					this.mMessageArchiveService.query(conversation);
1116				} else {
1117					if (query.getConversation() == null) {
1118						this.mMessageArchiveService.query(conversation, query.getStart());
1119					}
1120				}
1121			}
1122			checkDeletedFiles(conversation);
1123			this.conversations.add(conversation);
1124			updateConversationUi();
1125			return conversation;
1126		}
1127	}
1128
1129	public void archiveConversation(Conversation conversation) {
1130		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1131		conversation.setNextEncryption(-1);
1132		synchronized (this.conversations) {
1133			if (conversation.getMode() == Conversation.MODE_MULTI) {
1134				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1135					Bookmark bookmark = conversation.getBookmark();
1136					if (bookmark != null && bookmark.autojoin()) {
1137						bookmark.setAutojoin(false);
1138						pushBookmarks(bookmark.getAccount());
1139					}
1140				}
1141				leaveMuc(conversation);
1142			} else {
1143				conversation.endOtrIfNeeded();
1144			}
1145			this.databaseBackend.updateConversation(conversation);
1146			this.conversations.remove(conversation);
1147			updateConversationUi();
1148		}
1149	}
1150
1151	public void createAccount(final Account account) {
1152		account.initOtrEngine(this);
1153		databaseBackend.createAccount(account);
1154		this.accounts.add(account);
1155		this.reconnectAccountInBackground(account);
1156		updateAccountUi();
1157	}
1158
1159	public void updateAccount(final Account account) {
1160		this.statusListener.onStatusChanged(account);
1161		databaseBackend.updateAccount(account);
1162		reconnectAccount(account, false);
1163		updateAccountUi();
1164		getNotificationService().updateErrorNotification();
1165	}
1166
1167	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1168		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1169		sendIqPacket(account, iq, new OnIqPacketReceived() {
1170			@Override
1171			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1172				if (packet.getType() == IqPacket.TYPE.RESULT) {
1173					account.setPassword(newPassword);
1174					databaseBackend.updateAccount(account);
1175					callback.onPasswordChangeSucceeded();
1176				} else {
1177					callback.onPasswordChangeFailed();
1178				}
1179			}
1180		});
1181	}
1182
1183	public void deleteAccount(final Account account) {
1184		synchronized (this.conversations) {
1185			for (final Conversation conversation : conversations) {
1186				if (conversation.getAccount() == account) {
1187					if (conversation.getMode() == Conversation.MODE_MULTI) {
1188						leaveMuc(conversation);
1189					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1190						conversation.endOtrIfNeeded();
1191					}
1192					conversations.remove(conversation);
1193				}
1194			}
1195			if (account.getXmppConnection() != null) {
1196				this.disconnect(account, true);
1197			}
1198			databaseBackend.deleteAccount(account);
1199			this.accounts.remove(account);
1200			updateAccountUi();
1201			getNotificationService().updateErrorNotification();
1202		}
1203	}
1204
1205	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1206		synchronized (this) {
1207			if (checkListeners()) {
1208				switchToForeground();
1209			}
1210			this.mOnConversationUpdate = listener;
1211			this.mNotificationService.setIsInForeground(true);
1212			if (this.convChangedListenerCount < 2) {
1213				this.convChangedListenerCount++;
1214			}
1215		}
1216	}
1217
1218	public void removeOnConversationListChangedListener() {
1219		synchronized (this) {
1220			this.convChangedListenerCount--;
1221			if (this.convChangedListenerCount <= 0) {
1222				this.convChangedListenerCount = 0;
1223				this.mOnConversationUpdate = null;
1224				this.mNotificationService.setIsInForeground(false);
1225				if (checkListeners()) {
1226					switchToBackground();
1227				}
1228			}
1229		}
1230	}
1231
1232	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1233		synchronized (this) {
1234			if (checkListeners()) {
1235				switchToForeground();
1236			}
1237			this.mOnAccountUpdate = listener;
1238			if (this.accountChangedListenerCount < 2) {
1239				this.accountChangedListenerCount++;
1240			}
1241		}
1242	}
1243
1244	public void removeOnAccountListChangedListener() {
1245		synchronized (this) {
1246			this.accountChangedListenerCount--;
1247			if (this.accountChangedListenerCount <= 0) {
1248				this.mOnAccountUpdate = null;
1249				this.accountChangedListenerCount = 0;
1250				if (checkListeners()) {
1251					switchToBackground();
1252				}
1253			}
1254		}
1255	}
1256
1257	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1258		synchronized (this) {
1259			if (checkListeners()) {
1260				switchToForeground();
1261			}
1262			this.mOnRosterUpdate = listener;
1263			if (this.rosterChangedListenerCount < 2) {
1264				this.rosterChangedListenerCount++;
1265			}
1266		}
1267	}
1268
1269	public void removeOnRosterUpdateListener() {
1270		synchronized (this) {
1271			this.rosterChangedListenerCount--;
1272			if (this.rosterChangedListenerCount <= 0) {
1273				this.rosterChangedListenerCount = 0;
1274				this.mOnRosterUpdate = null;
1275				if (checkListeners()) {
1276					switchToBackground();
1277				}
1278			}
1279		}
1280	}
1281
1282	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1283		synchronized (this) {
1284			if (checkListeners()) {
1285				switchToForeground();
1286			}
1287			this.mOnUpdateBlocklist = listener;
1288			if (this.updateBlocklistListenerCount < 2) {
1289				this.updateBlocklistListenerCount++;
1290			}
1291		}
1292	}
1293
1294	public void removeOnUpdateBlocklistListener() {
1295		synchronized (this) {
1296			this.updateBlocklistListenerCount--;
1297			if (this.updateBlocklistListenerCount <= 0) {
1298				this.updateBlocklistListenerCount = 0;
1299				this.mOnUpdateBlocklist = null;
1300				if (checkListeners()) {
1301					switchToBackground();
1302				}
1303			}
1304		}
1305	}
1306
1307	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1308		synchronized (this) {
1309			if (checkListeners()) {
1310				switchToForeground();
1311			}
1312			this.mOnMucRosterUpdate = listener;
1313			if (this.mucRosterChangedListenerCount < 2) {
1314				this.mucRosterChangedListenerCount++;
1315			}
1316		}
1317	}
1318
1319	public void removeOnMucRosterUpdateListener() {
1320		synchronized (this) {
1321			this.mucRosterChangedListenerCount--;
1322			if (this.mucRosterChangedListenerCount <= 0) {
1323				this.mucRosterChangedListenerCount = 0;
1324				this.mOnMucRosterUpdate = null;
1325				if (checkListeners()) {
1326					switchToBackground();
1327				}
1328			}
1329		}
1330	}
1331
1332	private boolean checkListeners() {
1333		return (this.mOnAccountUpdate == null
1334				&& this.mOnConversationUpdate == null
1335				&& this.mOnRosterUpdate == null
1336				&& this.mOnUpdateBlocklist == null);
1337	}
1338
1339	private void switchToForeground() {
1340		for (Account account : getAccounts()) {
1341			if (account.getStatus() == Account.State.ONLINE) {
1342				XmppConnection connection = account.getXmppConnection();
1343				if (connection != null && connection.getFeatures().csi()) {
1344					connection.sendActive();
1345				}
1346			}
1347		}
1348		Log.d(Config.LOGTAG, "app switched into foreground");
1349	}
1350
1351	private void switchToBackground() {
1352		for (Account account : getAccounts()) {
1353			if (account.getStatus() == Account.State.ONLINE) {
1354				XmppConnection connection = account.getXmppConnection();
1355				if (connection != null && connection.getFeatures().csi()) {
1356					connection.sendInactive();
1357				}
1358			}
1359		}
1360		for(Conversation conversation : getConversations()) {
1361			conversation.setIncomingChatState(ChatState.ACTIVE);
1362		}
1363		this.mNotificationService.setIsInForeground(false);
1364		Log.d(Config.LOGTAG, "app switched into background");
1365	}
1366
1367	private void connectMultiModeConversations(Account account) {
1368		List<Conversation> conversations = getConversations();
1369		for (Conversation conversation : conversations) {
1370			if ((conversation.getMode() == Conversation.MODE_MULTI)
1371					&& (conversation.getAccount() == account)) {
1372				conversation.resetMucOptions();
1373				joinMuc(conversation);
1374			}
1375		}
1376	}
1377
1378	public void joinMuc(Conversation conversation) {
1379		Account account = conversation.getAccount();
1380		account.pendingConferenceJoins.remove(conversation);
1381		account.pendingConferenceLeaves.remove(conversation);
1382		if (account.getStatus() == Account.State.ONLINE) {
1383			final String nick = conversation.getMucOptions().getProposedNick();
1384			final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1385			if (joinJid == null) {
1386				return; //safety net
1387			}
1388			Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1389			PresencePacket packet = new PresencePacket();
1390			packet.setFrom(conversation.getAccount().getJid());
1391			packet.setTo(joinJid);
1392			Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1393			if (conversation.getMucOptions().getPassword() != null) {
1394				x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1395			}
1396			x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1397			String sig = account.getPgpSignature();
1398			if (sig != null) {
1399				packet.addChild("status").setContent("online");
1400				packet.addChild("x", "jabber:x:signed").setContent(sig);
1401			}
1402			sendPresencePacket(account, packet);
1403			fetchConferenceConfiguration(conversation);
1404			if (!joinJid.equals(conversation.getJid())) {
1405				conversation.setContactJid(joinJid);
1406				databaseBackend.updateConversation(conversation);
1407			}
1408			conversation.setHasMessagesLeftOnServer(false);
1409		} else {
1410			account.pendingConferenceJoins.add(conversation);
1411		}
1412	}
1413
1414	public void providePasswordForMuc(Conversation conversation, String password) {
1415		if (conversation.getMode() == Conversation.MODE_MULTI) {
1416			conversation.getMucOptions().setPassword(password);
1417			if (conversation.getBookmark() != null) {
1418				conversation.getBookmark().setAutojoin(true);
1419				pushBookmarks(conversation.getAccount());
1420			}
1421			databaseBackend.updateConversation(conversation);
1422			joinMuc(conversation);
1423		}
1424	}
1425
1426	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1427		final MucOptions options = conversation.getMucOptions();
1428		final Jid joinJid = options.createJoinJid(nick);
1429		if (options.online()) {
1430			Account account = conversation.getAccount();
1431			options.setOnRenameListener(new OnRenameListener() {
1432
1433				@Override
1434				public void onSuccess() {
1435					conversation.setContactJid(joinJid);
1436					databaseBackend.updateConversation(conversation);
1437					Bookmark bookmark = conversation.getBookmark();
1438					if (bookmark != null) {
1439						bookmark.setNick(nick);
1440						pushBookmarks(bookmark.getAccount());
1441					}
1442					callback.success(conversation);
1443				}
1444
1445				@Override
1446				public void onFailure() {
1447					callback.error(R.string.nick_in_use, conversation);
1448				}
1449			});
1450
1451			PresencePacket packet = new PresencePacket();
1452			packet.setTo(joinJid);
1453			packet.setFrom(conversation.getAccount().getJid());
1454
1455			String sig = account.getPgpSignature();
1456			if (sig != null) {
1457				packet.addChild("status").setContent("online");
1458				packet.addChild("x", "jabber:x:signed").setContent(sig);
1459			}
1460			sendPresencePacket(account, packet);
1461		} else {
1462			conversation.setContactJid(joinJid);
1463			databaseBackend.updateConversation(conversation);
1464			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1465				Bookmark bookmark = conversation.getBookmark();
1466				if (bookmark != null) {
1467					bookmark.setNick(nick);
1468					pushBookmarks(bookmark.getAccount());
1469				}
1470				joinMuc(conversation);
1471			}
1472		}
1473	}
1474
1475	public void leaveMuc(Conversation conversation) {
1476		Account account = conversation.getAccount();
1477		account.pendingConferenceJoins.remove(conversation);
1478		account.pendingConferenceLeaves.remove(conversation);
1479		if (account.getStatus() == Account.State.ONLINE) {
1480			PresencePacket packet = new PresencePacket();
1481			packet.setTo(conversation.getJid());
1482			packet.setFrom(conversation.getAccount().getJid());
1483			packet.setAttribute("type", "unavailable");
1484			sendPresencePacket(conversation.getAccount(), packet);
1485			conversation.getMucOptions().setOffline();
1486			conversation.deregisterWithBookmark();
1487			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1488					+ ": leaving muc " + conversation.getJid());
1489		} else {
1490			account.pendingConferenceLeaves.add(conversation);
1491		}
1492	}
1493
1494	private String findConferenceServer(final Account account) {
1495		String server;
1496		if (account.getXmppConnection() != null) {
1497			server = account.getXmppConnection().getMucServer();
1498			if (server != null) {
1499				return server;
1500			}
1501		}
1502		for (Account other : getAccounts()) {
1503			if (other != account && other.getXmppConnection() != null) {
1504				server = other.getXmppConnection().getMucServer();
1505				if (server != null) {
1506					return server;
1507				}
1508			}
1509		}
1510		return null;
1511	}
1512
1513	public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1514		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1515		if (account.getStatus() == Account.State.ONLINE) {
1516			try {
1517				String server = findConferenceServer(account);
1518				if (server == null) {
1519					if (callback != null) {
1520						callback.error(R.string.no_conference_server_found, null);
1521					}
1522					return;
1523				}
1524				String name = new BigInteger(75, getRNG()).toString(32);
1525				Jid jid = Jid.fromParts(name, server, null);
1526				final Conversation conversation = findOrCreateConversation(account, jid, true);
1527				joinMuc(conversation);
1528				Bundle options = new Bundle();
1529				options.putString("muc#roomconfig_persistentroom", "1");
1530				options.putString("muc#roomconfig_membersonly", "1");
1531				options.putString("muc#roomconfig_publicroom", "0");
1532				options.putString("muc#roomconfig_whois", "anyone");
1533				pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1534					@Override
1535					public void onPushSucceeded() {
1536						for (Jid invite : jids) {
1537							invite(conversation, invite);
1538						}
1539						if (callback != null) {
1540							callback.success(conversation);
1541						}
1542					}
1543
1544					@Override
1545					public void onPushFailed() {
1546						if (callback != null) {
1547							callback.error(R.string.conference_creation_failed, conversation);
1548						}
1549					}
1550				});
1551
1552			} catch (InvalidJidException e) {
1553				if (callback != null) {
1554					callback.error(R.string.conference_creation_failed, null);
1555				}
1556			}
1557		} else {
1558			if (callback != null) {
1559				callback.error(R.string.not_connected_try_again, null);
1560			}
1561		}
1562	}
1563
1564	public void fetchConferenceConfiguration(final Conversation conversation) {
1565		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1566		request.setTo(conversation.getJid().toBareJid());
1567		request.query("http://jabber.org/protocol/disco#info");
1568		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1569			@Override
1570			public void onIqPacketReceived(Account account, IqPacket packet) {
1571				if (packet.getType() != IqPacket.TYPE.ERROR) {
1572					ArrayList<String> features = new ArrayList<>();
1573					for (Element child : packet.query().getChildren()) {
1574						if (child != null && child.getName().equals("feature")) {
1575							String var = child.getAttribute("var");
1576							if (var != null) {
1577								features.add(var);
1578							}
1579						}
1580					}
1581					conversation.getMucOptions().updateFeatures(features);
1582					updateConversationUi();
1583				}
1584			}
1585		});
1586	}
1587
1588	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1589		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1590		request.setTo(conversation.getJid().toBareJid());
1591		request.query("http://jabber.org/protocol/muc#owner");
1592		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1593			@Override
1594			public void onIqPacketReceived(Account account, IqPacket packet) {
1595				if (packet.getType() != IqPacket.TYPE.ERROR) {
1596					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1597					for (Field field : data.getFields()) {
1598						if (options.containsKey(field.getName())) {
1599							field.setValue(options.getString(field.getName()));
1600						}
1601					}
1602					data.submit();
1603					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1604					set.setTo(conversation.getJid().toBareJid());
1605					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1606					sendIqPacket(account, set, new OnIqPacketReceived() {
1607						@Override
1608						public void onIqPacketReceived(Account account, IqPacket packet) {
1609							if (packet.getType() == IqPacket.TYPE.RESULT) {
1610								if (callback != null) {
1611									callback.onPushSucceeded();
1612								}
1613							} else {
1614								if (callback != null) {
1615									callback.onPushFailed();
1616								}
1617							}
1618						}
1619					});
1620				} else {
1621					if (callback != null) {
1622						callback.onPushFailed();
1623					}
1624				}
1625			}
1626		});
1627	}
1628
1629	public void pushSubjectToConference(final Conversation conference, final String subject) {
1630		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1631		this.sendMessagePacket(conference.getAccount(), packet);
1632		final MucOptions mucOptions = conference.getMucOptions();
1633		final MucOptions.User self = mucOptions.getSelf();
1634		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1635			Bundle options = new Bundle();
1636			options.putString("muc#roomconfig_persistentroom", "1");
1637			this.pushConferenceConfiguration(conference, options, null);
1638		}
1639	}
1640
1641	public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1642		final Jid jid = user.toBareJid();
1643		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
1644		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1645			@Override
1646			public void onIqPacketReceived(Account account, IqPacket packet) {
1647				if (packet.getType() == IqPacket.TYPE.RESULT) {
1648					callback.onAffiliationChangedSuccessful(jid);
1649				} else {
1650					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
1651				}
1652			}
1653		});
1654	}
1655
1656	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
1657		List<Jid> jids = new ArrayList<>();
1658		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
1659			if (user.getAffiliation() == before) {
1660				jids.add(user.getJid());
1661			}
1662		}
1663		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
1664		sendIqPacket(conference.getAccount(), request, null);
1665	}
1666
1667	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
1668		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
1669		Log.d(Config.LOGTAG, request.toString());
1670		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1671			@Override
1672			public void onIqPacketReceived(Account account, IqPacket packet) {
1673				Log.d(Config.LOGTAG, packet.toString());
1674				if (packet.getType() == IqPacket.TYPE.RESULT) {
1675					callback.onRoleChangedSuccessful(nick);
1676				} else {
1677					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
1678				}
1679			}
1680		});
1681	}
1682
1683	public void disconnect(Account account, boolean force) {
1684		if ((account.getStatus() == Account.State.ONLINE)
1685				|| (account.getStatus() == Account.State.DISABLED)) {
1686			if (!force) {
1687				List<Conversation> conversations = getConversations();
1688				for (Conversation conversation : conversations) {
1689					if (conversation.getAccount() == account) {
1690						if (conversation.getMode() == Conversation.MODE_MULTI) {
1691							leaveMuc(conversation);
1692						} else {
1693							if (conversation.endOtrIfNeeded()) {
1694								Log.d(Config.LOGTAG, account.getJid().toBareJid()
1695										+ ": ended otr session with "
1696										+ conversation.getJid());
1697							}
1698						}
1699					}
1700				}
1701			}
1702			account.getXmppConnection().disconnect(force);
1703		}
1704	}
1705
1706	@Override
1707	public IBinder onBind(Intent intent) {
1708		return mBinder;
1709	}
1710
1711	public void updateMessage(Message message) {
1712		databaseBackend.updateMessage(message);
1713		updateConversationUi();
1714	}
1715
1716	protected void syncDirtyContacts(Account account) {
1717		for (Contact contact : account.getRoster().getContacts()) {
1718			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1719				pushContactToServer(contact);
1720			}
1721			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1722				deleteContactOnServer(contact);
1723			}
1724		}
1725	}
1726
1727	public void createContact(Contact contact) {
1728		SharedPreferences sharedPref = getPreferences();
1729		boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1730		if (autoGrant) {
1731			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1732			contact.setOption(Contact.Options.ASKING);
1733		}
1734		pushContactToServer(contact);
1735	}
1736
1737	public void onOtrSessionEstablished(Conversation conversation) {
1738		final Account account = conversation.getAccount();
1739		final Session otrSession = conversation.getOtrSession();
1740		Log.d(Config.LOGTAG,
1741				account.getJid().toBareJid() + " otr session established with "
1742						+ conversation.getJid() + "/"
1743						+ otrSession.getSessionID().getUserID());
1744		conversation.findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
1745
1746			@Override
1747			public void onMessageFound(Message message) {
1748				SessionID id = otrSession.getSessionID();
1749				try {
1750					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
1751				} catch (InvalidJidException e) {
1752					return;
1753				}
1754				if (message.getType() == Message.TYPE_TEXT) {
1755					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message, true);
1756					if (outPacket != null) {
1757						message.setStatus(Message.STATUS_SEND);
1758						databaseBackend.updateMessage(message);
1759						sendMessagePacket(account, outPacket);
1760					}
1761				} else if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
1762					mJingleConnectionManager.createNewConnection(message);
1763				}
1764				updateConversationUi();
1765			}
1766		});
1767	}
1768
1769	public boolean renewSymmetricKey(Conversation conversation) {
1770		Account account = conversation.getAccount();
1771		byte[] symmetricKey = new byte[32];
1772		this.mRandom.nextBytes(symmetricKey);
1773		Session otrSession = conversation.getOtrSession();
1774		if (otrSession != null) {
1775			MessagePacket packet = new MessagePacket();
1776			packet.setType(MessagePacket.TYPE_CHAT);
1777			packet.setFrom(account.getJid());
1778			packet.addChild("private", "urn:xmpp:carbons:2");
1779			packet.addChild("no-copy", "urn:xmpp:hints");
1780			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
1781					+ otrSession.getSessionID().getUserID());
1782			try {
1783				packet.setBody(otrSession
1784						.transformSending(CryptoHelper.FILETRANSFER
1785								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
1786				sendMessagePacket(account, packet);
1787				conversation.setSymmetricKey(symmetricKey);
1788				return true;
1789			} catch (OtrException e) {
1790				return false;
1791			}
1792		}
1793		return false;
1794	}
1795
1796	public void pushContactToServer(final Contact contact) {
1797		contact.resetOption(Contact.Options.DIRTY_DELETE);
1798		contact.setOption(Contact.Options.DIRTY_PUSH);
1799		final Account account = contact.getAccount();
1800		if (account.getStatus() == Account.State.ONLINE) {
1801			final boolean ask = contact.getOption(Contact.Options.ASKING);
1802			final boolean sendUpdates = contact
1803					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
1804					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
1805			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1806			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
1807			account.getXmppConnection().sendIqPacket(iq, null);
1808			if (sendUpdates) {
1809				sendPresencePacket(account,
1810						mPresenceGenerator.sendPresenceUpdatesTo(contact));
1811			}
1812			if (ask) {
1813				sendPresencePacket(account,
1814						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
1815			}
1816		}
1817	}
1818
1819	public void publishAvatar(final Account account,
1820							  final Uri image,
1821							  final UiCallback<Avatar> callback) {
1822		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
1823		final int size = Config.AVATAR_SIZE;
1824		final Avatar avatar = getFileBackend()
1825				.getPepAvatar(image, size, format);
1826		if (avatar != null) {
1827			avatar.height = size;
1828			avatar.width = size;
1829			if (format.equals(Bitmap.CompressFormat.WEBP)) {
1830				avatar.type = "image/webp";
1831			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1832				avatar.type = "image/jpeg";
1833			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
1834				avatar.type = "image/png";
1835			}
1836			if (!getFileBackend().save(avatar)) {
1837				callback.error(R.string.error_saving_avatar, avatar);
1838				return;
1839			}
1840			final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
1841			this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1842
1843				@Override
1844				public void onIqPacketReceived(Account account, IqPacket result) {
1845					if (result.getType() == IqPacket.TYPE.RESULT) {
1846						final IqPacket packet = XmppConnectionService.this.mIqGenerator
1847								.publishAvatarMetadata(avatar);
1848						sendIqPacket(account, packet, new OnIqPacketReceived() {
1849
1850							@Override
1851							public void onIqPacketReceived(Account account,
1852														   IqPacket result) {
1853								if (result.getType() == IqPacket.TYPE.RESULT) {
1854									if (account.setAvatar(avatar.getFilename())) {
1855										databaseBackend.updateAccount(account);
1856									}
1857									callback.success(avatar);
1858								} else {
1859									callback.error(
1860											R.string.error_publish_avatar_server_reject,
1861											avatar);
1862								}
1863							}
1864						});
1865					} else {
1866						callback.error(
1867								R.string.error_publish_avatar_server_reject,
1868								avatar);
1869					}
1870				}
1871			});
1872		} else {
1873			callback.error(R.string.error_publish_avatar_converting, null);
1874		}
1875	}
1876
1877	public void fetchAvatar(Account account, Avatar avatar) {
1878		fetchAvatar(account, avatar, null);
1879	}
1880
1881	public void fetchAvatar(Account account, final Avatar avatar,
1882							final UiCallback<Avatar> callback) {
1883		IqPacket packet = this.mIqGenerator.retrieveAvatar(avatar);
1884		sendIqPacket(account, packet, new OnIqPacketReceived() {
1885
1886			@Override
1887			public void onIqPacketReceived(Account account, IqPacket result) {
1888				final String ERROR = account.getJid().toBareJid()
1889						+ ": fetching avatar for " + avatar.owner + " failed ";
1890				if (result.getType() == IqPacket.TYPE.RESULT) {
1891					avatar.image = mIqParser.avatarData(result);
1892					if (avatar.image != null) {
1893						if (getFileBackend().save(avatar)) {
1894							if (account.getJid().toBareJid().equals(avatar.owner)) {
1895								if (account.setAvatar(avatar.getFilename())) {
1896									databaseBackend.updateAccount(account);
1897								}
1898								getAvatarService().clear(account);
1899								updateConversationUi();
1900								updateAccountUi();
1901							} else {
1902								Contact contact = account.getRoster()
1903										.getContact(avatar.owner);
1904								contact.setAvatar(avatar.getFilename());
1905								getAvatarService().clear(contact);
1906								updateConversationUi();
1907								updateRosterUi();
1908							}
1909							if (callback != null) {
1910								callback.success(avatar);
1911							}
1912							Log.d(Config.LOGTAG, account.getJid().toBareJid()
1913									+ ": succesfully fetched avatar for "
1914									+ avatar.owner);
1915							return;
1916						}
1917					} else {
1918
1919						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
1920					}
1921				} else {
1922					Element error = result.findChild("error");
1923					if (error == null) {
1924						Log.d(Config.LOGTAG, ERROR + "(server error)");
1925					} else {
1926						Log.d(Config.LOGTAG, ERROR + error.toString());
1927					}
1928				}
1929				if (callback != null) {
1930					callback.error(0, null);
1931				}
1932
1933			}
1934		});
1935	}
1936
1937	public void checkForAvatar(Account account,
1938							   final UiCallback<Avatar> callback) {
1939		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
1940		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1941
1942			@Override
1943			public void onIqPacketReceived(Account account, IqPacket packet) {
1944				if (packet.getType() == IqPacket.TYPE.RESULT) {
1945					Element pubsub = packet.findChild("pubsub",
1946							"http://jabber.org/protocol/pubsub");
1947					if (pubsub != null) {
1948						Element items = pubsub.findChild("items");
1949						if (items != null) {
1950							Avatar avatar = Avatar.parseMetadata(items);
1951							if (avatar != null) {
1952								avatar.owner = account.getJid().toBareJid();
1953								if (fileBackend.isAvatarCached(avatar)) {
1954									if (account.setAvatar(avatar.getFilename())) {
1955										databaseBackend.updateAccount(account);
1956									}
1957									getAvatarService().clear(account);
1958									callback.success(avatar);
1959								} else {
1960									fetchAvatar(account, avatar, callback);
1961								}
1962								return;
1963							}
1964						}
1965					}
1966				}
1967				callback.error(0, null);
1968			}
1969		});
1970	}
1971
1972	public void deleteContactOnServer(Contact contact) {
1973		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
1974		contact.resetOption(Contact.Options.DIRTY_PUSH);
1975		contact.setOption(Contact.Options.DIRTY_DELETE);
1976		Account account = contact.getAccount();
1977		if (account.getStatus() == Account.State.ONLINE) {
1978			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1979			Element item = iq.query(Xmlns.ROSTER).addChild("item");
1980			item.setAttribute("jid", contact.getJid().toString());
1981			item.setAttribute("subscription", "remove");
1982			account.getXmppConnection().sendIqPacket(iq, null);
1983		}
1984	}
1985
1986	public void updateConversation(Conversation conversation) {
1987		this.databaseBackend.updateConversation(conversation);
1988	}
1989
1990	public void reconnectAccount(final Account account, final boolean force) {
1991		synchronized (account) {
1992			if (account.getXmppConnection() != null) {
1993				disconnect(account, force);
1994			}
1995			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
1996				if (account.getXmppConnection() == null) {
1997					account.setXmppConnection(createConnection(account));
1998				}
1999				Thread thread = new Thread(account.getXmppConnection());
2000				thread.start();
2001				scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
2002			} else {
2003				account.getRoster().clearPresences();
2004				account.setXmppConnection(null);
2005			}
2006		}
2007	}
2008
2009	public void reconnectAccountInBackground(final Account account) {
2010		new Thread(new Runnable() {
2011			@Override
2012			public void run() {
2013				reconnectAccount(account,false);
2014			}
2015		}).start();
2016	}
2017
2018	public void invite(Conversation conversation, Jid contact) {
2019		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2020		sendMessagePacket(conversation.getAccount(), packet);
2021	}
2022
2023	public void resetSendingToWaiting(Account account) {
2024		for (Conversation conversation : getConversations()) {
2025			if (conversation.getAccount() == account) {
2026				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2027
2028					@Override
2029					public void onMessageFound(Message message) {
2030						markMessage(message, Message.STATUS_WAITING);
2031					}
2032				});
2033			}
2034		}
2035	}
2036
2037	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2038		if (uuid == null) {
2039			return null;
2040		}
2041		for (Conversation conversation : getConversations()) {
2042			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2043				final Message message = conversation.findSentMessageWithUuid(uuid);
2044				if (message != null) {
2045					markMessage(message, status);
2046				}
2047				return message;
2048			}
2049		}
2050		return null;
2051	}
2052
2053	public boolean markMessage(Conversation conversation, String uuid,
2054							   int status) {
2055		if (uuid == null) {
2056			return false;
2057		} else {
2058			Message message = conversation.findSentMessageWithUuid(uuid);
2059			if (message != null) {
2060				markMessage(message, status);
2061				return true;
2062			} else {
2063				return false;
2064			}
2065		}
2066	}
2067
2068	public void markMessage(Message message, int status) {
2069		if (status == Message.STATUS_SEND_FAILED
2070				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2071				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2072			return;
2073		}
2074		message.setStatus(status);
2075		databaseBackend.updateMessage(message);
2076		updateConversationUi();
2077	}
2078
2079	public SharedPreferences getPreferences() {
2080		return PreferenceManager
2081				.getDefaultSharedPreferences(getApplicationContext());
2082	}
2083
2084	public boolean forceEncryption() {
2085		return getPreferences().getBoolean("force_encryption", false);
2086	}
2087
2088	public boolean confirmMessages() {
2089		return getPreferences().getBoolean("confirm_messages", true);
2090	}
2091
2092	public boolean sendChatStates() {
2093		return getPreferences().getBoolean("chat_states", false);
2094	}
2095
2096	public boolean saveEncryptedMessages() {
2097		return !getPreferences().getBoolean("dont_save_encrypted", false);
2098	}
2099
2100	public boolean indicateReceived() {
2101		return getPreferences().getBoolean("indicate_received", false);
2102	}
2103
2104	public int unreadCount() {
2105		int count = 0;
2106		for(Conversation conversation : getConversations()) {
2107			count += conversation.unreadCount();
2108		}
2109		return count;
2110	}
2111
2112	public void updateConversationUi() {
2113		if (mOnConversationUpdate != null) {
2114			mOnConversationUpdate.onConversationUpdate();
2115		}
2116	}
2117
2118	public void updateAccountUi() {
2119		if (mOnAccountUpdate != null) {
2120			mOnAccountUpdate.onAccountUpdate();
2121		}
2122	}
2123
2124	public void updateRosterUi() {
2125		if (mOnRosterUpdate != null) {
2126			mOnRosterUpdate.onRosterUpdate();
2127		}
2128	}
2129
2130	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2131		if (mOnUpdateBlocklist != null) {
2132			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2133		}
2134	}
2135
2136	public void updateMucRosterUi() {
2137		if (mOnMucRosterUpdate != null) {
2138			mOnMucRosterUpdate.onMucRosterUpdate();
2139		}
2140	}
2141
2142	public Account findAccountByJid(final Jid accountJid) {
2143		for (Account account : this.accounts) {
2144			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2145				return account;
2146			}
2147		}
2148		return null;
2149	}
2150
2151	public Conversation findConversationByUuid(String uuid) {
2152		for (Conversation conversation : getConversations()) {
2153			if (conversation.getUuid().equals(uuid)) {
2154				return conversation;
2155			}
2156		}
2157		return null;
2158	}
2159
2160	public void markRead(final Conversation conversation) {
2161		mNotificationService.clear(conversation);
2162		conversation.markRead();
2163	}
2164
2165	public void sendReadMarker(final Conversation conversation) {
2166		final Message markable = conversation.getLatestMarkableMessage();
2167		this.markRead(conversation);
2168		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2169			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2170			Account account = conversation.getAccount();
2171			final Jid to = markable.getCounterpart();
2172			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2173			this.sendMessagePacket(conversation.getAccount(), packet);
2174		}
2175		updateConversationUi();
2176	}
2177
2178	public SecureRandom getRNG() {
2179		return this.mRandom;
2180	}
2181
2182	public MemorizingTrustManager getMemorizingTrustManager() {
2183		return this.mMemorizingTrustManager;
2184	}
2185
2186	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2187		this.mMemorizingTrustManager = trustManager;
2188	}
2189
2190	public void updateMemorizingTrustmanager() {
2191		final MemorizingTrustManager tm;
2192		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2193		if (dontTrustSystemCAs) {
2194			 tm = new MemorizingTrustManager(getApplicationContext(), null);
2195		} else {
2196			tm = new MemorizingTrustManager(getApplicationContext());
2197		}
2198		setMemorizingTrustManager(tm);
2199	}
2200
2201	public PowerManager getPowerManager() {
2202		return this.pm;
2203	}
2204
2205	public LruCache<String, Bitmap> getBitmapCache() {
2206		return this.mBitmapCache;
2207	}
2208
2209	public void syncRosterToDisk(final Account account) {
2210		new Thread(new Runnable() {
2211
2212			@Override
2213			public void run() {
2214				databaseBackend.writeRoster(account.getRoster());
2215			}
2216		}).start();
2217
2218	}
2219
2220	public List<String> getKnownHosts() {
2221		final List<String> hosts = new ArrayList<>();
2222		for (final Account account : getAccounts()) {
2223			if (!hosts.contains(account.getServer().toString())) {
2224				hosts.add(account.getServer().toString());
2225			}
2226			for (final Contact contact : account.getRoster().getContacts()) {
2227				if (contact.showInRoster()) {
2228					final String server = contact.getServer().toString();
2229					if (server != null && !hosts.contains(server)) {
2230						hosts.add(server);
2231					}
2232				}
2233			}
2234		}
2235		return hosts;
2236	}
2237
2238	public List<String> getKnownConferenceHosts() {
2239		final ArrayList<String> mucServers = new ArrayList<>();
2240		for (final Account account : accounts) {
2241			if (account.getXmppConnection() != null) {
2242				final String server = account.getXmppConnection().getMucServer();
2243				if (server != null && !mucServers.contains(server)) {
2244					mucServers.add(server);
2245				}
2246			}
2247		}
2248		return mucServers;
2249	}
2250
2251	public void sendMessagePacket(Account account, MessagePacket packet) {
2252		XmppConnection connection = account.getXmppConnection();
2253		if (connection != null) {
2254			connection.sendMessagePacket(packet);
2255		}
2256	}
2257
2258	public void sendPresencePacket(Account account, PresencePacket packet) {
2259		XmppConnection connection = account.getXmppConnection();
2260		if (connection != null) {
2261			connection.sendPresencePacket(packet);
2262		}
2263	}
2264
2265	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2266		final XmppConnection connection = account.getXmppConnection();
2267		if (connection != null) {
2268			connection.sendIqPacket(packet, callback);
2269		}
2270	}
2271
2272	public void sendPresence(final Account account) {
2273		sendPresencePacket(account, mPresenceGenerator.sendPresence(account));
2274	}
2275
2276	public MessageGenerator getMessageGenerator() {
2277		return this.mMessageGenerator;
2278	}
2279
2280	public PresenceGenerator getPresenceGenerator() {
2281		return this.mPresenceGenerator;
2282	}
2283
2284	public IqGenerator getIqGenerator() {
2285		return this.mIqGenerator;
2286	}
2287
2288	public IqParser getIqParser() {
2289		return this.mIqParser;
2290	}
2291
2292	public JingleConnectionManager getJingleConnectionManager() {
2293		return this.mJingleConnectionManager;
2294	}
2295
2296	public MessageArchiveService getMessageArchiveService() {
2297		return this.mMessageArchiveService;
2298	}
2299
2300	public List<Contact> findContacts(Jid jid) {
2301		ArrayList<Contact> contacts = new ArrayList<>();
2302		for (Account account : getAccounts()) {
2303			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2304				Contact contact = account.getRoster().getContactFromRoster(jid);
2305				if (contact != null) {
2306					contacts.add(contact);
2307				}
2308			}
2309		}
2310		return contacts;
2311	}
2312
2313	public NotificationService getNotificationService() {
2314		return this.mNotificationService;
2315	}
2316
2317	public HttpConnectionManager getHttpConnectionManager() {
2318		return this.mHttpConnectionManager;
2319	}
2320
2321	public void resendFailedMessages(final Message message) {
2322		final Collection<Message> messages = new ArrayList<>();
2323		Message current = message;
2324		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2325			messages.add(current);
2326			if (current.mergeable(current.next())) {
2327				current = current.next();
2328			} else {
2329				break;
2330			}
2331		}
2332		for (final Message msg : messages) {
2333			markMessage(msg, Message.STATUS_WAITING);
2334			this.resendMessage(msg);
2335		}
2336	}
2337
2338	public void clearConversationHistory(final Conversation conversation) {
2339		conversation.clearMessages();
2340		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2341		new Thread(new Runnable() {
2342			@Override
2343			public void run() {
2344				databaseBackend.deleteMessagesInConversation(conversation);
2345			}
2346		}).start();
2347	}
2348
2349	public void sendBlockRequest(final Blockable blockable) {
2350		if (blockable != null && blockable.getBlockedJid() != null) {
2351			final Jid jid = blockable.getBlockedJid();
2352			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2353
2354				@Override
2355				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2356					if (packet.getType() == IqPacket.TYPE.RESULT) {
2357						account.getBlocklist().add(jid);
2358						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2359					}
2360				}
2361			});
2362		}
2363	}
2364
2365	public void sendUnblockRequest(final Blockable blockable) {
2366		if (blockable != null && blockable.getJid() != null) {
2367			final Jid jid = blockable.getBlockedJid();
2368			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2369				@Override
2370				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2371					if (packet.getType() == IqPacket.TYPE.RESULT) {
2372						account.getBlocklist().remove(jid);
2373						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2374					}
2375				}
2376			});
2377		}
2378	}
2379
2380	public interface OnMoreMessagesLoaded {
2381		public void onMoreMessagesLoaded(int count, Conversation conversation);
2382
2383		public void informUser(int r);
2384	}
2385
2386	public interface OnAccountPasswordChanged {
2387		public void onPasswordChangeSucceeded();
2388
2389		public void onPasswordChangeFailed();
2390	}
2391
2392	public interface OnAffiliationChanged {
2393		public void onAffiliationChangedSuccessful(Jid jid);
2394
2395		public void onAffiliationChangeFailed(Jid jid, int resId);
2396	}
2397
2398	public interface OnRoleChanged {
2399		public void onRoleChangedSuccessful(String nick);
2400
2401		public void onRoleChangeFailed(String nick, int resid);
2402	}
2403
2404	public interface OnConversationUpdate {
2405		public void onConversationUpdate();
2406	}
2407
2408	public interface OnAccountUpdate {
2409		public void onAccountUpdate();
2410	}
2411
2412	public interface OnRosterUpdate {
2413		public void onRosterUpdate();
2414	}
2415
2416	public interface OnMucRosterUpdate {
2417		public void onMucRosterUpdate();
2418	}
2419
2420	public interface OnConferenceOptionsPushed {
2421		public void onPushSucceeded();
2422
2423		public void onPushFailed();
2424	}
2425
2426	public class XmppConnectionBinder extends Binder {
2427		public XmppConnectionService getService() {
2428			return XmppConnectionService.this;
2429		}
2430	}
2431}