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