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		getNotificationService().clear(conversation);
1131		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1132		conversation.setNextEncryption(-1);
1133		synchronized (this.conversations) {
1134			if (conversation.getMode() == Conversation.MODE_MULTI) {
1135				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1136					Bookmark bookmark = conversation.getBookmark();
1137					if (bookmark != null && bookmark.autojoin()) {
1138						bookmark.setAutojoin(false);
1139						pushBookmarks(bookmark.getAccount());
1140					}
1141				}
1142				leaveMuc(conversation);
1143			} else {
1144				conversation.endOtrIfNeeded();
1145			}
1146			this.databaseBackend.updateConversation(conversation);
1147			this.conversations.remove(conversation);
1148			updateConversationUi();
1149		}
1150	}
1151
1152	public void createAccount(final Account account) {
1153		account.initOtrEngine(this);
1154		databaseBackend.createAccount(account);
1155		this.accounts.add(account);
1156		this.reconnectAccountInBackground(account);
1157		updateAccountUi();
1158	}
1159
1160	public void updateAccount(final Account account) {
1161		this.statusListener.onStatusChanged(account);
1162		databaseBackend.updateAccount(account);
1163		reconnectAccount(account, false);
1164		updateAccountUi();
1165		getNotificationService().updateErrorNotification();
1166	}
1167
1168	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1169		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1170		sendIqPacket(account, iq, new OnIqPacketReceived() {
1171			@Override
1172			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1173				if (packet.getType() == IqPacket.TYPE.RESULT) {
1174					account.setPassword(newPassword);
1175					databaseBackend.updateAccount(account);
1176					callback.onPasswordChangeSucceeded();
1177				} else {
1178					callback.onPasswordChangeFailed();
1179				}
1180			}
1181		});
1182	}
1183
1184	public void deleteAccount(final Account account) {
1185		synchronized (this.conversations) {
1186			for (final Conversation conversation : conversations) {
1187				if (conversation.getAccount() == account) {
1188					if (conversation.getMode() == Conversation.MODE_MULTI) {
1189						leaveMuc(conversation);
1190					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1191						conversation.endOtrIfNeeded();
1192					}
1193					conversations.remove(conversation);
1194				}
1195			}
1196			if (account.getXmppConnection() != null) {
1197				this.disconnect(account, true);
1198			}
1199			databaseBackend.deleteAccount(account);
1200			this.accounts.remove(account);
1201			updateAccountUi();
1202			getNotificationService().updateErrorNotification();
1203		}
1204	}
1205
1206	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1207		synchronized (this) {
1208			if (checkListeners()) {
1209				switchToForeground();
1210			}
1211			this.mOnConversationUpdate = listener;
1212			this.mNotificationService.setIsInForeground(true);
1213			if (this.convChangedListenerCount < 2) {
1214				this.convChangedListenerCount++;
1215			}
1216		}
1217	}
1218
1219	public void removeOnConversationListChangedListener() {
1220		synchronized (this) {
1221			this.convChangedListenerCount--;
1222			if (this.convChangedListenerCount <= 0) {
1223				this.convChangedListenerCount = 0;
1224				this.mOnConversationUpdate = null;
1225				this.mNotificationService.setIsInForeground(false);
1226				if (checkListeners()) {
1227					switchToBackground();
1228				}
1229			}
1230		}
1231	}
1232
1233	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1234		synchronized (this) {
1235			if (checkListeners()) {
1236				switchToForeground();
1237			}
1238			this.mOnAccountUpdate = listener;
1239			if (this.accountChangedListenerCount < 2) {
1240				this.accountChangedListenerCount++;
1241			}
1242		}
1243	}
1244
1245	public void removeOnAccountListChangedListener() {
1246		synchronized (this) {
1247			this.accountChangedListenerCount--;
1248			if (this.accountChangedListenerCount <= 0) {
1249				this.mOnAccountUpdate = null;
1250				this.accountChangedListenerCount = 0;
1251				if (checkListeners()) {
1252					switchToBackground();
1253				}
1254			}
1255		}
1256	}
1257
1258	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1259		synchronized (this) {
1260			if (checkListeners()) {
1261				switchToForeground();
1262			}
1263			this.mOnRosterUpdate = listener;
1264			if (this.rosterChangedListenerCount < 2) {
1265				this.rosterChangedListenerCount++;
1266			}
1267		}
1268	}
1269
1270	public void removeOnRosterUpdateListener() {
1271		synchronized (this) {
1272			this.rosterChangedListenerCount--;
1273			if (this.rosterChangedListenerCount <= 0) {
1274				this.rosterChangedListenerCount = 0;
1275				this.mOnRosterUpdate = null;
1276				if (checkListeners()) {
1277					switchToBackground();
1278				}
1279			}
1280		}
1281	}
1282
1283	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1284		synchronized (this) {
1285			if (checkListeners()) {
1286				switchToForeground();
1287			}
1288			this.mOnUpdateBlocklist = listener;
1289			if (this.updateBlocklistListenerCount < 2) {
1290				this.updateBlocklistListenerCount++;
1291			}
1292		}
1293	}
1294
1295	public void removeOnUpdateBlocklistListener() {
1296		synchronized (this) {
1297			this.updateBlocklistListenerCount--;
1298			if (this.updateBlocklistListenerCount <= 0) {
1299				this.updateBlocklistListenerCount = 0;
1300				this.mOnUpdateBlocklist = null;
1301				if (checkListeners()) {
1302					switchToBackground();
1303				}
1304			}
1305		}
1306	}
1307
1308	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1309		synchronized (this) {
1310			if (checkListeners()) {
1311				switchToForeground();
1312			}
1313			this.mOnMucRosterUpdate = listener;
1314			if (this.mucRosterChangedListenerCount < 2) {
1315				this.mucRosterChangedListenerCount++;
1316			}
1317		}
1318	}
1319
1320	public void removeOnMucRosterUpdateListener() {
1321		synchronized (this) {
1322			this.mucRosterChangedListenerCount--;
1323			if (this.mucRosterChangedListenerCount <= 0) {
1324				this.mucRosterChangedListenerCount = 0;
1325				this.mOnMucRosterUpdate = null;
1326				if (checkListeners()) {
1327					switchToBackground();
1328				}
1329			}
1330		}
1331	}
1332
1333	private boolean checkListeners() {
1334		return (this.mOnAccountUpdate == null
1335				&& this.mOnConversationUpdate == null
1336				&& this.mOnRosterUpdate == null
1337				&& this.mOnUpdateBlocklist == null);
1338	}
1339
1340	private void switchToForeground() {
1341		for (Account account : getAccounts()) {
1342			if (account.getStatus() == Account.State.ONLINE) {
1343				XmppConnection connection = account.getXmppConnection();
1344				if (connection != null && connection.getFeatures().csi()) {
1345					connection.sendActive();
1346				}
1347			}
1348		}
1349		Log.d(Config.LOGTAG, "app switched into foreground");
1350	}
1351
1352	private void switchToBackground() {
1353		for (Account account : getAccounts()) {
1354			if (account.getStatus() == Account.State.ONLINE) {
1355				XmppConnection connection = account.getXmppConnection();
1356				if (connection != null && connection.getFeatures().csi()) {
1357					connection.sendInactive();
1358				}
1359			}
1360		}
1361		for(Conversation conversation : getConversations()) {
1362			conversation.setIncomingChatState(ChatState.ACTIVE);
1363		}
1364		this.mNotificationService.setIsInForeground(false);
1365		Log.d(Config.LOGTAG, "app switched into background");
1366	}
1367
1368	private void connectMultiModeConversations(Account account) {
1369		List<Conversation> conversations = getConversations();
1370		for (Conversation conversation : conversations) {
1371			if ((conversation.getMode() == Conversation.MODE_MULTI)
1372					&& (conversation.getAccount() == account)) {
1373				conversation.resetMucOptions();
1374				joinMuc(conversation);
1375			}
1376		}
1377	}
1378
1379	public void joinMuc(Conversation conversation) {
1380		Account account = conversation.getAccount();
1381		account.pendingConferenceJoins.remove(conversation);
1382		account.pendingConferenceLeaves.remove(conversation);
1383		if (account.getStatus() == Account.State.ONLINE) {
1384			final String nick = conversation.getMucOptions().getProposedNick();
1385			final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1386			if (joinJid == null) {
1387				return; //safety net
1388			}
1389			Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1390			PresencePacket packet = new PresencePacket();
1391			packet.setFrom(conversation.getAccount().getJid());
1392			packet.setTo(joinJid);
1393			Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1394			if (conversation.getMucOptions().getPassword() != null) {
1395				x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1396			}
1397			x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1398			String sig = account.getPgpSignature();
1399			if (sig != null) {
1400				packet.addChild("status").setContent("online");
1401				packet.addChild("x", "jabber:x:signed").setContent(sig);
1402			}
1403			sendPresencePacket(account, packet);
1404			fetchConferenceConfiguration(conversation);
1405			if (!joinJid.equals(conversation.getJid())) {
1406				conversation.setContactJid(joinJid);
1407				databaseBackend.updateConversation(conversation);
1408			}
1409			conversation.setHasMessagesLeftOnServer(false);
1410		} else {
1411			account.pendingConferenceJoins.add(conversation);
1412		}
1413	}
1414
1415	public void providePasswordForMuc(Conversation conversation, String password) {
1416		if (conversation.getMode() == Conversation.MODE_MULTI) {
1417			conversation.getMucOptions().setPassword(password);
1418			if (conversation.getBookmark() != null) {
1419				conversation.getBookmark().setAutojoin(true);
1420				pushBookmarks(conversation.getAccount());
1421			}
1422			databaseBackend.updateConversation(conversation);
1423			joinMuc(conversation);
1424		}
1425	}
1426
1427	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1428		final MucOptions options = conversation.getMucOptions();
1429		final Jid joinJid = options.createJoinJid(nick);
1430		if (options.online()) {
1431			Account account = conversation.getAccount();
1432			options.setOnRenameListener(new OnRenameListener() {
1433
1434				@Override
1435				public void onSuccess() {
1436					conversation.setContactJid(joinJid);
1437					databaseBackend.updateConversation(conversation);
1438					Bookmark bookmark = conversation.getBookmark();
1439					if (bookmark != null) {
1440						bookmark.setNick(nick);
1441						pushBookmarks(bookmark.getAccount());
1442					}
1443					callback.success(conversation);
1444				}
1445
1446				@Override
1447				public void onFailure() {
1448					callback.error(R.string.nick_in_use, conversation);
1449				}
1450			});
1451
1452			PresencePacket packet = new PresencePacket();
1453			packet.setTo(joinJid);
1454			packet.setFrom(conversation.getAccount().getJid());
1455
1456			String sig = account.getPgpSignature();
1457			if (sig != null) {
1458				packet.addChild("status").setContent("online");
1459				packet.addChild("x", "jabber:x:signed").setContent(sig);
1460			}
1461			sendPresencePacket(account, packet);
1462		} else {
1463			conversation.setContactJid(joinJid);
1464			databaseBackend.updateConversation(conversation);
1465			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1466				Bookmark bookmark = conversation.getBookmark();
1467				if (bookmark != null) {
1468					bookmark.setNick(nick);
1469					pushBookmarks(bookmark.getAccount());
1470				}
1471				joinMuc(conversation);
1472			}
1473		}
1474	}
1475
1476	public void leaveMuc(Conversation conversation) {
1477		Account account = conversation.getAccount();
1478		account.pendingConferenceJoins.remove(conversation);
1479		account.pendingConferenceLeaves.remove(conversation);
1480		if (account.getStatus() == Account.State.ONLINE) {
1481			PresencePacket packet = new PresencePacket();
1482			packet.setTo(conversation.getJid());
1483			packet.setFrom(conversation.getAccount().getJid());
1484			packet.setAttribute("type", "unavailable");
1485			sendPresencePacket(conversation.getAccount(), packet);
1486			conversation.getMucOptions().setOffline();
1487			conversation.deregisterWithBookmark();
1488			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1489					+ ": leaving muc " + conversation.getJid());
1490		} else {
1491			account.pendingConferenceLeaves.add(conversation);
1492		}
1493	}
1494
1495	private String findConferenceServer(final Account account) {
1496		String server;
1497		if (account.getXmppConnection() != null) {
1498			server = account.getXmppConnection().getMucServer();
1499			if (server != null) {
1500				return server;
1501			}
1502		}
1503		for (Account other : getAccounts()) {
1504			if (other != account && other.getXmppConnection() != null) {
1505				server = other.getXmppConnection().getMucServer();
1506				if (server != null) {
1507					return server;
1508				}
1509			}
1510		}
1511		return null;
1512	}
1513
1514	public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1515		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1516		if (account.getStatus() == Account.State.ONLINE) {
1517			try {
1518				String server = findConferenceServer(account);
1519				if (server == null) {
1520					if (callback != null) {
1521						callback.error(R.string.no_conference_server_found, null);
1522					}
1523					return;
1524				}
1525				String name = new BigInteger(75, getRNG()).toString(32);
1526				Jid jid = Jid.fromParts(name, server, null);
1527				final Conversation conversation = findOrCreateConversation(account, jid, true);
1528				joinMuc(conversation);
1529				Bundle options = new Bundle();
1530				options.putString("muc#roomconfig_persistentroom", "1");
1531				options.putString("muc#roomconfig_membersonly", "1");
1532				options.putString("muc#roomconfig_publicroom", "0");
1533				options.putString("muc#roomconfig_whois", "anyone");
1534				pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1535					@Override
1536					public void onPushSucceeded() {
1537						for (Jid invite : jids) {
1538							invite(conversation, invite);
1539						}
1540						if (callback != null) {
1541							callback.success(conversation);
1542						}
1543					}
1544
1545					@Override
1546					public void onPushFailed() {
1547						if (callback != null) {
1548							callback.error(R.string.conference_creation_failed, conversation);
1549						}
1550					}
1551				});
1552
1553			} catch (InvalidJidException e) {
1554				if (callback != null) {
1555					callback.error(R.string.conference_creation_failed, null);
1556				}
1557			}
1558		} else {
1559			if (callback != null) {
1560				callback.error(R.string.not_connected_try_again, null);
1561			}
1562		}
1563	}
1564
1565	public void fetchConferenceConfiguration(final Conversation conversation) {
1566		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1567		request.setTo(conversation.getJid().toBareJid());
1568		request.query("http://jabber.org/protocol/disco#info");
1569		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1570			@Override
1571			public void onIqPacketReceived(Account account, IqPacket packet) {
1572				if (packet.getType() != IqPacket.TYPE.ERROR) {
1573					ArrayList<String> features = new ArrayList<>();
1574					for (Element child : packet.query().getChildren()) {
1575						if (child != null && child.getName().equals("feature")) {
1576							String var = child.getAttribute("var");
1577							if (var != null) {
1578								features.add(var);
1579							}
1580						}
1581					}
1582					conversation.getMucOptions().updateFeatures(features);
1583					updateConversationUi();
1584				}
1585			}
1586		});
1587	}
1588
1589	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1590		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1591		request.setTo(conversation.getJid().toBareJid());
1592		request.query("http://jabber.org/protocol/muc#owner");
1593		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1594			@Override
1595			public void onIqPacketReceived(Account account, IqPacket packet) {
1596				if (packet.getType() != IqPacket.TYPE.ERROR) {
1597					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1598					for (Field field : data.getFields()) {
1599						if (options.containsKey(field.getName())) {
1600							field.setValue(options.getString(field.getName()));
1601						}
1602					}
1603					data.submit();
1604					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1605					set.setTo(conversation.getJid().toBareJid());
1606					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1607					sendIqPacket(account, set, new OnIqPacketReceived() {
1608						@Override
1609						public void onIqPacketReceived(Account account, IqPacket packet) {
1610							if (packet.getType() == IqPacket.TYPE.RESULT) {
1611								if (callback != null) {
1612									callback.onPushSucceeded();
1613								}
1614							} else {
1615								if (callback != null) {
1616									callback.onPushFailed();
1617								}
1618							}
1619						}
1620					});
1621				} else {
1622					if (callback != null) {
1623						callback.onPushFailed();
1624					}
1625				}
1626			}
1627		});
1628	}
1629
1630	public void pushSubjectToConference(final Conversation conference, final String subject) {
1631		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1632		this.sendMessagePacket(conference.getAccount(), packet);
1633		final MucOptions mucOptions = conference.getMucOptions();
1634		final MucOptions.User self = mucOptions.getSelf();
1635		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1636			Bundle options = new Bundle();
1637			options.putString("muc#roomconfig_persistentroom", "1");
1638			this.pushConferenceConfiguration(conference, options, null);
1639		}
1640	}
1641
1642	public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1643		final Jid jid = user.toBareJid();
1644		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
1645		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1646			@Override
1647			public void onIqPacketReceived(Account account, IqPacket packet) {
1648				if (packet.getType() == IqPacket.TYPE.RESULT) {
1649					callback.onAffiliationChangedSuccessful(jid);
1650				} else {
1651					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
1652				}
1653			}
1654		});
1655	}
1656
1657	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
1658		List<Jid> jids = new ArrayList<>();
1659		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
1660			if (user.getAffiliation() == before) {
1661				jids.add(user.getJid());
1662			}
1663		}
1664		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
1665		sendIqPacket(conference.getAccount(), request, null);
1666	}
1667
1668	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
1669		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
1670		Log.d(Config.LOGTAG, request.toString());
1671		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1672			@Override
1673			public void onIqPacketReceived(Account account, IqPacket packet) {
1674				Log.d(Config.LOGTAG, packet.toString());
1675				if (packet.getType() == IqPacket.TYPE.RESULT) {
1676					callback.onRoleChangedSuccessful(nick);
1677				} else {
1678					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
1679				}
1680			}
1681		});
1682	}
1683
1684	public void disconnect(Account account, boolean force) {
1685		if ((account.getStatus() == Account.State.ONLINE)
1686				|| (account.getStatus() == Account.State.DISABLED)) {
1687			if (!force) {
1688				List<Conversation> conversations = getConversations();
1689				for (Conversation conversation : conversations) {
1690					if (conversation.getAccount() == account) {
1691						if (conversation.getMode() == Conversation.MODE_MULTI) {
1692							leaveMuc(conversation);
1693						} else {
1694							if (conversation.endOtrIfNeeded()) {
1695								Log.d(Config.LOGTAG, account.getJid().toBareJid()
1696										+ ": ended otr session with "
1697										+ conversation.getJid());
1698							}
1699						}
1700					}
1701				}
1702				sendOfflinePresence(account);
1703			}
1704			account.getXmppConnection().disconnect(force);
1705		}
1706	}
1707
1708	@Override
1709	public IBinder onBind(Intent intent) {
1710		return mBinder;
1711	}
1712
1713	public void updateMessage(Message message) {
1714		databaseBackend.updateMessage(message);
1715		updateConversationUi();
1716	}
1717
1718	protected void syncDirtyContacts(Account account) {
1719		for (Contact contact : account.getRoster().getContacts()) {
1720			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1721				pushContactToServer(contact);
1722			}
1723			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1724				deleteContactOnServer(contact);
1725			}
1726		}
1727	}
1728
1729	public void createContact(Contact contact) {
1730		SharedPreferences sharedPref = getPreferences();
1731		boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1732		if (autoGrant) {
1733			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1734			contact.setOption(Contact.Options.ASKING);
1735		}
1736		pushContactToServer(contact);
1737	}
1738
1739	public void onOtrSessionEstablished(Conversation conversation) {
1740		final Account account = conversation.getAccount();
1741		final Session otrSession = conversation.getOtrSession();
1742		Log.d(Config.LOGTAG,
1743				account.getJid().toBareJid() + " otr session established with "
1744						+ conversation.getJid() + "/"
1745						+ otrSession.getSessionID().getUserID());
1746		conversation.findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
1747
1748			@Override
1749			public void onMessageFound(Message message) {
1750				SessionID id = otrSession.getSessionID();
1751				try {
1752					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
1753				} catch (InvalidJidException e) {
1754					return;
1755				}
1756				if (message.getType() == Message.TYPE_TEXT) {
1757					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message, true);
1758					if (outPacket != null) {
1759						message.setStatus(Message.STATUS_SEND);
1760						databaseBackend.updateMessage(message);
1761						sendMessagePacket(account, outPacket);
1762					}
1763				} else if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
1764					mJingleConnectionManager.createNewConnection(message);
1765				}
1766				updateConversationUi();
1767			}
1768		});
1769	}
1770
1771	public boolean renewSymmetricKey(Conversation conversation) {
1772		Account account = conversation.getAccount();
1773		byte[] symmetricKey = new byte[32];
1774		this.mRandom.nextBytes(symmetricKey);
1775		Session otrSession = conversation.getOtrSession();
1776		if (otrSession != null) {
1777			MessagePacket packet = new MessagePacket();
1778			packet.setType(MessagePacket.TYPE_CHAT);
1779			packet.setFrom(account.getJid());
1780			packet.addChild("private", "urn:xmpp:carbons:2");
1781			packet.addChild("no-copy", "urn:xmpp:hints");
1782			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
1783					+ otrSession.getSessionID().getUserID());
1784			try {
1785				packet.setBody(otrSession
1786						.transformSending(CryptoHelper.FILETRANSFER
1787								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
1788				sendMessagePacket(account, packet);
1789				conversation.setSymmetricKey(symmetricKey);
1790				return true;
1791			} catch (OtrException e) {
1792				return false;
1793			}
1794		}
1795		return false;
1796	}
1797
1798	public void pushContactToServer(final Contact contact) {
1799		contact.resetOption(Contact.Options.DIRTY_DELETE);
1800		contact.setOption(Contact.Options.DIRTY_PUSH);
1801		final Account account = contact.getAccount();
1802		if (account.getStatus() == Account.State.ONLINE) {
1803			final boolean ask = contact.getOption(Contact.Options.ASKING);
1804			final boolean sendUpdates = contact
1805					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
1806					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
1807			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1808			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
1809			account.getXmppConnection().sendIqPacket(iq, null);
1810			if (sendUpdates) {
1811				sendPresencePacket(account,
1812						mPresenceGenerator.sendPresenceUpdatesTo(contact));
1813			}
1814			if (ask) {
1815				sendPresencePacket(account,
1816						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
1817			}
1818		}
1819	}
1820
1821	public void publishAvatar(final Account account,
1822							  final Uri image,
1823							  final UiCallback<Avatar> callback) {
1824		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
1825		final int size = Config.AVATAR_SIZE;
1826		final Avatar avatar = getFileBackend()
1827				.getPepAvatar(image, size, format);
1828		if (avatar != null) {
1829			avatar.height = size;
1830			avatar.width = size;
1831			if (format.equals(Bitmap.CompressFormat.WEBP)) {
1832				avatar.type = "image/webp";
1833			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1834				avatar.type = "image/jpeg";
1835			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
1836				avatar.type = "image/png";
1837			}
1838			if (!getFileBackend().save(avatar)) {
1839				callback.error(R.string.error_saving_avatar, avatar);
1840				return;
1841			}
1842			final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
1843			this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1844
1845				@Override
1846				public void onIqPacketReceived(Account account, IqPacket result) {
1847					if (result.getType() == IqPacket.TYPE.RESULT) {
1848						final IqPacket packet = XmppConnectionService.this.mIqGenerator
1849								.publishAvatarMetadata(avatar);
1850						sendIqPacket(account, packet, new OnIqPacketReceived() {
1851
1852							@Override
1853							public void onIqPacketReceived(Account account,
1854														   IqPacket result) {
1855								if (result.getType() == IqPacket.TYPE.RESULT) {
1856									if (account.setAvatar(avatar.getFilename())) {
1857										databaseBackend.updateAccount(account);
1858									}
1859									callback.success(avatar);
1860								} else {
1861									callback.error(
1862											R.string.error_publish_avatar_server_reject,
1863											avatar);
1864								}
1865							}
1866						});
1867					} else {
1868						callback.error(
1869								R.string.error_publish_avatar_server_reject,
1870								avatar);
1871					}
1872				}
1873			});
1874		} else {
1875			callback.error(R.string.error_publish_avatar_converting, null);
1876		}
1877	}
1878
1879	public void fetchAvatar(Account account, Avatar avatar) {
1880		fetchAvatar(account, avatar, null);
1881	}
1882
1883	public void fetchAvatar(Account account, final Avatar avatar,
1884							final UiCallback<Avatar> callback) {
1885		IqPacket packet = this.mIqGenerator.retrieveAvatar(avatar);
1886		sendIqPacket(account, packet, new OnIqPacketReceived() {
1887
1888			@Override
1889			public void onIqPacketReceived(Account account, IqPacket result) {
1890				final String ERROR = account.getJid().toBareJid()
1891						+ ": fetching avatar for " + avatar.owner + " failed ";
1892				if (result.getType() == IqPacket.TYPE.RESULT) {
1893					avatar.image = mIqParser.avatarData(result);
1894					if (avatar.image != null) {
1895						if (getFileBackend().save(avatar)) {
1896							if (account.getJid().toBareJid().equals(avatar.owner)) {
1897								if (account.setAvatar(avatar.getFilename())) {
1898									databaseBackend.updateAccount(account);
1899								}
1900								getAvatarService().clear(account);
1901								updateConversationUi();
1902								updateAccountUi();
1903							} else {
1904								Contact contact = account.getRoster()
1905										.getContact(avatar.owner);
1906								contact.setAvatar(avatar.getFilename());
1907								getAvatarService().clear(contact);
1908								updateConversationUi();
1909								updateRosterUi();
1910							}
1911							if (callback != null) {
1912								callback.success(avatar);
1913							}
1914							Log.d(Config.LOGTAG, account.getJid().toBareJid()
1915									+ ": succesfully fetched avatar for "
1916									+ avatar.owner);
1917							return;
1918						}
1919					} else {
1920
1921						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
1922					}
1923				} else {
1924					Element error = result.findChild("error");
1925					if (error == null) {
1926						Log.d(Config.LOGTAG, ERROR + "(server error)");
1927					} else {
1928						Log.d(Config.LOGTAG, ERROR + error.toString());
1929					}
1930				}
1931				if (callback != null) {
1932					callback.error(0, null);
1933				}
1934
1935			}
1936		});
1937	}
1938
1939	public void checkForAvatar(Account account,
1940							   final UiCallback<Avatar> callback) {
1941		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
1942		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1943
1944			@Override
1945			public void onIqPacketReceived(Account account, IqPacket packet) {
1946				if (packet.getType() == IqPacket.TYPE.RESULT) {
1947					Element pubsub = packet.findChild("pubsub",
1948							"http://jabber.org/protocol/pubsub");
1949					if (pubsub != null) {
1950						Element items = pubsub.findChild("items");
1951						if (items != null) {
1952							Avatar avatar = Avatar.parseMetadata(items);
1953							if (avatar != null) {
1954								avatar.owner = account.getJid().toBareJid();
1955								if (fileBackend.isAvatarCached(avatar)) {
1956									if (account.setAvatar(avatar.getFilename())) {
1957										databaseBackend.updateAccount(account);
1958									}
1959									getAvatarService().clear(account);
1960									callback.success(avatar);
1961								} else {
1962									fetchAvatar(account, avatar, callback);
1963								}
1964								return;
1965							}
1966						}
1967					}
1968				}
1969				callback.error(0, null);
1970			}
1971		});
1972	}
1973
1974	public void deleteContactOnServer(Contact contact) {
1975		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
1976		contact.resetOption(Contact.Options.DIRTY_PUSH);
1977		contact.setOption(Contact.Options.DIRTY_DELETE);
1978		Account account = contact.getAccount();
1979		if (account.getStatus() == Account.State.ONLINE) {
1980			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1981			Element item = iq.query(Xmlns.ROSTER).addChild("item");
1982			item.setAttribute("jid", contact.getJid().toString());
1983			item.setAttribute("subscription", "remove");
1984			account.getXmppConnection().sendIqPacket(iq, null);
1985		}
1986	}
1987
1988	public void updateConversation(Conversation conversation) {
1989		this.databaseBackend.updateConversation(conversation);
1990	}
1991
1992	public void reconnectAccount(final Account account, final boolean force) {
1993		synchronized (account) {
1994			if (account.getXmppConnection() != null) {
1995				disconnect(account, force);
1996			}
1997			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
1998				if (account.getXmppConnection() == null) {
1999					account.setXmppConnection(createConnection(account));
2000				}
2001				Thread thread = new Thread(account.getXmppConnection());
2002				thread.start();
2003				scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
2004			} else {
2005				account.getRoster().clearPresences();
2006				account.setXmppConnection(null);
2007			}
2008		}
2009	}
2010
2011	public void reconnectAccountInBackground(final Account account) {
2012		new Thread(new Runnable() {
2013			@Override
2014			public void run() {
2015				reconnectAccount(account,false);
2016			}
2017		}).start();
2018	}
2019
2020	public void invite(Conversation conversation, Jid contact) {
2021		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2022		sendMessagePacket(conversation.getAccount(), packet);
2023	}
2024
2025	public void resetSendingToWaiting(Account account) {
2026		for (Conversation conversation : getConversations()) {
2027			if (conversation.getAccount() == account) {
2028				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2029
2030					@Override
2031					public void onMessageFound(Message message) {
2032						markMessage(message, Message.STATUS_WAITING);
2033					}
2034				});
2035			}
2036		}
2037	}
2038
2039	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2040		if (uuid == null) {
2041			return null;
2042		}
2043		for (Conversation conversation : getConversations()) {
2044			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2045				final Message message = conversation.findSentMessageWithUuid(uuid);
2046				if (message != null) {
2047					markMessage(message, status);
2048				}
2049				return message;
2050			}
2051		}
2052		return null;
2053	}
2054
2055	public boolean markMessage(Conversation conversation, String uuid,
2056							   int status) {
2057		if (uuid == null) {
2058			return false;
2059		} else {
2060			Message message = conversation.findSentMessageWithUuid(uuid);
2061			if (message != null) {
2062				markMessage(message, status);
2063				return true;
2064			} else {
2065				return false;
2066			}
2067		}
2068	}
2069
2070	public void markMessage(Message message, int status) {
2071		if (status == Message.STATUS_SEND_FAILED
2072				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2073				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2074			return;
2075		}
2076		message.setStatus(status);
2077		databaseBackend.updateMessage(message);
2078		updateConversationUi();
2079	}
2080
2081	public SharedPreferences getPreferences() {
2082		return PreferenceManager
2083				.getDefaultSharedPreferences(getApplicationContext());
2084	}
2085
2086	public boolean forceEncryption() {
2087		return getPreferences().getBoolean("force_encryption", false);
2088	}
2089
2090	public boolean confirmMessages() {
2091		return getPreferences().getBoolean("confirm_messages", true);
2092	}
2093
2094	public boolean sendChatStates() {
2095		return getPreferences().getBoolean("chat_states", false);
2096	}
2097
2098	public boolean saveEncryptedMessages() {
2099		return !getPreferences().getBoolean("dont_save_encrypted", false);
2100	}
2101
2102	public boolean indicateReceived() {
2103		return getPreferences().getBoolean("indicate_received", false);
2104	}
2105
2106	public int unreadCount() {
2107		int count = 0;
2108		for(Conversation conversation : getConversations()) {
2109			count += conversation.unreadCount();
2110		}
2111		return count;
2112	}
2113
2114	public void updateConversationUi() {
2115		if (mOnConversationUpdate != null) {
2116			mOnConversationUpdate.onConversationUpdate();
2117		}
2118	}
2119
2120	public void updateAccountUi() {
2121		if (mOnAccountUpdate != null) {
2122			mOnAccountUpdate.onAccountUpdate();
2123		}
2124	}
2125
2126	public void updateRosterUi() {
2127		if (mOnRosterUpdate != null) {
2128			mOnRosterUpdate.onRosterUpdate();
2129		}
2130	}
2131
2132	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2133		if (mOnUpdateBlocklist != null) {
2134			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2135		}
2136	}
2137
2138	public void updateMucRosterUi() {
2139		if (mOnMucRosterUpdate != null) {
2140			mOnMucRosterUpdate.onMucRosterUpdate();
2141		}
2142	}
2143
2144	public Account findAccountByJid(final Jid accountJid) {
2145		for (Account account : this.accounts) {
2146			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2147				return account;
2148			}
2149		}
2150		return null;
2151	}
2152
2153	public Conversation findConversationByUuid(String uuid) {
2154		for (Conversation conversation : getConversations()) {
2155			if (conversation.getUuid().equals(uuid)) {
2156				return conversation;
2157			}
2158		}
2159		return null;
2160	}
2161
2162	public void markRead(final Conversation conversation) {
2163		mNotificationService.clear(conversation);
2164		conversation.markRead();
2165	}
2166
2167	public void sendReadMarker(final Conversation conversation) {
2168		final Message markable = conversation.getLatestMarkableMessage();
2169		this.markRead(conversation);
2170		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2171			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2172			Account account = conversation.getAccount();
2173			final Jid to = markable.getCounterpart();
2174			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2175			this.sendMessagePacket(conversation.getAccount(), packet);
2176		}
2177		updateConversationUi();
2178	}
2179
2180	public SecureRandom getRNG() {
2181		return this.mRandom;
2182	}
2183
2184	public MemorizingTrustManager getMemorizingTrustManager() {
2185		return this.mMemorizingTrustManager;
2186	}
2187
2188	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2189		this.mMemorizingTrustManager = trustManager;
2190	}
2191
2192	public void updateMemorizingTrustmanager() {
2193		final MemorizingTrustManager tm;
2194		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2195		if (dontTrustSystemCAs) {
2196			 tm = new MemorizingTrustManager(getApplicationContext(), null);
2197		} else {
2198			tm = new MemorizingTrustManager(getApplicationContext());
2199		}
2200		setMemorizingTrustManager(tm);
2201	}
2202
2203	public PowerManager getPowerManager() {
2204		return this.pm;
2205	}
2206
2207	public LruCache<String, Bitmap> getBitmapCache() {
2208		return this.mBitmapCache;
2209	}
2210
2211	public void syncRosterToDisk(final Account account) {
2212		new Thread(new Runnable() {
2213
2214			@Override
2215			public void run() {
2216				databaseBackend.writeRoster(account.getRoster());
2217			}
2218		}).start();
2219
2220	}
2221
2222	public List<String> getKnownHosts() {
2223		final List<String> hosts = new ArrayList<>();
2224		for (final Account account : getAccounts()) {
2225			if (!hosts.contains(account.getServer().toString())) {
2226				hosts.add(account.getServer().toString());
2227			}
2228			for (final Contact contact : account.getRoster().getContacts()) {
2229				if (contact.showInRoster()) {
2230					final String server = contact.getServer().toString();
2231					if (server != null && !hosts.contains(server)) {
2232						hosts.add(server);
2233					}
2234				}
2235			}
2236		}
2237		return hosts;
2238	}
2239
2240	public List<String> getKnownConferenceHosts() {
2241		final ArrayList<String> mucServers = new ArrayList<>();
2242		for (final Account account : accounts) {
2243			if (account.getXmppConnection() != null) {
2244				final String server = account.getXmppConnection().getMucServer();
2245				if (server != null && !mucServers.contains(server)) {
2246					mucServers.add(server);
2247				}
2248			}
2249		}
2250		return mucServers;
2251	}
2252
2253	public void sendMessagePacket(Account account, MessagePacket packet) {
2254		XmppConnection connection = account.getXmppConnection();
2255		if (connection != null) {
2256			connection.sendMessagePacket(packet);
2257		}
2258	}
2259
2260	public void sendPresencePacket(Account account, PresencePacket packet) {
2261		XmppConnection connection = account.getXmppConnection();
2262		if (connection != null) {
2263			connection.sendPresencePacket(packet);
2264		}
2265	}
2266
2267	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2268		final XmppConnection connection = account.getXmppConnection();
2269		if (connection != null) {
2270			connection.sendIqPacket(packet, callback);
2271		}
2272	}
2273
2274	public void sendPresence(final Account account) {
2275		sendPresencePacket(account, mPresenceGenerator.sendPresence(account));
2276	}
2277
2278	public void sendOfflinePresence(final Account account) {
2279		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2280	}
2281
2282	public MessageGenerator getMessageGenerator() {
2283		return this.mMessageGenerator;
2284	}
2285
2286	public PresenceGenerator getPresenceGenerator() {
2287		return this.mPresenceGenerator;
2288	}
2289
2290	public IqGenerator getIqGenerator() {
2291		return this.mIqGenerator;
2292	}
2293
2294	public IqParser getIqParser() {
2295		return this.mIqParser;
2296	}
2297
2298	public JingleConnectionManager getJingleConnectionManager() {
2299		return this.mJingleConnectionManager;
2300	}
2301
2302	public MessageArchiveService getMessageArchiveService() {
2303		return this.mMessageArchiveService;
2304	}
2305
2306	public List<Contact> findContacts(Jid jid) {
2307		ArrayList<Contact> contacts = new ArrayList<>();
2308		for (Account account : getAccounts()) {
2309			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2310				Contact contact = account.getRoster().getContactFromRoster(jid);
2311				if (contact != null) {
2312					contacts.add(contact);
2313				}
2314			}
2315		}
2316		return contacts;
2317	}
2318
2319	public NotificationService getNotificationService() {
2320		return this.mNotificationService;
2321	}
2322
2323	public HttpConnectionManager getHttpConnectionManager() {
2324		return this.mHttpConnectionManager;
2325	}
2326
2327	public void resendFailedMessages(final Message message) {
2328		final Collection<Message> messages = new ArrayList<>();
2329		Message current = message;
2330		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2331			messages.add(current);
2332			if (current.mergeable(current.next())) {
2333				current = current.next();
2334			} else {
2335				break;
2336			}
2337		}
2338		for (final Message msg : messages) {
2339			markMessage(msg, Message.STATUS_WAITING);
2340			this.resendMessage(msg);
2341		}
2342	}
2343
2344	public void clearConversationHistory(final Conversation conversation) {
2345		conversation.clearMessages();
2346		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2347		new Thread(new Runnable() {
2348			@Override
2349			public void run() {
2350				databaseBackend.deleteMessagesInConversation(conversation);
2351			}
2352		}).start();
2353	}
2354
2355	public void sendBlockRequest(final Blockable blockable) {
2356		if (blockable != null && blockable.getBlockedJid() != null) {
2357			final Jid jid = blockable.getBlockedJid();
2358			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2359
2360				@Override
2361				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2362					if (packet.getType() == IqPacket.TYPE.RESULT) {
2363						account.getBlocklist().add(jid);
2364						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2365					}
2366				}
2367			});
2368		}
2369	}
2370
2371	public void sendUnblockRequest(final Blockable blockable) {
2372		if (blockable != null && blockable.getJid() != null) {
2373			final Jid jid = blockable.getBlockedJid();
2374			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2375				@Override
2376				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2377					if (packet.getType() == IqPacket.TYPE.RESULT) {
2378						account.getBlocklist().remove(jid);
2379						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2380					}
2381				}
2382			});
2383		}
2384	}
2385
2386	public interface OnMoreMessagesLoaded {
2387		public void onMoreMessagesLoaded(int count, Conversation conversation);
2388
2389		public void informUser(int r);
2390	}
2391
2392	public interface OnAccountPasswordChanged {
2393		public void onPasswordChangeSucceeded();
2394
2395		public void onPasswordChangeFailed();
2396	}
2397
2398	public interface OnAffiliationChanged {
2399		public void onAffiliationChangedSuccessful(Jid jid);
2400
2401		public void onAffiliationChangeFailed(Jid jid, int resId);
2402	}
2403
2404	public interface OnRoleChanged {
2405		public void onRoleChangedSuccessful(String nick);
2406
2407		public void onRoleChangeFailed(String nick, int resid);
2408	}
2409
2410	public interface OnConversationUpdate {
2411		public void onConversationUpdate();
2412	}
2413
2414	public interface OnAccountUpdate {
2415		public void onAccountUpdate();
2416	}
2417
2418	public interface OnRosterUpdate {
2419		public void onRosterUpdate();
2420	}
2421
2422	public interface OnMucRosterUpdate {
2423		public void onMucRosterUpdate();
2424	}
2425
2426	public interface OnConferenceOptionsPushed {
2427		public void onPushSucceeded();
2428
2429		public void onPushFailed();
2430	}
2431
2432	public class XmppConnectionBinder extends Binder {
2433		public XmppConnectionService getService() {
2434			return XmppConnectionService.this;
2435		}
2436	}
2437}