XmppConnectionService.java

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