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 (account.countPresences() > 1) {
1541							directInvite(conversation, account.getJid().toBareJid());
1542						}
1543						if (callback != null) {
1544							callback.success(conversation);
1545						}
1546					}
1547
1548					@Override
1549					public void onPushFailed() {
1550						if (callback != null) {
1551							callback.error(R.string.conference_creation_failed, conversation);
1552						}
1553					}
1554				});
1555
1556			} catch (InvalidJidException e) {
1557				if (callback != null) {
1558					callback.error(R.string.conference_creation_failed, null);
1559				}
1560			}
1561		} else {
1562			if (callback != null) {
1563				callback.error(R.string.not_connected_try_again, null);
1564			}
1565		}
1566	}
1567
1568	public void fetchConferenceConfiguration(final Conversation conversation) {
1569		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1570		request.setTo(conversation.getJid().toBareJid());
1571		request.query("http://jabber.org/protocol/disco#info");
1572		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1573			@Override
1574			public void onIqPacketReceived(Account account, IqPacket packet) {
1575				if (packet.getType() != IqPacket.TYPE.ERROR) {
1576					ArrayList<String> features = new ArrayList<>();
1577					for (Element child : packet.query().getChildren()) {
1578						if (child != null && child.getName().equals("feature")) {
1579							String var = child.getAttribute("var");
1580							if (var != null) {
1581								features.add(var);
1582							}
1583						}
1584					}
1585					conversation.getMucOptions().updateFeatures(features);
1586					updateConversationUi();
1587				}
1588			}
1589		});
1590	}
1591
1592	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1593		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1594		request.setTo(conversation.getJid().toBareJid());
1595		request.query("http://jabber.org/protocol/muc#owner");
1596		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1597			@Override
1598			public void onIqPacketReceived(Account account, IqPacket packet) {
1599				if (packet.getType() != IqPacket.TYPE.ERROR) {
1600					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1601					for (Field field : data.getFields()) {
1602						if (options.containsKey(field.getName())) {
1603							field.setValue(options.getString(field.getName()));
1604						}
1605					}
1606					data.submit();
1607					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1608					set.setTo(conversation.getJid().toBareJid());
1609					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1610					sendIqPacket(account, set, new OnIqPacketReceived() {
1611						@Override
1612						public void onIqPacketReceived(Account account, IqPacket packet) {
1613							if (packet.getType() == IqPacket.TYPE.RESULT) {
1614								if (callback != null) {
1615									callback.onPushSucceeded();
1616								}
1617							} else {
1618								if (callback != null) {
1619									callback.onPushFailed();
1620								}
1621							}
1622						}
1623					});
1624				} else {
1625					if (callback != null) {
1626						callback.onPushFailed();
1627					}
1628				}
1629			}
1630		});
1631	}
1632
1633	public void pushSubjectToConference(final Conversation conference, final String subject) {
1634		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1635		this.sendMessagePacket(conference.getAccount(), packet);
1636		final MucOptions mucOptions = conference.getMucOptions();
1637		final MucOptions.User self = mucOptions.getSelf();
1638		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1639			Bundle options = new Bundle();
1640			options.putString("muc#roomconfig_persistentroom", "1");
1641			this.pushConferenceConfiguration(conference, options, null);
1642		}
1643	}
1644
1645	public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1646		final Jid jid = user.toBareJid();
1647		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
1648		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1649			@Override
1650			public void onIqPacketReceived(Account account, IqPacket packet) {
1651				if (packet.getType() == IqPacket.TYPE.RESULT) {
1652					callback.onAffiliationChangedSuccessful(jid);
1653				} else {
1654					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
1655				}
1656			}
1657		});
1658	}
1659
1660	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
1661		List<Jid> jids = new ArrayList<>();
1662		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
1663			if (user.getAffiliation() == before) {
1664				jids.add(user.getJid());
1665			}
1666		}
1667		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
1668		sendIqPacket(conference.getAccount(), request, null);
1669	}
1670
1671	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
1672		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
1673		Log.d(Config.LOGTAG, request.toString());
1674		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1675			@Override
1676			public void onIqPacketReceived(Account account, IqPacket packet) {
1677				Log.d(Config.LOGTAG, packet.toString());
1678				if (packet.getType() == IqPacket.TYPE.RESULT) {
1679					callback.onRoleChangedSuccessful(nick);
1680				} else {
1681					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
1682				}
1683			}
1684		});
1685	}
1686
1687	public void disconnect(Account account, boolean force) {
1688		if ((account.getStatus() == Account.State.ONLINE)
1689				|| (account.getStatus() == Account.State.DISABLED)) {
1690			if (!force) {
1691				List<Conversation> conversations = getConversations();
1692				for (Conversation conversation : conversations) {
1693					if (conversation.getAccount() == account) {
1694						if (conversation.getMode() == Conversation.MODE_MULTI) {
1695							leaveMuc(conversation);
1696						} else {
1697							if (conversation.endOtrIfNeeded()) {
1698								Log.d(Config.LOGTAG, account.getJid().toBareJid()
1699										+ ": ended otr session with "
1700										+ conversation.getJid());
1701							}
1702						}
1703					}
1704				}
1705				sendOfflinePresence(account);
1706			}
1707			account.getXmppConnection().disconnect(force);
1708		}
1709	}
1710
1711	@Override
1712	public IBinder onBind(Intent intent) {
1713		return mBinder;
1714	}
1715
1716	public void updateMessage(Message message) {
1717		databaseBackend.updateMessage(message);
1718		updateConversationUi();
1719	}
1720
1721	protected void syncDirtyContacts(Account account) {
1722		for (Contact contact : account.getRoster().getContacts()) {
1723			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1724				pushContactToServer(contact);
1725			}
1726			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1727				deleteContactOnServer(contact);
1728			}
1729		}
1730	}
1731
1732	public void createContact(Contact contact) {
1733		SharedPreferences sharedPref = getPreferences();
1734		boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1735		if (autoGrant) {
1736			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1737			contact.setOption(Contact.Options.ASKING);
1738		}
1739		pushContactToServer(contact);
1740	}
1741
1742	public void onOtrSessionEstablished(Conversation conversation) {
1743		final Account account = conversation.getAccount();
1744		final Session otrSession = conversation.getOtrSession();
1745		Log.d(Config.LOGTAG,
1746				account.getJid().toBareJid() + " otr session established with "
1747						+ conversation.getJid() + "/"
1748						+ otrSession.getSessionID().getUserID());
1749		conversation.findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
1750
1751			@Override
1752			public void onMessageFound(Message message) {
1753				SessionID id = otrSession.getSessionID();
1754				try {
1755					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
1756				} catch (InvalidJidException e) {
1757					return;
1758				}
1759				if (message.getType() == Message.TYPE_TEXT) {
1760					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message, true);
1761					if (outPacket != null) {
1762						message.setStatus(Message.STATUS_SEND);
1763						databaseBackend.updateMessage(message);
1764						sendMessagePacket(account, outPacket);
1765					}
1766				} else if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
1767					mJingleConnectionManager.createNewConnection(message);
1768				}
1769				updateConversationUi();
1770			}
1771		});
1772	}
1773
1774	public boolean renewSymmetricKey(Conversation conversation) {
1775		Account account = conversation.getAccount();
1776		byte[] symmetricKey = new byte[32];
1777		this.mRandom.nextBytes(symmetricKey);
1778		Session otrSession = conversation.getOtrSession();
1779		if (otrSession != null) {
1780			MessagePacket packet = new MessagePacket();
1781			packet.setType(MessagePacket.TYPE_CHAT);
1782			packet.setFrom(account.getJid());
1783			packet.addChild("private", "urn:xmpp:carbons:2");
1784			packet.addChild("no-copy", "urn:xmpp:hints");
1785			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
1786					+ otrSession.getSessionID().getUserID());
1787			try {
1788				packet.setBody(otrSession
1789						.transformSending(CryptoHelper.FILETRANSFER
1790								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
1791				sendMessagePacket(account, packet);
1792				conversation.setSymmetricKey(symmetricKey);
1793				return true;
1794			} catch (OtrException e) {
1795				return false;
1796			}
1797		}
1798		return false;
1799	}
1800
1801	public void pushContactToServer(final Contact contact) {
1802		contact.resetOption(Contact.Options.DIRTY_DELETE);
1803		contact.setOption(Contact.Options.DIRTY_PUSH);
1804		final Account account = contact.getAccount();
1805		if (account.getStatus() == Account.State.ONLINE) {
1806			final boolean ask = contact.getOption(Contact.Options.ASKING);
1807			final boolean sendUpdates = contact
1808					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
1809					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
1810			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1811			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
1812			account.getXmppConnection().sendIqPacket(iq, null);
1813			if (sendUpdates) {
1814				sendPresencePacket(account,
1815						mPresenceGenerator.sendPresenceUpdatesTo(contact));
1816			}
1817			if (ask) {
1818				sendPresencePacket(account,
1819						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
1820			}
1821		}
1822	}
1823
1824	public void publishAvatar(final Account account,
1825							  final Uri image,
1826							  final UiCallback<Avatar> callback) {
1827		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
1828		final int size = Config.AVATAR_SIZE;
1829		final Avatar avatar = getFileBackend()
1830				.getPepAvatar(image, size, format);
1831		if (avatar != null) {
1832			avatar.height = size;
1833			avatar.width = size;
1834			if (format.equals(Bitmap.CompressFormat.WEBP)) {
1835				avatar.type = "image/webp";
1836			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1837				avatar.type = "image/jpeg";
1838			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
1839				avatar.type = "image/png";
1840			}
1841			if (!getFileBackend().save(avatar)) {
1842				callback.error(R.string.error_saving_avatar, avatar);
1843				return;
1844			}
1845			final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
1846			this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1847
1848				@Override
1849				public void onIqPacketReceived(Account account, IqPacket result) {
1850					if (result.getType() == IqPacket.TYPE.RESULT) {
1851						final IqPacket packet = XmppConnectionService.this.mIqGenerator
1852								.publishAvatarMetadata(avatar);
1853						sendIqPacket(account, packet, new OnIqPacketReceived() {
1854
1855							@Override
1856							public void onIqPacketReceived(Account account,
1857														   IqPacket result) {
1858								if (result.getType() == IqPacket.TYPE.RESULT) {
1859									if (account.setAvatar(avatar.getFilename())) {
1860										databaseBackend.updateAccount(account);
1861									}
1862									callback.success(avatar);
1863								} else {
1864									callback.error(
1865											R.string.error_publish_avatar_server_reject,
1866											avatar);
1867								}
1868							}
1869						});
1870					} else {
1871						callback.error(
1872								R.string.error_publish_avatar_server_reject,
1873								avatar);
1874					}
1875				}
1876			});
1877		} else {
1878			callback.error(R.string.error_publish_avatar_converting, null);
1879		}
1880	}
1881
1882	public void fetchAvatar(Account account, Avatar avatar) {
1883		fetchAvatar(account, avatar, null);
1884	}
1885
1886	public void fetchAvatar(Account account, final Avatar avatar,
1887							final UiCallback<Avatar> callback) {
1888		IqPacket packet = this.mIqGenerator.retrieveAvatar(avatar);
1889		sendIqPacket(account, packet, new OnIqPacketReceived() {
1890
1891			@Override
1892			public void onIqPacketReceived(Account account, IqPacket result) {
1893				final String ERROR = account.getJid().toBareJid()
1894						+ ": fetching avatar for " + avatar.owner + " failed ";
1895				if (result.getType() == IqPacket.TYPE.RESULT) {
1896					avatar.image = mIqParser.avatarData(result);
1897					if (avatar.image != null) {
1898						if (getFileBackend().save(avatar)) {
1899							if (account.getJid().toBareJid().equals(avatar.owner)) {
1900								if (account.setAvatar(avatar.getFilename())) {
1901									databaseBackend.updateAccount(account);
1902								}
1903								getAvatarService().clear(account);
1904								updateConversationUi();
1905								updateAccountUi();
1906							} else {
1907								Contact contact = account.getRoster()
1908										.getContact(avatar.owner);
1909								contact.setAvatar(avatar.getFilename());
1910								getAvatarService().clear(contact);
1911								updateConversationUi();
1912								updateRosterUi();
1913							}
1914							if (callback != null) {
1915								callback.success(avatar);
1916							}
1917							Log.d(Config.LOGTAG, account.getJid().toBareJid()
1918									+ ": succesfully fetched avatar for "
1919									+ avatar.owner);
1920							return;
1921						}
1922					} else {
1923
1924						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
1925					}
1926				} else {
1927					Element error = result.findChild("error");
1928					if (error == null) {
1929						Log.d(Config.LOGTAG, ERROR + "(server error)");
1930					} else {
1931						Log.d(Config.LOGTAG, ERROR + error.toString());
1932					}
1933				}
1934				if (callback != null) {
1935					callback.error(0, null);
1936				}
1937
1938			}
1939		});
1940	}
1941
1942	public void checkForAvatar(Account account,
1943							   final UiCallback<Avatar> callback) {
1944		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
1945		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1946
1947			@Override
1948			public void onIqPacketReceived(Account account, IqPacket packet) {
1949				if (packet.getType() == IqPacket.TYPE.RESULT) {
1950					Element pubsub = packet.findChild("pubsub",
1951							"http://jabber.org/protocol/pubsub");
1952					if (pubsub != null) {
1953						Element items = pubsub.findChild("items");
1954						if (items != null) {
1955							Avatar avatar = Avatar.parseMetadata(items);
1956							if (avatar != null) {
1957								avatar.owner = account.getJid().toBareJid();
1958								if (fileBackend.isAvatarCached(avatar)) {
1959									if (account.setAvatar(avatar.getFilename())) {
1960										databaseBackend.updateAccount(account);
1961									}
1962									getAvatarService().clear(account);
1963									callback.success(avatar);
1964								} else {
1965									fetchAvatar(account, avatar, callback);
1966								}
1967								return;
1968							}
1969						}
1970					}
1971				}
1972				callback.error(0, null);
1973			}
1974		});
1975	}
1976
1977	public void deleteContactOnServer(Contact contact) {
1978		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
1979		contact.resetOption(Contact.Options.DIRTY_PUSH);
1980		contact.setOption(Contact.Options.DIRTY_DELETE);
1981		Account account = contact.getAccount();
1982		if (account.getStatus() == Account.State.ONLINE) {
1983			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1984			Element item = iq.query(Xmlns.ROSTER).addChild("item");
1985			item.setAttribute("jid", contact.getJid().toString());
1986			item.setAttribute("subscription", "remove");
1987			account.getXmppConnection().sendIqPacket(iq, null);
1988		}
1989	}
1990
1991	public void updateConversation(Conversation conversation) {
1992		this.databaseBackend.updateConversation(conversation);
1993	}
1994
1995	public void reconnectAccount(final Account account, final boolean force) {
1996		synchronized (account) {
1997			if (account.getXmppConnection() != null) {
1998				disconnect(account, force);
1999			}
2000			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2001				if (account.getXmppConnection() == null) {
2002					account.setXmppConnection(createConnection(account));
2003				}
2004				Thread thread = new Thread(account.getXmppConnection());
2005				thread.start();
2006				scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
2007			} else {
2008				account.getRoster().clearPresences();
2009				account.setXmppConnection(null);
2010			}
2011		}
2012	}
2013
2014	public void reconnectAccountInBackground(final Account account) {
2015		new Thread(new Runnable() {
2016			@Override
2017			public void run() {
2018				reconnectAccount(account,false);
2019			}
2020		}).start();
2021	}
2022
2023	public void invite(Conversation conversation, Jid contact) {
2024		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2025		sendMessagePacket(conversation.getAccount(), packet);
2026	}
2027
2028	public void directInvite(Conversation conversation, Jid jid) {
2029		MessagePacket packet = mMessageGenerator.directInvite(conversation,jid);
2030		sendMessagePacket(conversation.getAccount(),packet);
2031	}
2032
2033	public void resetSendingToWaiting(Account account) {
2034		for (Conversation conversation : getConversations()) {
2035			if (conversation.getAccount() == account) {
2036				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2037
2038					@Override
2039					public void onMessageFound(Message message) {
2040						markMessage(message, Message.STATUS_WAITING);
2041					}
2042				});
2043			}
2044		}
2045	}
2046
2047	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2048		if (uuid == null) {
2049			return null;
2050		}
2051		for (Conversation conversation : getConversations()) {
2052			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2053				final Message message = conversation.findSentMessageWithUuid(uuid);
2054				if (message != null) {
2055					markMessage(message, status);
2056				}
2057				return message;
2058			}
2059		}
2060		return null;
2061	}
2062
2063	public boolean markMessage(Conversation conversation, String uuid,
2064							   int status) {
2065		if (uuid == null) {
2066			return false;
2067		} else {
2068			Message message = conversation.findSentMessageWithUuid(uuid);
2069			if (message != null) {
2070				markMessage(message, status);
2071				return true;
2072			} else {
2073				return false;
2074			}
2075		}
2076	}
2077
2078	public void markMessage(Message message, int status) {
2079		if (status == Message.STATUS_SEND_FAILED
2080				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2081				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2082			return;
2083		}
2084		message.setStatus(status);
2085		databaseBackend.updateMessage(message);
2086		updateConversationUi();
2087	}
2088
2089	public SharedPreferences getPreferences() {
2090		return PreferenceManager
2091				.getDefaultSharedPreferences(getApplicationContext());
2092	}
2093
2094	public boolean forceEncryption() {
2095		return getPreferences().getBoolean("force_encryption", false);
2096	}
2097
2098	public boolean confirmMessages() {
2099		return getPreferences().getBoolean("confirm_messages", true);
2100	}
2101
2102	public boolean sendChatStates() {
2103		return getPreferences().getBoolean("chat_states", false);
2104	}
2105
2106	public boolean saveEncryptedMessages() {
2107		return !getPreferences().getBoolean("dont_save_encrypted", false);
2108	}
2109
2110	public boolean indicateReceived() {
2111		return getPreferences().getBoolean("indicate_received", false);
2112	}
2113
2114	public int unreadCount() {
2115		int count = 0;
2116		for(Conversation conversation : getConversations()) {
2117			count += conversation.unreadCount();
2118		}
2119		return count;
2120	}
2121
2122	public void updateConversationUi() {
2123		if (mOnConversationUpdate != null) {
2124			mOnConversationUpdate.onConversationUpdate();
2125		}
2126	}
2127
2128	public void updateAccountUi() {
2129		if (mOnAccountUpdate != null) {
2130			mOnAccountUpdate.onAccountUpdate();
2131		}
2132	}
2133
2134	public void updateRosterUi() {
2135		if (mOnRosterUpdate != null) {
2136			mOnRosterUpdate.onRosterUpdate();
2137		}
2138	}
2139
2140	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2141		if (mOnUpdateBlocklist != null) {
2142			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2143		}
2144	}
2145
2146	public void updateMucRosterUi() {
2147		if (mOnMucRosterUpdate != null) {
2148			mOnMucRosterUpdate.onMucRosterUpdate();
2149		}
2150	}
2151
2152	public Account findAccountByJid(final Jid accountJid) {
2153		for (Account account : this.accounts) {
2154			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2155				return account;
2156			}
2157		}
2158		return null;
2159	}
2160
2161	public Conversation findConversationByUuid(String uuid) {
2162		for (Conversation conversation : getConversations()) {
2163			if (conversation.getUuid().equals(uuid)) {
2164				return conversation;
2165			}
2166		}
2167		return null;
2168	}
2169
2170	public void markRead(final Conversation conversation) {
2171		mNotificationService.clear(conversation);
2172		conversation.markRead();
2173	}
2174
2175	public void sendReadMarker(final Conversation conversation) {
2176		final Message markable = conversation.getLatestMarkableMessage();
2177		this.markRead(conversation);
2178		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2179			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2180			Account account = conversation.getAccount();
2181			final Jid to = markable.getCounterpart();
2182			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2183			this.sendMessagePacket(conversation.getAccount(), packet);
2184		}
2185		updateConversationUi();
2186	}
2187
2188	public SecureRandom getRNG() {
2189		return this.mRandom;
2190	}
2191
2192	public MemorizingTrustManager getMemorizingTrustManager() {
2193		return this.mMemorizingTrustManager;
2194	}
2195
2196	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2197		this.mMemorizingTrustManager = trustManager;
2198	}
2199
2200	public void updateMemorizingTrustmanager() {
2201		final MemorizingTrustManager tm;
2202		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2203		if (dontTrustSystemCAs) {
2204			 tm = new MemorizingTrustManager(getApplicationContext(), null);
2205		} else {
2206			tm = new MemorizingTrustManager(getApplicationContext());
2207		}
2208		setMemorizingTrustManager(tm);
2209	}
2210
2211	public PowerManager getPowerManager() {
2212		return this.pm;
2213	}
2214
2215	public LruCache<String, Bitmap> getBitmapCache() {
2216		return this.mBitmapCache;
2217	}
2218
2219	public void syncRosterToDisk(final Account account) {
2220		new Thread(new Runnable() {
2221
2222			@Override
2223			public void run() {
2224				databaseBackend.writeRoster(account.getRoster());
2225			}
2226		}).start();
2227
2228	}
2229
2230	public List<String> getKnownHosts() {
2231		final List<String> hosts = new ArrayList<>();
2232		for (final Account account : getAccounts()) {
2233			if (!hosts.contains(account.getServer().toString())) {
2234				hosts.add(account.getServer().toString());
2235			}
2236			for (final Contact contact : account.getRoster().getContacts()) {
2237				if (contact.showInRoster()) {
2238					final String server = contact.getServer().toString();
2239					if (server != null && !hosts.contains(server)) {
2240						hosts.add(server);
2241					}
2242				}
2243			}
2244		}
2245		return hosts;
2246	}
2247
2248	public List<String> getKnownConferenceHosts() {
2249		final ArrayList<String> mucServers = new ArrayList<>();
2250		for (final Account account : accounts) {
2251			if (account.getXmppConnection() != null) {
2252				final String server = account.getXmppConnection().getMucServer();
2253				if (server != null && !mucServers.contains(server)) {
2254					mucServers.add(server);
2255				}
2256			}
2257		}
2258		return mucServers;
2259	}
2260
2261	public void sendMessagePacket(Account account, MessagePacket packet) {
2262		XmppConnection connection = account.getXmppConnection();
2263		if (connection != null) {
2264			connection.sendMessagePacket(packet);
2265		}
2266	}
2267
2268	public void sendPresencePacket(Account account, PresencePacket packet) {
2269		XmppConnection connection = account.getXmppConnection();
2270		if (connection != null) {
2271			connection.sendPresencePacket(packet);
2272		}
2273	}
2274
2275	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2276		final XmppConnection connection = account.getXmppConnection();
2277		if (connection != null) {
2278			connection.sendIqPacket(packet, callback);
2279		}
2280	}
2281
2282	public void sendPresence(final Account account) {
2283		sendPresencePacket(account, mPresenceGenerator.sendPresence(account));
2284	}
2285
2286	public void sendOfflinePresence(final Account account) {
2287		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2288	}
2289
2290	public MessageGenerator getMessageGenerator() {
2291		return this.mMessageGenerator;
2292	}
2293
2294	public PresenceGenerator getPresenceGenerator() {
2295		return this.mPresenceGenerator;
2296	}
2297
2298	public IqGenerator getIqGenerator() {
2299		return this.mIqGenerator;
2300	}
2301
2302	public IqParser getIqParser() {
2303		return this.mIqParser;
2304	}
2305
2306	public JingleConnectionManager getJingleConnectionManager() {
2307		return this.mJingleConnectionManager;
2308	}
2309
2310	public MessageArchiveService getMessageArchiveService() {
2311		return this.mMessageArchiveService;
2312	}
2313
2314	public List<Contact> findContacts(Jid jid) {
2315		ArrayList<Contact> contacts = new ArrayList<>();
2316		for (Account account : getAccounts()) {
2317			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2318				Contact contact = account.getRoster().getContactFromRoster(jid);
2319				if (contact != null) {
2320					contacts.add(contact);
2321				}
2322			}
2323		}
2324		return contacts;
2325	}
2326
2327	public NotificationService getNotificationService() {
2328		return this.mNotificationService;
2329	}
2330
2331	public HttpConnectionManager getHttpConnectionManager() {
2332		return this.mHttpConnectionManager;
2333	}
2334
2335	public void resendFailedMessages(final Message message) {
2336		final Collection<Message> messages = new ArrayList<>();
2337		Message current = message;
2338		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2339			messages.add(current);
2340			if (current.mergeable(current.next())) {
2341				current = current.next();
2342			} else {
2343				break;
2344			}
2345		}
2346		for (final Message msg : messages) {
2347			markMessage(msg, Message.STATUS_WAITING);
2348			this.resendMessage(msg);
2349		}
2350	}
2351
2352	public void clearConversationHistory(final Conversation conversation) {
2353		conversation.clearMessages();
2354		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2355		new Thread(new Runnable() {
2356			@Override
2357			public void run() {
2358				databaseBackend.deleteMessagesInConversation(conversation);
2359			}
2360		}).start();
2361	}
2362
2363	public void sendBlockRequest(final Blockable blockable) {
2364		if (blockable != null && blockable.getBlockedJid() != null) {
2365			final Jid jid = blockable.getBlockedJid();
2366			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2367
2368				@Override
2369				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2370					if (packet.getType() == IqPacket.TYPE.RESULT) {
2371						account.getBlocklist().add(jid);
2372						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2373					}
2374				}
2375			});
2376		}
2377	}
2378
2379	public void sendUnblockRequest(final Blockable blockable) {
2380		if (blockable != null && blockable.getJid() != null) {
2381			final Jid jid = blockable.getBlockedJid();
2382			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2383				@Override
2384				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2385					if (packet.getType() == IqPacket.TYPE.RESULT) {
2386						account.getBlocklist().remove(jid);
2387						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2388					}
2389				}
2390			});
2391		}
2392	}
2393
2394	public interface OnMoreMessagesLoaded {
2395		public void onMoreMessagesLoaded(int count, Conversation conversation);
2396
2397		public void informUser(int r);
2398	}
2399
2400	public interface OnAccountPasswordChanged {
2401		public void onPasswordChangeSucceeded();
2402
2403		public void onPasswordChangeFailed();
2404	}
2405
2406	public interface OnAffiliationChanged {
2407		public void onAffiliationChangedSuccessful(Jid jid);
2408
2409		public void onAffiliationChangeFailed(Jid jid, int resId);
2410	}
2411
2412	public interface OnRoleChanged {
2413		public void onRoleChangedSuccessful(String nick);
2414
2415		public void onRoleChangeFailed(String nick, int resid);
2416	}
2417
2418	public interface OnConversationUpdate {
2419		public void onConversationUpdate();
2420	}
2421
2422	public interface OnAccountUpdate {
2423		public void onAccountUpdate();
2424	}
2425
2426	public interface OnRosterUpdate {
2427		public void onRosterUpdate();
2428	}
2429
2430	public interface OnMucRosterUpdate {
2431		public void onMucRosterUpdate();
2432	}
2433
2434	public interface OnConferenceOptionsPushed {
2435		public void onPushSucceeded();
2436
2437		public void onPushFailed();
2438	}
2439
2440	public class XmppConnectionBinder extends Binder {
2441		public XmppConnectionService getService() {
2442			return XmppConnectionService.this;
2443		}
2444	}
2445}