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