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.IntentFilter;
  10import android.content.SharedPreferences;
  11import android.database.ContentObserver;
  12import android.graphics.Bitmap;
  13import android.media.AudioManager;
  14import android.net.ConnectivityManager;
  15import android.net.NetworkInfo;
  16import android.net.Uri;
  17import android.os.Binder;
  18import android.os.Build;
  19import android.os.Bundle;
  20import android.os.FileObserver;
  21import android.os.IBinder;
  22import android.os.Looper;
  23import android.os.PowerManager;
  24import android.os.PowerManager.WakeLock;
  25import android.os.SystemClock;
  26import android.preference.PreferenceManager;
  27import android.provider.ContactsContract;
  28import android.security.KeyChain;
  29import android.util.DisplayMetrics;
  30import android.util.Log;
  31import android.util.LruCache;
  32import android.util.Pair;
  33
  34import net.java.otr4j.OtrException;
  35import net.java.otr4j.session.Session;
  36import net.java.otr4j.session.SessionID;
  37import net.java.otr4j.session.SessionImpl;
  38import net.java.otr4j.session.SessionStatus;
  39
  40import org.openintents.openpgp.IOpenPgpService2;
  41import org.openintents.openpgp.util.OpenPgpApi;
  42import org.openintents.openpgp.util.OpenPgpServiceConnection;
  43
  44import java.math.BigInteger;
  45import java.security.SecureRandom;
  46import java.security.cert.CertificateException;
  47import java.security.cert.X509Certificate;
  48import java.util.ArrayList;
  49import java.util.Arrays;
  50import java.util.Collection;
  51import java.util.Collections;
  52import java.util.Comparator;
  53import java.util.HashMap;
  54import java.util.Hashtable;
  55import java.util.Iterator;
  56import java.util.List;
  57import java.util.Locale;
  58import java.util.Map;
  59import java.util.concurrent.CopyOnWriteArrayList;
  60
  61import de.duenndns.ssl.MemorizingTrustManager;
  62import eu.siacs.conversations.Config;
  63import eu.siacs.conversations.R;
  64import eu.siacs.conversations.crypto.PgpEngine;
  65import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  66import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
  67import eu.siacs.conversations.entities.Account;
  68import eu.siacs.conversations.entities.Blockable;
  69import eu.siacs.conversations.entities.Bookmark;
  70import eu.siacs.conversations.entities.Contact;
  71import eu.siacs.conversations.entities.Conversation;
  72import eu.siacs.conversations.entities.Message;
  73import eu.siacs.conversations.entities.MucOptions;
  74import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
  75import eu.siacs.conversations.entities.Presence;
  76import eu.siacs.conversations.entities.Roster;
  77import eu.siacs.conversations.entities.ServiceDiscoveryResult;
  78import eu.siacs.conversations.entities.Transferable;
  79import eu.siacs.conversations.entities.TransferablePlaceholder;
  80import eu.siacs.conversations.generator.IqGenerator;
  81import eu.siacs.conversations.generator.MessageGenerator;
  82import eu.siacs.conversations.generator.PresenceGenerator;
  83import eu.siacs.conversations.http.HttpConnectionManager;
  84import eu.siacs.conversations.parser.IqParser;
  85import eu.siacs.conversations.parser.MessageParser;
  86import eu.siacs.conversations.parser.PresenceParser;
  87import eu.siacs.conversations.persistance.DatabaseBackend;
  88import eu.siacs.conversations.persistance.FileBackend;
  89import eu.siacs.conversations.ui.UiCallback;
  90import eu.siacs.conversations.utils.CryptoHelper;
  91import eu.siacs.conversations.utils.ExceptionHelper;
  92import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
  93import eu.siacs.conversations.utils.PRNGFixes;
  94import eu.siacs.conversations.utils.PhoneHelper;
  95import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
  96import eu.siacs.conversations.utils.Xmlns;
  97import eu.siacs.conversations.xml.Element;
  98import eu.siacs.conversations.xmpp.OnBindListener;
  99import eu.siacs.conversations.xmpp.OnContactStatusChanged;
 100import eu.siacs.conversations.xmpp.OnIqPacketReceived;
 101import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
 102import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
 103import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
 104import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
 105import eu.siacs.conversations.xmpp.OnStatusChanged;
 106import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 107import eu.siacs.conversations.xmpp.XmppConnection;
 108import eu.siacs.conversations.xmpp.chatstate.ChatState;
 109import eu.siacs.conversations.xmpp.forms.Data;
 110import eu.siacs.conversations.xmpp.forms.Field;
 111import eu.siacs.conversations.xmpp.jid.InvalidJidException;
 112import eu.siacs.conversations.xmpp.jid.Jid;
 113import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
 114import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
 115import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
 116import eu.siacs.conversations.xmpp.pep.Avatar;
 117import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 118import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 119import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
 120import me.leolin.shortcutbadger.ShortcutBadger;
 121
 122public class XmppConnectionService extends Service implements OnPhoneContactsLoadedListener {
 123
 124	public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification";
 125	public static final String ACTION_DISABLE_FOREGROUND = "disable_foreground";
 126	public static final String ACTION_TRY_AGAIN = "try_again";
 127	public static final String ACTION_DISABLE_ACCOUNT = "disable_account";
 128	private static final String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
 129	public static final String ACTION_GCM_TOKEN_REFRESH = "gcm_token_refresh";
 130	public static final String ACTION_GCM_MESSAGE_RECEIVED = "gcm_message_received";
 131	private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor();
 132	private final SerialSingleThreadExecutor mDatabaseExecutor = new SerialSingleThreadExecutor();
 133	private final IBinder mBinder = new XmppConnectionBinder();
 134	private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
 135	private final IqGenerator mIqGenerator = new IqGenerator(this);
 136	private final List<String> mInProgressAvatarFetches = new ArrayList<>();
 137	public DatabaseBackend databaseBackend;
 138	private ContentObserver contactObserver = new ContentObserver(null) {
 139		@Override
 140		public void onChange(boolean selfChange) {
 141			super.onChange(selfChange);
 142			Intent intent = new Intent(getApplicationContext(),
 143					XmppConnectionService.class);
 144			intent.setAction(ACTION_MERGE_PHONE_CONTACTS);
 145			startService(intent);
 146		}
 147	};
 148	private FileBackend fileBackend = new FileBackend(this);
 149	private MemorizingTrustManager mMemorizingTrustManager;
 150	private NotificationService mNotificationService = new NotificationService(
 151			this);
 152	private OnMessagePacketReceived mMessageParser = new MessageParser(this);
 153	private OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
 154	private IqParser mIqParser = new IqParser(this);
 155	private OnIqPacketReceived mDefaultIqHandler = new OnIqPacketReceived() {
 156		@Override
 157		public void onIqPacketReceived(Account account, IqPacket packet) {
 158			if (packet.getType() != IqPacket.TYPE.RESULT) {
 159				Element error = packet.findChild("error");
 160				String text = error != null ? error.findChildContent("text") : null;
 161				if (text != null) {
 162					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": received iq error - " + text);
 163				}
 164			}
 165		}
 166	};
 167	private MessageGenerator mMessageGenerator = new MessageGenerator(this);
 168	private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
 169	private List<Account> accounts;
 170	private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
 171			this);
 172	public OnContactStatusChanged onContactStatusChanged = new OnContactStatusChanged() {
 173
 174		@Override
 175		public void onContactStatusChanged(Contact contact, boolean online) {
 176			Conversation conversation = find(getConversations(), contact);
 177			if (conversation != null) {
 178				if (online) {
 179					conversation.endOtrIfNeeded();
 180					if (contact.getPresences().size() == 1) {
 181						sendUnsentMessages(conversation);
 182					}
 183				} else {
 184					if (contact.getPresences().size() >= 1) {
 185						if (conversation.hasValidOtrSession()) {
 186							String otrResource = conversation.getOtrSession().getSessionID().getUserID();
 187							if (!(Arrays.asList(contact.getPresences().asStringArray()).contains(otrResource))) {
 188								conversation.endOtrIfNeeded();
 189							}
 190						}
 191					} else {
 192						conversation.endOtrIfNeeded();
 193					}
 194				}
 195			}
 196		}
 197	};
 198	private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(
 199			this);
 200	private AvatarService mAvatarService = new AvatarService(this);
 201	private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
 202	private PushManagementService mPushManagementService = new PushManagementService(this);
 203	private OnConversationUpdate mOnConversationUpdate = null;
 204	private final FileObserver fileObserver = new FileObserver(
 205			FileBackend.getConversationsImageDirectory()) {
 206
 207		@Override
 208		public void onEvent(int event, String path) {
 209			if (event == FileObserver.DELETE) {
 210				markFileDeleted(path.split("\\.")[0]);
 211			}
 212		}
 213	};
 214	private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
 215
 216		@Override
 217		public void onJinglePacketReceived(Account account, JinglePacket packet) {
 218			mJingleConnectionManager.deliverPacket(account, packet);
 219		}
 220	};
 221	private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
 222
 223		@Override
 224		public void onMessageAcknowledged(Account account, String uuid) {
 225			for (final Conversation conversation : getConversations()) {
 226				if (conversation.getAccount() == account) {
 227					Message message = conversation.findUnsentMessageWithUuid(uuid);
 228					if (message != null) {
 229						markMessage(message, Message.STATUS_SEND);
 230					}
 231				}
 232			}
 233		}
 234	};
 235	private int convChangedListenerCount = 0;
 236	private OnShowErrorToast mOnShowErrorToast = null;
 237	private int showErrorToastListenerCount = 0;
 238	private int unreadCount = -1;
 239	private OnAccountUpdate mOnAccountUpdate = null;
 240	private OnCaptchaRequested mOnCaptchaRequested = null;
 241	private int accountChangedListenerCount = 0;
 242	private int captchaRequestedListenerCount = 0;
 243	private OnRosterUpdate mOnRosterUpdate = null;
 244	private OnUpdateBlocklist mOnUpdateBlocklist = null;
 245	private int updateBlocklistListenerCount = 0;
 246	private int rosterChangedListenerCount = 0;
 247	private OnMucRosterUpdate mOnMucRosterUpdate = null;
 248	private int mucRosterChangedListenerCount = 0;
 249	private OnKeyStatusUpdated mOnKeyStatusUpdated = null;
 250	private int keyStatusUpdatedListenerCount = 0;
 251	private SecureRandom mRandom;
 252	private LruCache<Pair<String,String>,ServiceDiscoveryResult> discoCache = new LruCache<>(20);
 253	private final OnBindListener mOnBindListener = new OnBindListener() {
 254
 255		@Override
 256		public void onBind(final Account account) {
 257			account.getRoster().clearPresences();
 258			mJingleConnectionManager.cancelInTransmission();
 259			fetchRosterFromServer(account);
 260			fetchBookmarks(account);
 261			sendPresence(account);
 262			if (mPushManagementService.pushAvailable(account)) {
 263				mPushManagementService.registerPushTokenOnServer(account);
 264			}
 265			mMessageArchiveService.executePendingQueries(account);
 266			connectMultiModeConversations(account);
 267			syncDirtyContacts(account);
 268		}
 269	};
 270	private OnStatusChanged statusListener = new OnStatusChanged() {
 271
 272		@Override
 273		public void onStatusChanged(final Account account) {
 274			XmppConnection connection = account.getXmppConnection();
 275			if (mOnAccountUpdate != null) {
 276				mOnAccountUpdate.onAccountUpdate();
 277			}
 278			if (account.getStatus() == Account.State.ONLINE) {
 279				if (connection != null && connection.getFeatures().csi()) {
 280					if (checkListeners()) {
 281						Log.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//inactive");
 282						connection.sendInactive();
 283					} else {
 284						Log.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//active");
 285						connection.sendActive();
 286					}
 287				}
 288				List<Conversation> conversations = getConversations();
 289				for (Conversation conversation : conversations) {
 290					if (conversation.getAccount() == account && conversation.getMode() == Conversation.MODE_SINGLE) {
 291						conversation.startOtrIfNeeded();
 292						sendUnsentMessages(conversation);
 293					}
 294				}
 295				for (Conversation conversation : account.pendingConferenceLeaves) {
 296					leaveMuc(conversation);
 297				}
 298				account.pendingConferenceLeaves.clear();
 299				for (Conversation conversation : account.pendingConferenceJoins) {
 300					joinMuc(conversation);
 301				}
 302				account.pendingConferenceJoins.clear();
 303				scheduleWakeUpCall(Config.PING_MAX_INTERVAL, account.getUuid().hashCode());
 304			} else if (account.getStatus() == Account.State.OFFLINE) {
 305				resetSendingToWaiting(account);
 306				if (!account.isOptionSet(Account.OPTION_DISABLED)) {
 307					int timeToReconnect = mRandom.nextInt(20) + 10;
 308					scheduleWakeUpCall(timeToReconnect, account.getUuid().hashCode());
 309				}
 310			} else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
 311				databaseBackend.updateAccount(account);
 312				reconnectAccount(account, true, false);
 313			} else if ((account.getStatus() != Account.State.CONNECTING)
 314					&& (account.getStatus() != Account.State.NO_INTERNET)) {
 315				if (connection != null) {
 316					int next = connection.getTimeToNextAttempt();
 317					Log.d(Config.LOGTAG, account.getJid().toBareJid()
 318							+ ": error connecting account. try again in "
 319							+ next + "s for the "
 320							+ (connection.getAttempt() + 1) + " time");
 321					scheduleWakeUpCall(next, account.getUuid().hashCode());
 322				}
 323			}
 324			getNotificationService().updateErrorNotification();
 325		}
 326	};
 327	private OpenPgpServiceConnection pgpServiceConnection;
 328	private PgpEngine mPgpEngine = null;
 329	private WakeLock wakeLock;
 330	private PowerManager pm;
 331	private LruCache<String, Bitmap> mBitmapCache;
 332	private Thread mPhoneContactMergerThread;
 333	private EventReceiver mEventReceiver = new EventReceiver();
 334
 335	private boolean mRestoredFromDatabase = false;
 336
 337	private static String generateFetchKey(Account account, final Avatar avatar) {
 338		return account.getJid().toBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum;
 339	}
 340
 341	public boolean areMessagesInitialized() {
 342		return this.mRestoredFromDatabase;
 343	}
 344
 345	public PgpEngine getPgpEngine() {
 346		if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
 347			if (this.mPgpEngine == null) {
 348				this.mPgpEngine = new PgpEngine(new OpenPgpApi(
 349						getApplicationContext(),
 350						pgpServiceConnection.getService()), this);
 351			}
 352			return mPgpEngine;
 353		} else {
 354			return null;
 355		}
 356
 357	}
 358
 359	public FileBackend getFileBackend() {
 360		return this.fileBackend;
 361	}
 362
 363	public AvatarService getAvatarService() {
 364		return this.mAvatarService;
 365	}
 366
 367	public void attachLocationToConversation(final Conversation conversation,
 368											 final Uri uri,
 369											 final UiCallback<Message> callback) {
 370		int encryption = conversation.getNextEncryption();
 371		if (encryption == Message.ENCRYPTION_PGP) {
 372			encryption = Message.ENCRYPTION_DECRYPTED;
 373		}
 374		Message message = new Message(conversation, uri.toString(), encryption);
 375		if (conversation.getNextCounterpart() != null) {
 376			message.setCounterpart(conversation.getNextCounterpart());
 377		}
 378		if (encryption == Message.ENCRYPTION_DECRYPTED) {
 379			getPgpEngine().encrypt(message, callback);
 380		} else {
 381			callback.success(message);
 382		}
 383	}
 384
 385	public void attachFileToConversation(final Conversation conversation,
 386										 final Uri uri,
 387										 final UiCallback<Message> callback) {
 388		final Message message;
 389		if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 390			message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
 391		} else {
 392			message = new Message(conversation, "", conversation.getNextEncryption());
 393		}
 394		message.setCounterpart(conversation.getNextCounterpart());
 395		message.setType(Message.TYPE_FILE);
 396		String path = getFileBackend().getOriginalPath(uri);
 397		if (path != null) {
 398			message.setRelativeFilePath(path);
 399			getFileBackend().updateFileParams(message);
 400			if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 401				getPgpEngine().encrypt(message, callback);
 402			} else {
 403				callback.success(message);
 404			}
 405		} else {
 406			mFileAddingExecutor.execute(new Runnable() {
 407				@Override
 408				public void run() {
 409					try {
 410						getFileBackend().copyFileToPrivateStorage(message, uri);
 411						getFileBackend().updateFileParams(message);
 412						if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 413							getPgpEngine().encrypt(message, callback);
 414						} else {
 415							callback.success(message);
 416						}
 417					} catch (FileBackend.FileCopyException e) {
 418						callback.error(e.getResId(), message);
 419					}
 420				}
 421			});
 422		}
 423	}
 424
 425	public void attachImageToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
 426		final String compressPictures = getCompressPicturesPreference();
 427		if ("never".equals(compressPictures)
 428				|| ("auto".equals(compressPictures) && getFileBackend().useImageAsIs(uri))) {
 429			Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+ ": not compressing picture. sending as file");
 430			attachFileToConversation(conversation, uri, callback);
 431			return;
 432		}
 433		final Message message;
 434		if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 435			message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
 436		} else {
 437			message = new Message(conversation, "", conversation.getNextEncryption());
 438		}
 439		message.setCounterpart(conversation.getNextCounterpart());
 440		message.setType(Message.TYPE_IMAGE);
 441		mFileAddingExecutor.execute(new Runnable() {
 442
 443			@Override
 444			public void run() {
 445				try {
 446					getFileBackend().copyImageToPrivateStorage(message, uri);
 447					if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
 448						getPgpEngine().encrypt(message, callback);
 449					} else {
 450						callback.success(message);
 451					}
 452				} catch (final FileBackend.FileCopyException e) {
 453					callback.error(e.getResId(), message);
 454				}
 455			}
 456		});
 457	}
 458
 459	public Conversation find(Bookmark bookmark) {
 460		return find(bookmark.getAccount(), bookmark.getJid());
 461	}
 462
 463	public Conversation find(final Account account, final Jid jid) {
 464		return find(getConversations(), account, jid);
 465	}
 466
 467	@Override
 468	public int onStartCommand(Intent intent, int flags, int startId) {
 469		final String action = intent == null ? null : intent.getAction();
 470		boolean interactive = false;
 471		if (action != null) {
 472			switch (action) {
 473				case ConnectivityManager.CONNECTIVITY_ACTION:
 474					if (hasInternetConnection() && Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
 475						resetAllAttemptCounts(true);
 476					}
 477					break;
 478				case ACTION_MERGE_PHONE_CONTACTS:
 479					if (mRestoredFromDatabase) {
 480						loadPhoneContacts();
 481					}
 482					return START_STICKY;
 483				case Intent.ACTION_SHUTDOWN:
 484					logoutAndSave();
 485					return START_NOT_STICKY;
 486				case ACTION_CLEAR_NOTIFICATION:
 487					mNotificationService.clear();
 488					break;
 489				case ACTION_DISABLE_FOREGROUND:
 490					getPreferences().edit().putBoolean("keep_foreground_service", false).commit();
 491					toggleForegroundService();
 492					break;
 493				case ACTION_TRY_AGAIN:
 494					resetAllAttemptCounts(false);
 495					interactive = true;
 496					break;
 497				case ACTION_DISABLE_ACCOUNT:
 498					try {
 499						String jid = intent.getStringExtra("account");
 500						Account account = jid == null ? null : findAccountByJid(Jid.fromString(jid));
 501						if (account != null) {
 502							account.setOption(Account.OPTION_DISABLED, true);
 503							updateAccount(account);
 504						}
 505					} catch (final InvalidJidException ignored) {
 506						break;
 507					}
 508					break;
 509				case AudioManager.RINGER_MODE_CHANGED_ACTION:
 510					if (xaOnSilentMode()) {
 511						refreshAllPresences();
 512					}
 513					break;
 514				case Intent.ACTION_SCREEN_OFF:
 515				case Intent.ACTION_SCREEN_ON:
 516					if (awayWhenScreenOff()) {
 517						refreshAllPresences();
 518					}
 519					break;
 520				case ACTION_GCM_TOKEN_REFRESH:
 521					refreshAllGcmTokens();
 522					break;
 523				case ACTION_GCM_MESSAGE_RECEIVED:
 524					Log.d(Config.LOGTAG,"gcm push message arrived in service. extras="+intent.getExtras());
 525			}
 526		}
 527		this.wakeLock.acquire();
 528
 529		for (Account account : accounts) {
 530			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
 531				if (!hasInternetConnection()) {
 532					account.setStatus(Account.State.NO_INTERNET);
 533					if (statusListener != null) {
 534						statusListener.onStatusChanged(account);
 535					}
 536				} else {
 537					if (account.getStatus() == Account.State.NO_INTERNET) {
 538						account.setStatus(Account.State.OFFLINE);
 539						if (statusListener != null) {
 540							statusListener.onStatusChanged(account);
 541						}
 542					}
 543					if (account.getStatus() == Account.State.ONLINE) {
 544						long lastReceived = account.getXmppConnection().getLastPacketReceived();
 545						long lastSent = account.getXmppConnection().getLastPingSent();
 546						long pingInterval = "ui".equals(action) ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
 547						long msToNextPing = (Math.max(lastReceived, lastSent) + pingInterval) - SystemClock.elapsedRealtime();
 548						long pingTimeoutIn = (lastSent + Config.PING_TIMEOUT * 1000) - SystemClock.elapsedRealtime();
 549						if (lastSent > lastReceived) {
 550							if (pingTimeoutIn < 0) {
 551								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": ping timeout");
 552								this.reconnectAccount(account, true, interactive);
 553							} else {
 554								int secs = (int) (pingTimeoutIn / 1000);
 555								this.scheduleWakeUpCall(secs, account.getUuid().hashCode());
 556							}
 557						} else if (msToNextPing <= 0) {
 558							account.getXmppConnection().sendPing();
 559							Log.d(Config.LOGTAG, account.getJid().toBareJid() + " send ping");
 560							this.scheduleWakeUpCall(Config.PING_TIMEOUT, account.getUuid().hashCode());
 561						} else {
 562							this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
 563						}
 564					} else if (account.getStatus() == Account.State.OFFLINE) {
 565						reconnectAccount(account, true, interactive);
 566					} else if (account.getStatus() == Account.State.CONNECTING) {
 567						long secondsSinceLastConnect = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000;
 568						long secondsSinceLastDisco = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastDiscoStarted()) / 1000;
 569						long discoTimeout = Config.CONNECT_DISCO_TIMEOUT - secondsSinceLastDisco;
 570						long timeout = Config.CONNECT_TIMEOUT - secondsSinceLastConnect;
 571						if (timeout < 0) {
 572							Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting");
 573							reconnectAccount(account, true, interactive);
 574						} else if (discoTimeout < 0) {
 575							account.getXmppConnection().sendDiscoTimeout();
 576							scheduleWakeUpCall((int) Math.min(timeout,discoTimeout), account.getUuid().hashCode());
 577						} else {
 578							scheduleWakeUpCall((int) Math.min(timeout,discoTimeout), account.getUuid().hashCode());
 579						}
 580					} else {
 581						if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
 582							reconnectAccount(account, true, interactive);
 583						}
 584					}
 585				}
 586				if (mOnAccountUpdate != null) {
 587					mOnAccountUpdate.onAccountUpdate();
 588				}
 589			}
 590		}
 591		if (wakeLock.isHeld()) {
 592			try {
 593				wakeLock.release();
 594			} catch (final RuntimeException ignored) {
 595			}
 596		}
 597		return START_STICKY;
 598	}
 599
 600	private boolean xaOnSilentMode() {
 601		return getPreferences().getBoolean("xa_on_silent_mode", false);
 602	}
 603
 604	private boolean awayWhenScreenOff() {
 605		return getPreferences().getBoolean("away_when_screen_off", false);
 606	}
 607
 608	private String getCompressPicturesPreference() {
 609		return getPreferences().getString("picture_compression", "auto");
 610	}
 611
 612	private Presence.Status getTargetPresence() {
 613		if (xaOnSilentMode() && isPhoneSilenced()) {
 614			return Presence.Status.XA;
 615		} else if (awayWhenScreenOff() && !isInteractive()) {
 616			return Presence.Status.AWAY;
 617		} else {
 618			return Presence.Status.ONLINE;
 619		}
 620	}
 621
 622	@SuppressLint("NewApi")
 623	@SuppressWarnings("deprecation")
 624	public boolean isInteractive() {
 625		final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 626
 627		final boolean isScreenOn;
 628		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
 629			isScreenOn = pm.isScreenOn();
 630		} else {
 631			isScreenOn = pm.isInteractive();
 632		}
 633		return isScreenOn;
 634	}
 635
 636	private boolean isPhoneSilenced() {
 637		AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
 638		return audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT;
 639	}
 640
 641	private void resetAllAttemptCounts(boolean reallyAll) {
 642		Log.d(Config.LOGTAG, "resetting all attepmt counts");
 643		for (Account account : accounts) {
 644			if (account.hasErrorStatus() || reallyAll) {
 645				final XmppConnection connection = account.getXmppConnection();
 646				if (connection != null) {
 647					connection.resetAttemptCount();
 648				}
 649			}
 650		}
 651	}
 652
 653	public boolean hasInternetConnection() {
 654		ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
 655				.getSystemService(Context.CONNECTIVITY_SERVICE);
 656		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
 657		return activeNetwork != null && activeNetwork.isConnected();
 658	}
 659
 660	@SuppressLint("TrulyRandom")
 661	@Override
 662	public void onCreate() {
 663		ExceptionHelper.init(getApplicationContext());
 664		PRNGFixes.apply();
 665		this.mRandom = new SecureRandom();
 666		updateMemorizingTrustmanager();
 667		final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
 668		final int cacheSize = maxMemory / 8;
 669		this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
 670			@Override
 671			protected int sizeOf(final String key, final Bitmap bitmap) {
 672				return bitmap.getByteCount() / 1024;
 673			}
 674		};
 675
 676		this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
 677		this.accounts = databaseBackend.getAccounts();
 678
 679		restoreFromDatabase();
 680
 681		getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
 682		this.fileObserver.startWatching();
 683
 684		this.pgpServiceConnection = new OpenPgpServiceConnection(getApplicationContext(), "org.sufficientlysecure.keychain", new OpenPgpServiceConnection.OnBound() {
 685			@Override
 686			public void onBound(IOpenPgpService2 service) {
 687				for (Account account : accounts) {
 688					if (account.getPgpDecryptionService() != null) {
 689						account.getPgpDecryptionService().onOpenPgpServiceBound();
 690					}
 691				}
 692			}
 693
 694			@Override
 695			public void onError(Exception e) { }
 696		});
 697		this.pgpServiceConnection.bindToService();
 698
 699		this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 700		this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "XmppConnectionService");
 701		toggleForegroundService();
 702		updateUnreadCountBadge();
 703		toggleScreenEventReceiver();
 704	}
 705
 706	@Override
 707	public void onTrimMemory(int level) {
 708		super.onTrimMemory(level);
 709		if (level >= TRIM_MEMORY_COMPLETE) {
 710			Log.d(Config.LOGTAG, "clear cache due to low memory");
 711			getBitmapCache().evictAll();
 712		}
 713	}
 714
 715	@Override
 716	public void onDestroy() {
 717		try {
 718			unregisterReceiver(this.mEventReceiver);
 719		} catch (IllegalArgumentException e) {
 720			//ignored
 721		}
 722		super.onDestroy();
 723	}
 724
 725	public void toggleScreenEventReceiver() {
 726		if (awayWhenScreenOff()) {
 727			final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
 728			filter.addAction(Intent.ACTION_SCREEN_OFF);
 729			registerReceiver(this.mEventReceiver, filter);
 730		} else {
 731			try {
 732				unregisterReceiver(this.mEventReceiver);
 733			} catch (IllegalArgumentException e) {
 734				//ignored
 735			}
 736		}
 737	}
 738
 739	public void toggleForegroundService() {
 740		if (getPreferences().getBoolean("keep_foreground_service", false)) {
 741			startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
 742		} else {
 743			stopForeground(true);
 744		}
 745	}
 746
 747	@Override
 748	public void onTaskRemoved(final Intent rootIntent) {
 749		super.onTaskRemoved(rootIntent);
 750		if (!getPreferences().getBoolean("keep_foreground_service", false)) {
 751			this.logoutAndSave();
 752		}
 753	}
 754
 755	private void logoutAndSave() {
 756		for (final Account account : accounts) {
 757			databaseBackend.writeRoster(account.getRoster());
 758			if (account.getXmppConnection() != null) {
 759				new Thread(new Runnable() {
 760					@Override
 761					public void run() {
 762						disconnect(account, false);
 763					}
 764				}).start();
 765
 766			}
 767		}
 768		Context context = getApplicationContext();
 769		AlarmManager alarmManager = (AlarmManager) context
 770				.getSystemService(Context.ALARM_SERVICE);
 771		Intent intent = new Intent(context, EventReceiver.class);
 772		alarmManager.cancel(PendingIntent.getBroadcast(context, 0, intent, 0));
 773		Log.d(Config.LOGTAG, "good bye");
 774		stopSelf();
 775	}
 776
 777	public void scheduleWakeUpCall(int seconds, int requestCode) {
 778		final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
 779
 780		Context context = getApplicationContext();
 781		AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
 782
 783		Intent intent = new Intent(context, EventReceiver.class);
 784		intent.setAction("ping");
 785		PendingIntent alarmIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0);
 786		alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, alarmIntent);
 787	}
 788
 789	public XmppConnection createConnection(final Account account) {
 790		final SharedPreferences sharedPref = getPreferences();
 791		account.setResource(sharedPref.getString("resource", "mobile")
 792				.toLowerCase(Locale.getDefault()));
 793		final XmppConnection connection = new XmppConnection(account, this);
 794		connection.setOnMessagePacketReceivedListener(this.mMessageParser);
 795		connection.setOnStatusChangedListener(this.statusListener);
 796		connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
 797		connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
 798		connection.setOnJinglePacketReceivedListener(this.jingleListener);
 799		connection.setOnBindListener(this.mOnBindListener);
 800		connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
 801		connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
 802		AxolotlService axolotlService = account.getAxolotlService();
 803		if (axolotlService != null) {
 804			connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
 805		}
 806		return connection;
 807	}
 808
 809	public void sendChatState(Conversation conversation) {
 810		if (sendChatStates()) {
 811			MessagePacket packet = mMessageGenerator.generateChatState(conversation);
 812			sendMessagePacket(conversation.getAccount(), packet);
 813		}
 814	}
 815
 816	private void sendFileMessage(final Message message, final boolean delay) {
 817		Log.d(Config.LOGTAG, "send file message");
 818		final Account account = message.getConversation().getAccount();
 819		final XmppConnection connection = account.getXmppConnection();
 820		if (connection != null && connection.getFeatures().httpUpload()) {
 821			mHttpConnectionManager.createNewUploadConnection(message, delay);
 822		} else {
 823			mJingleConnectionManager.createNewConnection(message);
 824		}
 825	}
 826
 827	public void sendMessage(final Message message) {
 828		sendMessage(message, false, false);
 829	}
 830
 831	private void sendMessage(final Message message, final boolean resend, final boolean delay) {
 832		final Account account = message.getConversation().getAccount();
 833		final Conversation conversation = message.getConversation();
 834		account.deactivateGracePeriod();
 835		MessagePacket packet = null;
 836		final boolean addToConversation = conversation.getMode() != Conversation.MODE_MULTI
 837				|| account.getServerIdentity() != XmppConnection.Identity.SLACK;
 838		boolean saveInDb = addToConversation;
 839		message.setStatus(Message.STATUS_WAITING);
 840
 841		if (!resend && message.getEncryption() != Message.ENCRYPTION_OTR) {
 842			message.getConversation().endOtrIfNeeded();
 843			message.getConversation().findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR,
 844					new Conversation.OnMessageFound() {
 845						@Override
 846						public void onMessageFound(Message message) {
 847							markMessage(message, Message.STATUS_SEND_FAILED);
 848						}
 849					});
 850		}
 851
 852		if (account.isOnlineAndConnected()) {
 853			switch (message.getEncryption()) {
 854				case Message.ENCRYPTION_NONE:
 855					if (message.needsUploading()) {
 856						if (account.httpUploadAvailable() || message.fixCounterpart()) {
 857							this.sendFileMessage(message, delay);
 858						} else {
 859							break;
 860						}
 861					} else {
 862						packet = mMessageGenerator.generateChat(message);
 863					}
 864					break;
 865				case Message.ENCRYPTION_PGP:
 866				case Message.ENCRYPTION_DECRYPTED:
 867					if (message.needsUploading()) {
 868						if (account.httpUploadAvailable() || message.fixCounterpart()) {
 869							this.sendFileMessage(message, delay);
 870						} else {
 871							break;
 872						}
 873					} else {
 874						packet = mMessageGenerator.generatePgpChat(message);
 875					}
 876					break;
 877				case Message.ENCRYPTION_OTR:
 878					SessionImpl otrSession = conversation.getOtrSession();
 879					if (otrSession != null && otrSession.getSessionStatus() == SessionStatus.ENCRYPTED) {
 880						try {
 881							message.setCounterpart(Jid.fromSessionID(otrSession.getSessionID()));
 882						} catch (InvalidJidException e) {
 883							break;
 884						}
 885						if (message.needsUploading()) {
 886							mJingleConnectionManager.createNewConnection(message);
 887						} else {
 888							packet = mMessageGenerator.generateOtrChat(message);
 889						}
 890					} else if (otrSession == null) {
 891						if (message.fixCounterpart()) {
 892							conversation.startOtrSession(message.getCounterpart().getResourcepart(), true);
 893						} else {
 894							break;
 895						}
 896					}
 897					break;
 898				case Message.ENCRYPTION_AXOLOTL:
 899					message.setAxolotlFingerprint(account.getAxolotlService().getOwnFingerprint());
 900					if (message.needsUploading()) {
 901						if (account.httpUploadAvailable() || message.fixCounterpart()) {
 902							this.sendFileMessage(message, delay);
 903						} else {
 904							break;
 905						}
 906					} else {
 907						XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
 908						if (axolotlMessage == null) {
 909							account.getAxolotlService().preparePayloadMessage(message, delay);
 910						} else {
 911							packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
 912						}
 913					}
 914					break;
 915
 916			}
 917			if (packet != null) {
 918				if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
 919					message.setStatus(Message.STATUS_UNSEND);
 920				} else {
 921					message.setStatus(Message.STATUS_SEND);
 922				}
 923			}
 924		} else {
 925			switch (message.getEncryption()) {
 926				case Message.ENCRYPTION_DECRYPTED:
 927					if (!message.needsUploading()) {
 928						String pgpBody = message.getEncryptedBody();
 929						String decryptedBody = message.getBody();
 930						message.setBody(pgpBody);
 931						message.setEncryption(Message.ENCRYPTION_PGP);
 932						databaseBackend.createMessage(message);
 933						saveInDb = false;
 934						message.setBody(decryptedBody);
 935						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 936					}
 937					break;
 938				case Message.ENCRYPTION_OTR:
 939					if (!conversation.hasValidOtrSession() && message.getCounterpart() != null) {
 940						conversation.startOtrSession(message.getCounterpart().getResourcepart(), false);
 941					}
 942					break;
 943				case Message.ENCRYPTION_AXOLOTL:
 944					message.setAxolotlFingerprint(account.getAxolotlService().getOwnFingerprint());
 945					break;
 946			}
 947		}
 948
 949		if (resend) {
 950			if (packet != null && addToConversation) {
 951				if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
 952					markMessage(message, Message.STATUS_UNSEND);
 953				} else {
 954					markMessage(message, Message.STATUS_SEND);
 955				}
 956			}
 957		} else {
 958			if (addToConversation) {
 959				conversation.add(message);
 960			}
 961			if (saveInDb && (message.getEncryption() == Message.ENCRYPTION_NONE || saveEncryptedMessages())) {
 962				databaseBackend.createMessage(message);
 963			}
 964			updateConversationUi();
 965		}
 966		if (packet != null) {
 967			if (delay) {
 968				mMessageGenerator.addDelay(packet, message.getTimeSent());
 969			}
 970			if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
 971				if (this.sendChatStates()) {
 972					packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
 973				}
 974			}
 975			sendMessagePacket(account, packet);
 976		}
 977	}
 978
 979	private void sendUnsentMessages(final Conversation conversation) {
 980		conversation.findWaitingMessages(new Conversation.OnMessageFound() {
 981
 982			@Override
 983			public void onMessageFound(Message message) {
 984				resendMessage(message, true);
 985			}
 986		});
 987	}
 988
 989	public void resendMessage(final Message message, final boolean delay) {
 990		sendMessage(message, true, delay);
 991	}
 992
 993	public void fetchRosterFromServer(final Account account) {
 994		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
 995		if (!"".equals(account.getRosterVersion())) {
 996			Log.d(Config.LOGTAG, account.getJid().toBareJid()
 997					+ ": fetching roster version " + account.getRosterVersion());
 998		} else {
 999			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
1000		}
1001		iqPacket.query(Xmlns.ROSTER).setAttribute("ver", account.getRosterVersion());
1002		sendIqPacket(account, iqPacket, mIqParser);
1003	}
1004
1005	public void fetchBookmarks(final Account account) {
1006		final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1007		final Element query = iqPacket.query("jabber:iq:private");
1008		query.addChild("storage", "storage:bookmarks");
1009		final OnIqPacketReceived callback = new OnIqPacketReceived() {
1010
1011			@Override
1012			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1013				if (packet.getType() == IqPacket.TYPE.RESULT) {
1014					final Element query = packet.query();
1015					final HashMap<Jid, Bookmark> bookmarks = new HashMap<>();
1016					final Element storage = query.findChild("storage", "storage:bookmarks");
1017					final boolean autojoin = respectAutojoin();
1018					if (storage != null) {
1019						for (final Element item : storage.getChildren()) {
1020							if (item.getName().equals("conference")) {
1021								final Bookmark bookmark = Bookmark.parse(item, account);
1022								Bookmark old = bookmarks.put(bookmark.getJid(), bookmark);
1023								if (old != null && old.getBookmarkName() != null && bookmark.getBookmarkName() == null) {
1024									bookmark.setBookmarkName(old.getBookmarkName());
1025								}
1026								Conversation conversation = find(bookmark);
1027								if (conversation != null) {
1028									conversation.setBookmark(bookmark);
1029								} else if (bookmark.autojoin() && bookmark.getJid() != null && autojoin) {
1030									conversation = findOrCreateConversation(
1031											account, bookmark.getJid(), true);
1032									conversation.setBookmark(bookmark);
1033									joinMuc(conversation);
1034								}
1035							}
1036						}
1037					}
1038					account.setBookmarks(new ArrayList<>(bookmarks.values()));
1039				} else {
1040					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not fetch bookmarks");
1041				}
1042			}
1043		};
1044		sendIqPacket(account, iqPacket, callback);
1045	}
1046
1047	public void pushBookmarks(Account account) {
1048		Log.d(Config.LOGTAG, account.getJid().toBareJid()+": pushing bookmarks");
1049		IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1050		Element query = iqPacket.query("jabber:iq:private");
1051		Element storage = query.addChild("storage", "storage:bookmarks");
1052		for (Bookmark bookmark : account.getBookmarks()) {
1053			storage.addChild(bookmark);
1054		}
1055		sendIqPacket(account, iqPacket, mDefaultIqHandler);
1056	}
1057
1058	public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
1059		if (mPhoneContactMergerThread != null) {
1060			mPhoneContactMergerThread.interrupt();
1061		}
1062		mPhoneContactMergerThread = new Thread(new Runnable() {
1063			@Override
1064			public void run() {
1065				Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1066				for (Account account : accounts) {
1067					List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
1068					for (Bundle phoneContact : phoneContacts) {
1069						if (Thread.interrupted()) {
1070							Log.d(Config.LOGTAG, "interrupted merging phone contacts");
1071							return;
1072						}
1073						Jid jid;
1074						try {
1075							jid = Jid.fromString(phoneContact.getString("jid"));
1076						} catch (final InvalidJidException e) {
1077							continue;
1078						}
1079						final Contact contact = account.getRoster().getContact(jid);
1080						String systemAccount = phoneContact.getInt("phoneid")
1081								+ "#"
1082								+ phoneContact.getString("lookup");
1083						contact.setSystemAccount(systemAccount);
1084						if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
1085							getAvatarService().clear(contact);
1086						}
1087						contact.setSystemName(phoneContact.getString("displayname"));
1088						withSystemAccounts.remove(contact);
1089					}
1090					for (Contact contact : withSystemAccounts) {
1091						contact.setSystemAccount(null);
1092						contact.setSystemName(null);
1093						if (contact.setPhotoUri(null)) {
1094							getAvatarService().clear(contact);
1095						}
1096					}
1097				}
1098				Log.d(Config.LOGTAG, "finished merging phone contacts");
1099				updateAccountUi();
1100			}
1101		});
1102		mPhoneContactMergerThread.start();
1103	}
1104
1105	private void restoreFromDatabase() {
1106		synchronized (this.conversations) {
1107			final Map<String, Account> accountLookupTable = new Hashtable<>();
1108			for (Account account : this.accounts) {
1109				accountLookupTable.put(account.getUuid(), account);
1110			}
1111			this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1112			for (Conversation conversation : this.conversations) {
1113				Account account = accountLookupTable.get(conversation.getAccountUuid());
1114				conversation.setAccount(account);
1115			}
1116			Runnable runnable = new Runnable() {
1117				@Override
1118				public void run() {
1119					Log.d(Config.LOGTAG, "restoring roster");
1120					for (Account account : accounts) {
1121						databaseBackend.readRoster(account.getRoster());
1122						account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1123					}
1124					getBitmapCache().evictAll();
1125					Looper.prepare();
1126					loadPhoneContacts();
1127					Log.d(Config.LOGTAG, "restoring messages");
1128					for (Conversation conversation : conversations) {
1129						conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1130						checkDeletedFiles(conversation);
1131						conversation.findUnreadMessages(new Conversation.OnMessageFound() {
1132							@Override
1133							public void onMessageFound(Message message) {
1134								mNotificationService.pushFromBacklog(message);
1135							}
1136						});
1137					}
1138					mNotificationService.finishBacklog(false);
1139					mRestoredFromDatabase = true;
1140					Log.d(Config.LOGTAG, "restored all messages");
1141					updateConversationUi();
1142				}
1143			};
1144			mDatabaseExecutor.execute(runnable);
1145		}
1146	}
1147
1148	public void loadPhoneContacts() {
1149		PhoneHelper.loadPhoneContacts(getApplicationContext(),
1150				new CopyOnWriteArrayList<Bundle>(),
1151				XmppConnectionService.this);
1152	}
1153
1154	public List<Conversation> getConversations() {
1155		return this.conversations;
1156	}
1157
1158	private void checkDeletedFiles(Conversation conversation) {
1159		conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1160
1161			@Override
1162			public void onMessageFound(Message message) {
1163				if (!getFileBackend().isFileAvailable(message)) {
1164					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1165					final int s = message.getStatus();
1166					if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1167						markMessage(message, Message.STATUS_SEND_FAILED);
1168					}
1169				}
1170			}
1171		});
1172	}
1173
1174	private void markFileDeleted(String uuid) {
1175		for (Conversation conversation : getConversations()) {
1176			Message message = conversation.findMessageWithFileAndUuid(uuid);
1177			if (message != null) {
1178				if (!getFileBackend().isFileAvailable(message)) {
1179					message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1180					final int s = message.getStatus();
1181					if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1182						markMessage(message, Message.STATUS_SEND_FAILED);
1183					} else {
1184						updateConversationUi();
1185					}
1186				}
1187				return;
1188			}
1189		}
1190	}
1191
1192	public void populateWithOrderedConversations(final List<Conversation> list) {
1193		populateWithOrderedConversations(list, true);
1194	}
1195
1196	public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1197		list.clear();
1198		if (includeNoFileUpload) {
1199			list.addAll(getConversations());
1200		} else {
1201			for (Conversation conversation : getConversations()) {
1202				if (conversation.getMode() == Conversation.MODE_SINGLE
1203						|| conversation.getAccount().httpUploadAvailable()) {
1204					list.add(conversation);
1205				}
1206			}
1207		}
1208		Collections.sort(list, new Comparator<Conversation>() {
1209			@Override
1210			public int compare(Conversation lhs, Conversation rhs) {
1211				Message left = lhs.getLatestMessage();
1212				Message right = rhs.getLatestMessage();
1213				if (left.getTimeSent() > right.getTimeSent()) {
1214					return -1;
1215				} else if (left.getTimeSent() < right.getTimeSent()) {
1216					return 1;
1217				} else {
1218					return 0;
1219				}
1220			}
1221		});
1222	}
1223
1224	public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1225		if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
1226			return;
1227		} else if (timestamp == 0) {
1228			return;
1229		}
1230		Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1231		Runnable runnable = new Runnable() {
1232			@Override
1233			public void run() {
1234				final Account account = conversation.getAccount();
1235				List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
1236				if (messages.size() > 0) {
1237					conversation.addAll(0, messages);
1238					checkDeletedFiles(conversation);
1239					callback.onMoreMessagesLoaded(messages.size(), conversation);
1240				} else if (conversation.hasMessagesLeftOnServer()
1241						&& account.isOnlineAndConnected()
1242						&& conversation.getLastClearHistory() == 0) {
1243					if ((conversation.getMode() == Conversation.MODE_SINGLE && account.getXmppConnection().getFeatures().mam())
1244							|| (conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().mamSupport())) {
1245						MessageArchiveService.Query query = getMessageArchiveService().query(conversation, 0, timestamp);
1246						if (query != null) {
1247							query.setCallback(callback);
1248						}
1249						callback.informUser(R.string.fetching_history_from_server);
1250					}
1251				}
1252			}
1253		};
1254		mDatabaseExecutor.execute(runnable);
1255	}
1256
1257	public List<Account> getAccounts() {
1258		return this.accounts;
1259	}
1260
1261	public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1262		for (final Conversation conversation : haystack) {
1263			if (conversation.getContact() == contact) {
1264				return conversation;
1265			}
1266		}
1267		return null;
1268	}
1269
1270	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1271		if (jid == null) {
1272			return null;
1273		}
1274		for (final Conversation conversation : haystack) {
1275			if ((account == null || conversation.getAccount() == account)
1276					&& (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1277				return conversation;
1278			}
1279		}
1280		return null;
1281	}
1282
1283	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1284		return this.findOrCreateConversation(account, jid, muc, null);
1285	}
1286
1287	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1288		synchronized (this.conversations) {
1289			Conversation conversation = find(account, jid);
1290			if (conversation != null) {
1291				return conversation;
1292			}
1293			conversation = databaseBackend.findConversation(account, jid);
1294			if (conversation != null) {
1295				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1296				conversation.setAccount(account);
1297				if (muc) {
1298					conversation.setMode(Conversation.MODE_MULTI);
1299					conversation.setContactJid(jid);
1300				} else {
1301					conversation.setMode(Conversation.MODE_SINGLE);
1302					conversation.setContactJid(jid.toBareJid());
1303				}
1304				conversation.setNextEncryption(-1);
1305				conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1306				this.databaseBackend.updateConversation(conversation);
1307			} else {
1308				String conversationName;
1309				Contact contact = account.getRoster().getContact(jid);
1310				if (contact != null) {
1311					conversationName = contact.getDisplayName();
1312				} else {
1313					conversationName = jid.getLocalpart();
1314				}
1315				if (muc) {
1316					conversation = new Conversation(conversationName, account, jid,
1317							Conversation.MODE_MULTI);
1318				} else {
1319					conversation = new Conversation(conversationName, account, jid.toBareJid(),
1320							Conversation.MODE_SINGLE);
1321				}
1322				this.databaseBackend.createConversation(conversation);
1323			}
1324			if (account.getXmppConnection() != null
1325					&& account.getXmppConnection().getFeatures().mam()
1326					&& !muc) {
1327				if (query == null) {
1328					this.mMessageArchiveService.query(conversation);
1329				} else {
1330					if (query.getConversation() == null) {
1331						this.mMessageArchiveService.query(conversation, query.getStart());
1332					}
1333				}
1334			}
1335			checkDeletedFiles(conversation);
1336			this.conversations.add(conversation);
1337			updateConversationUi();
1338			return conversation;
1339		}
1340	}
1341
1342	public void archiveConversation(Conversation conversation) {
1343		getNotificationService().clear(conversation);
1344		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1345		conversation.setNextEncryption(-1);
1346		synchronized (this.conversations) {
1347			if (conversation.getMode() == Conversation.MODE_MULTI) {
1348				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1349					Bookmark bookmark = conversation.getBookmark();
1350					if (bookmark != null && bookmark.autojoin() && respectAutojoin()) {
1351						bookmark.setAutojoin(false);
1352						pushBookmarks(bookmark.getAccount());
1353					}
1354				}
1355				leaveMuc(conversation);
1356			} else {
1357				conversation.endOtrIfNeeded();
1358				if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1359					Log.d(Config.LOGTAG, "Canceling presence request from " + conversation.getJid().toString());
1360					sendPresencePacket(
1361							conversation.getAccount(),
1362							mPresenceGenerator.stopPresenceUpdatesTo(conversation.getContact())
1363					);
1364				}
1365			}
1366			this.databaseBackend.updateConversation(conversation);
1367			this.conversations.remove(conversation);
1368			updateConversationUi();
1369		}
1370	}
1371
1372	public void createAccount(final Account account) {
1373		account.initAccountServices(this);
1374		databaseBackend.createAccount(account);
1375		this.accounts.add(account);
1376		this.reconnectAccountInBackground(account);
1377		updateAccountUi();
1378	}
1379
1380	public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1381		new Thread(new Runnable() {
1382			@Override
1383			public void run() {
1384				try {
1385					X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1386					Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1387					if (findAccountByJid(info.first) == null) {
1388						Account account = new Account(info.first, "");
1389						account.setPrivateKeyAlias(alias);
1390						account.setOption(Account.OPTION_DISABLED, true);
1391						account.setDisplayName(info.second);
1392						createAccount(account);
1393						callback.onAccountCreated(account);
1394						if (Config.X509_VERIFICATION) {
1395							try {
1396								getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1397							} catch (CertificateException e) {
1398								callback.informUser(R.string.certificate_chain_is_not_trusted);
1399							}
1400						}
1401					} else {
1402						callback.informUser(R.string.account_already_exists);
1403					}
1404				} catch (Exception e) {
1405					e.printStackTrace();
1406					callback.informUser(R.string.unable_to_parse_certificate);
1407				}
1408			}
1409		}).start();
1410
1411	}
1412
1413	public void updateKeyInAccount(final Account account, final String alias) {
1414		Log.d(Config.LOGTAG, "update key in account " + alias);
1415		try {
1416			X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1417			Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1418			if (account.getJid().toBareJid().equals(info.first)) {
1419				account.setPrivateKeyAlias(alias);
1420				account.setDisplayName(info.second);
1421				databaseBackend.updateAccount(account);
1422				if (Config.X509_VERIFICATION) {
1423					try {
1424						getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1425					} catch (CertificateException e) {
1426						showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1427					}
1428					account.getAxolotlService().regenerateKeys(true);
1429				}
1430			} else {
1431				showErrorToastInUi(R.string.jid_does_not_match_certificate);
1432			}
1433		} catch (Exception e) {
1434			e.printStackTrace();
1435		}
1436	}
1437
1438	public void updateAccount(final Account account) {
1439		this.statusListener.onStatusChanged(account);
1440		databaseBackend.updateAccount(account);
1441		reconnectAccountInBackground(account);
1442		updateAccountUi();
1443		getNotificationService().updateErrorNotification();
1444	}
1445
1446	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1447		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1448		sendIqPacket(account, iq, new OnIqPacketReceived() {
1449			@Override
1450			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1451				if (packet.getType() == IqPacket.TYPE.RESULT) {
1452					account.setPassword(newPassword);
1453					databaseBackend.updateAccount(account);
1454					callback.onPasswordChangeSucceeded();
1455				} else {
1456					callback.onPasswordChangeFailed();
1457				}
1458			}
1459		});
1460	}
1461
1462	public void deleteAccount(final Account account) {
1463		synchronized (this.conversations) {
1464			for (final Conversation conversation : conversations) {
1465				if (conversation.getAccount() == account) {
1466					if (conversation.getMode() == Conversation.MODE_MULTI) {
1467						leaveMuc(conversation);
1468					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1469						conversation.endOtrIfNeeded();
1470					}
1471					conversations.remove(conversation);
1472				}
1473			}
1474			if (account.getXmppConnection() != null) {
1475				this.disconnect(account, true);
1476			}
1477			Runnable runnable = new Runnable() {
1478				@Override
1479				public void run() {
1480					databaseBackend.deleteAccount(account);
1481				}
1482			};
1483			mDatabaseExecutor.execute(runnable);
1484			this.accounts.remove(account);
1485			updateAccountUi();
1486			getNotificationService().updateErrorNotification();
1487		}
1488	}
1489
1490	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1491		synchronized (this) {
1492			if (checkListeners()) {
1493				switchToForeground();
1494			}
1495			this.mOnConversationUpdate = listener;
1496			this.mNotificationService.setIsInForeground(true);
1497			if (this.convChangedListenerCount < 2) {
1498				this.convChangedListenerCount++;
1499			}
1500		}
1501	}
1502
1503	public void removeOnConversationListChangedListener() {
1504		synchronized (this) {
1505			this.convChangedListenerCount--;
1506			if (this.convChangedListenerCount <= 0) {
1507				this.convChangedListenerCount = 0;
1508				this.mOnConversationUpdate = null;
1509				this.mNotificationService.setIsInForeground(false);
1510				if (checkListeners()) {
1511					switchToBackground();
1512				}
1513			}
1514		}
1515	}
1516
1517	public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1518		synchronized (this) {
1519			if (checkListeners()) {
1520				switchToForeground();
1521			}
1522			this.mOnShowErrorToast = onShowErrorToast;
1523			if (this.showErrorToastListenerCount < 2) {
1524				this.showErrorToastListenerCount++;
1525			}
1526		}
1527		this.mOnShowErrorToast = onShowErrorToast;
1528	}
1529
1530	public void removeOnShowErrorToastListener() {
1531		synchronized (this) {
1532			this.showErrorToastListenerCount--;
1533			if (this.showErrorToastListenerCount <= 0) {
1534				this.showErrorToastListenerCount = 0;
1535				this.mOnShowErrorToast = null;
1536				if (checkListeners()) {
1537					switchToBackground();
1538				}
1539			}
1540		}
1541	}
1542
1543	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1544		synchronized (this) {
1545			if (checkListeners()) {
1546				switchToForeground();
1547			}
1548			this.mOnAccountUpdate = listener;
1549			if (this.accountChangedListenerCount < 2) {
1550				this.accountChangedListenerCount++;
1551			}
1552		}
1553	}
1554
1555	public void removeOnAccountListChangedListener() {
1556		synchronized (this) {
1557			this.accountChangedListenerCount--;
1558			if (this.accountChangedListenerCount <= 0) {
1559				this.mOnAccountUpdate = null;
1560				this.accountChangedListenerCount = 0;
1561				if (checkListeners()) {
1562					switchToBackground();
1563				}
1564			}
1565		}
1566	}
1567
1568	public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
1569		synchronized (this) {
1570			if (checkListeners()) {
1571				switchToForeground();
1572			}
1573			this.mOnCaptchaRequested = listener;
1574			if (this.captchaRequestedListenerCount < 2) {
1575				this.captchaRequestedListenerCount++;
1576			}
1577		}
1578	}
1579
1580	public void removeOnCaptchaRequestedListener() {
1581		synchronized (this) {
1582			this.captchaRequestedListenerCount--;
1583			if (this.captchaRequestedListenerCount <= 0) {
1584				this.mOnCaptchaRequested = null;
1585				this.captchaRequestedListenerCount = 0;
1586				if (checkListeners()) {
1587					switchToBackground();
1588				}
1589			}
1590		}
1591	}
1592
1593	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1594		synchronized (this) {
1595			if (checkListeners()) {
1596				switchToForeground();
1597			}
1598			this.mOnRosterUpdate = listener;
1599			if (this.rosterChangedListenerCount < 2) {
1600				this.rosterChangedListenerCount++;
1601			}
1602		}
1603	}
1604
1605	public void removeOnRosterUpdateListener() {
1606		synchronized (this) {
1607			this.rosterChangedListenerCount--;
1608			if (this.rosterChangedListenerCount <= 0) {
1609				this.rosterChangedListenerCount = 0;
1610				this.mOnRosterUpdate = null;
1611				if (checkListeners()) {
1612					switchToBackground();
1613				}
1614			}
1615		}
1616	}
1617
1618	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1619		synchronized (this) {
1620			if (checkListeners()) {
1621				switchToForeground();
1622			}
1623			this.mOnUpdateBlocklist = listener;
1624			if (this.updateBlocklistListenerCount < 2) {
1625				this.updateBlocklistListenerCount++;
1626			}
1627		}
1628	}
1629
1630	public void removeOnUpdateBlocklistListener() {
1631		synchronized (this) {
1632			this.updateBlocklistListenerCount--;
1633			if (this.updateBlocklistListenerCount <= 0) {
1634				this.updateBlocklistListenerCount = 0;
1635				this.mOnUpdateBlocklist = null;
1636				if (checkListeners()) {
1637					switchToBackground();
1638				}
1639			}
1640		}
1641	}
1642
1643	public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
1644		synchronized (this) {
1645			if (checkListeners()) {
1646				switchToForeground();
1647			}
1648			this.mOnKeyStatusUpdated = listener;
1649			if (this.keyStatusUpdatedListenerCount < 2) {
1650				this.keyStatusUpdatedListenerCount++;
1651			}
1652		}
1653	}
1654
1655	public void removeOnNewKeysAvailableListener() {
1656		synchronized (this) {
1657			this.keyStatusUpdatedListenerCount--;
1658			if (this.keyStatusUpdatedListenerCount <= 0) {
1659				this.keyStatusUpdatedListenerCount = 0;
1660				this.mOnKeyStatusUpdated = null;
1661				if (checkListeners()) {
1662					switchToBackground();
1663				}
1664			}
1665		}
1666	}
1667
1668	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1669		synchronized (this) {
1670			if (checkListeners()) {
1671				switchToForeground();
1672			}
1673			this.mOnMucRosterUpdate = listener;
1674			if (this.mucRosterChangedListenerCount < 2) {
1675				this.mucRosterChangedListenerCount++;
1676			}
1677		}
1678	}
1679
1680	public void removeOnMucRosterUpdateListener() {
1681		synchronized (this) {
1682			this.mucRosterChangedListenerCount--;
1683			if (this.mucRosterChangedListenerCount <= 0) {
1684				this.mucRosterChangedListenerCount = 0;
1685				this.mOnMucRosterUpdate = null;
1686				if (checkListeners()) {
1687					switchToBackground();
1688				}
1689			}
1690		}
1691	}
1692
1693	private boolean checkListeners() {
1694		return (this.mOnAccountUpdate == null
1695				&& this.mOnConversationUpdate == null
1696				&& this.mOnRosterUpdate == null
1697				&& this.mOnCaptchaRequested == null
1698				&& this.mOnUpdateBlocklist == null
1699				&& this.mOnShowErrorToast == null
1700				&& this.mOnKeyStatusUpdated == null);
1701	}
1702
1703	private void switchToForeground() {
1704		for (Conversation conversation : getConversations()) {
1705			conversation.setIncomingChatState(ChatState.ACTIVE);
1706		}
1707		for (Account account : getAccounts()) {
1708			if (account.getStatus() == Account.State.ONLINE) {
1709				XmppConnection connection = account.getXmppConnection();
1710				if (connection != null && connection.getFeatures().csi()) {
1711					connection.sendActive();
1712				}
1713			}
1714		}
1715		Log.d(Config.LOGTAG, "app switched into foreground");
1716	}
1717
1718	private void switchToBackground() {
1719		for (Account account : getAccounts()) {
1720			if (account.getStatus() == Account.State.ONLINE) {
1721				XmppConnection connection = account.getXmppConnection();
1722				if (connection != null && connection.getFeatures().csi()) {
1723					connection.sendInactive();
1724				}
1725			}
1726		}
1727		this.mNotificationService.setIsInForeground(false);
1728		Log.d(Config.LOGTAG, "app switched into background");
1729	}
1730
1731	private void connectMultiModeConversations(Account account) {
1732		List<Conversation> conversations = getConversations();
1733		for (Conversation conversation : conversations) {
1734			if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
1735				joinMuc(conversation, true, null);
1736			}
1737		}
1738	}
1739
1740	public void joinMuc(Conversation conversation) {
1741		joinMuc(conversation, false, null);
1742	}
1743
1744	private void joinMuc(Conversation conversation, boolean now, final OnConferenceJoined onConferenceJoined) {
1745		Account account = conversation.getAccount();
1746		account.pendingConferenceJoins.remove(conversation);
1747		account.pendingConferenceLeaves.remove(conversation);
1748		if (account.getStatus() == Account.State.ONLINE || now) {
1749			conversation.resetMucOptions();
1750			fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
1751
1752				private void join(Conversation conversation) {
1753					Account account = conversation.getAccount();
1754					final String nick = conversation.getMucOptions().getProposedNick();
1755					final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1756					Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1757					PresencePacket packet = new PresencePacket();
1758					packet.setFrom(conversation.getAccount().getJid());
1759					packet.setTo(joinJid);
1760					Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1761					if (conversation.getMucOptions().getPassword() != null) {
1762						x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1763					}
1764
1765					if (conversation.getMucOptions().mamSupport()) {
1766						// Use MAM instead of the limited muc history to get history
1767						x.addChild("history").setAttribute("maxchars", "0");
1768					} else {
1769						// Fallback to muc history
1770						x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1771					}
1772					String sig = account.getPgpSignature();
1773					if (sig != null) {
1774						packet.addChild("x", "jabber:x:signed").setContent(sig);
1775					}
1776					sendPresencePacket(account, packet);
1777					if (onConferenceJoined != null) {
1778						onConferenceJoined.onConferenceJoined(conversation);
1779					}
1780					if (!joinJid.equals(conversation.getJid())) {
1781						conversation.setContactJid(joinJid);
1782						databaseBackend.updateConversation(conversation);
1783					}
1784					conversation.setHasMessagesLeftOnServer(false);
1785					if (conversation.getMucOptions().mamSupport()) {
1786						getMessageArchiveService().catchupMUC(conversation);
1787					}
1788					sendUnsentMessages(conversation);
1789				}
1790
1791				@Override
1792				public void onConferenceConfigurationFetched(Conversation conversation) {
1793					join(conversation);
1794				}
1795
1796				@Override
1797				public void onFetchFailed(final Conversation conversation, Element error) {
1798					join(conversation);
1799					fetchConferenceConfiguration(conversation);
1800				}
1801			});
1802
1803		} else {
1804			account.pendingConferenceJoins.add(conversation);
1805		}
1806	}
1807
1808	public void providePasswordForMuc(Conversation conversation, String password) {
1809		if (conversation.getMode() == Conversation.MODE_MULTI) {
1810			conversation.getMucOptions().setPassword(password);
1811			if (conversation.getBookmark() != null) {
1812				if (respectAutojoin()) {
1813					conversation.getBookmark().setAutojoin(true);
1814				}
1815				pushBookmarks(conversation.getAccount());
1816			}
1817			databaseBackend.updateConversation(conversation);
1818			joinMuc(conversation);
1819		}
1820	}
1821
1822	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1823		final MucOptions options = conversation.getMucOptions();
1824		final Jid joinJid = options.createJoinJid(nick);
1825		if (options.online()) {
1826			Account account = conversation.getAccount();
1827			options.setOnRenameListener(new OnRenameListener() {
1828
1829				@Override
1830				public void onSuccess() {
1831					conversation.setContactJid(joinJid);
1832					databaseBackend.updateConversation(conversation);
1833					Bookmark bookmark = conversation.getBookmark();
1834					if (bookmark != null) {
1835						bookmark.setNick(nick);
1836						pushBookmarks(bookmark.getAccount());
1837					}
1838					callback.success(conversation);
1839				}
1840
1841				@Override
1842				public void onFailure() {
1843					callback.error(R.string.nick_in_use, conversation);
1844				}
1845			});
1846
1847			PresencePacket packet = new PresencePacket();
1848			packet.setTo(joinJid);
1849			packet.setFrom(conversation.getAccount().getJid());
1850
1851			String sig = account.getPgpSignature();
1852			if (sig != null) {
1853				packet.addChild("status").setContent("online");
1854				packet.addChild("x", "jabber:x:signed").setContent(sig);
1855			}
1856			sendPresencePacket(account, packet);
1857		} else {
1858			conversation.setContactJid(joinJid);
1859			databaseBackend.updateConversation(conversation);
1860			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1861				Bookmark bookmark = conversation.getBookmark();
1862				if (bookmark != null) {
1863					bookmark.setNick(nick);
1864					pushBookmarks(bookmark.getAccount());
1865				}
1866				joinMuc(conversation);
1867			}
1868		}
1869	}
1870
1871	public void leaveMuc(Conversation conversation) {
1872		leaveMuc(conversation, false);
1873	}
1874
1875	private void leaveMuc(Conversation conversation, boolean now) {
1876		Account account = conversation.getAccount();
1877		account.pendingConferenceJoins.remove(conversation);
1878		account.pendingConferenceLeaves.remove(conversation);
1879		if (account.getStatus() == Account.State.ONLINE || now) {
1880			PresencePacket packet = new PresencePacket();
1881			packet.setTo(conversation.getJid());
1882			packet.setFrom(conversation.getAccount().getJid());
1883			packet.setAttribute("type", "unavailable");
1884			sendPresencePacket(conversation.getAccount(), packet);
1885			conversation.getMucOptions().setOffline();
1886			conversation.deregisterWithBookmark();
1887			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1888					+ ": leaving muc " + conversation.getJid());
1889		} else {
1890			account.pendingConferenceLeaves.add(conversation);
1891		}
1892	}
1893
1894	private String findConferenceServer(final Account account) {
1895		String server;
1896		if (account.getXmppConnection() != null) {
1897			server = account.getXmppConnection().getMucServer();
1898			if (server != null) {
1899				return server;
1900			}
1901		}
1902		for (Account other : getAccounts()) {
1903			if (other != account && other.getXmppConnection() != null) {
1904				server = other.getXmppConnection().getMucServer();
1905				if (server != null) {
1906					return server;
1907				}
1908			}
1909		}
1910		return null;
1911	}
1912
1913	public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1914		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1915		if (account.getStatus() == Account.State.ONLINE) {
1916			try {
1917				String server = findConferenceServer(account);
1918				if (server == null) {
1919					if (callback != null) {
1920						callback.error(R.string.no_conference_server_found, null);
1921					}
1922					return;
1923				}
1924				String name = new BigInteger(75, getRNG()).toString(32);
1925				Jid jid = Jid.fromParts(name, server, null);
1926				final Conversation conversation = findOrCreateConversation(account, jid, true);
1927				joinMuc(conversation, true, new OnConferenceJoined() {
1928					@Override
1929					public void onConferenceJoined(final Conversation conversation) {
1930						Bundle options = new Bundle();
1931						options.putString("muc#roomconfig_persistentroom", "1");
1932						options.putString("muc#roomconfig_membersonly", "1");
1933						options.putString("muc#roomconfig_publicroom", "0");
1934						options.putString("muc#roomconfig_whois", "anyone");
1935						pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1936							@Override
1937							public void onPushSucceeded() {
1938								for (Jid invite : jids) {
1939									invite(conversation, invite);
1940								}
1941								if (account.countPresences() > 1) {
1942									directInvite(conversation, account.getJid().toBareJid());
1943								}
1944								if (callback != null) {
1945									callback.success(conversation);
1946								}
1947							}
1948
1949							@Override
1950							public void onPushFailed() {
1951								if (callback != null) {
1952									callback.error(R.string.conference_creation_failed, conversation);
1953								}
1954							}
1955						});
1956					}
1957				});
1958			} catch (InvalidJidException e) {
1959				if (callback != null) {
1960					callback.error(R.string.conference_creation_failed, null);
1961				}
1962			}
1963		} else {
1964			if (callback != null) {
1965				callback.error(R.string.not_connected_try_again, null);
1966			}
1967		}
1968	}
1969
1970	public void fetchConferenceConfiguration(final Conversation conversation) {
1971		fetchConferenceConfiguration(conversation, null);
1972	}
1973
1974	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
1975		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1976		request.setTo(conversation.getJid().toBareJid());
1977		request.query("http://jabber.org/protocol/disco#info");
1978		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1979			@Override
1980			public void onIqPacketReceived(Account account, IqPacket packet) {
1981				if (packet.getType() == IqPacket.TYPE.RESULT) {
1982					ArrayList<String> features = new ArrayList<>();
1983					Element query = packet.query();
1984					for (Element child : query.getChildren()) {
1985						if (child != null && child.getName().equals("feature")) {
1986							String var = child.getAttribute("var");
1987							if (var != null) {
1988								features.add(var);
1989							}
1990						}
1991					}
1992					Element form = query.findChild("x", "jabber:x:data");
1993					if (form != null) {
1994						conversation.getMucOptions().updateFormData(Data.parse(form));
1995					}
1996					conversation.getMucOptions().updateFeatures(features);
1997					if (callback != null) {
1998						callback.onConferenceConfigurationFetched(conversation);
1999					}
2000					updateConversationUi();
2001				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
2002					if (callback != null) {
2003						callback.onFetchFailed(conversation, packet.getError());
2004					}
2005				}
2006			}
2007		});
2008	}
2009
2010	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
2011		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2012		request.setTo(conversation.getJid().toBareJid());
2013		request.query("http://jabber.org/protocol/muc#owner");
2014		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2015			@Override
2016			public void onIqPacketReceived(Account account, IqPacket packet) {
2017				if (packet.getType() == IqPacket.TYPE.RESULT) {
2018					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
2019					for (Field field : data.getFields()) {
2020						if (options.containsKey(field.getFieldName())) {
2021							field.setValue(options.getString(field.getFieldName()));
2022						}
2023					}
2024					data.submit();
2025					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2026					set.setTo(conversation.getJid().toBareJid());
2027					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2028					sendIqPacket(account, set, new OnIqPacketReceived() {
2029						@Override
2030						public void onIqPacketReceived(Account account, IqPacket packet) {
2031							if (callback != null) {
2032								if (packet.getType() == IqPacket.TYPE.RESULT) {
2033									callback.onPushSucceeded();
2034								} else {
2035									callback.onPushFailed();
2036								}
2037							}
2038						}
2039					});
2040				} else {
2041					if (callback != null) {
2042						callback.onPushFailed();
2043					}
2044				}
2045			}
2046		});
2047	}
2048
2049	public void pushSubjectToConference(final Conversation conference, final String subject) {
2050		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2051		this.sendMessagePacket(conference.getAccount(), packet);
2052		final MucOptions mucOptions = conference.getMucOptions();
2053		final MucOptions.User self = mucOptions.getSelf();
2054		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2055			Bundle options = new Bundle();
2056			options.putString("muc#roomconfig_persistentroom", "1");
2057			this.pushConferenceConfiguration(conference, options, null);
2058		}
2059	}
2060
2061	public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2062		final Jid jid = user.toBareJid();
2063		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2064		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2065			@Override
2066			public void onIqPacketReceived(Account account, IqPacket packet) {
2067				if (packet.getType() == IqPacket.TYPE.RESULT) {
2068					callback.onAffiliationChangedSuccessful(jid);
2069				} else {
2070					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2071				}
2072			}
2073		});
2074	}
2075
2076	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2077		List<Jid> jids = new ArrayList<>();
2078		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2079			if (user.getAffiliation() == before && user.getJid() != null) {
2080				jids.add(user.getJid());
2081			}
2082		}
2083		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2084		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2085	}
2086
2087	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2088		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2089		Log.d(Config.LOGTAG, request.toString());
2090		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2091			@Override
2092			public void onIqPacketReceived(Account account, IqPacket packet) {
2093				Log.d(Config.LOGTAG, packet.toString());
2094				if (packet.getType() == IqPacket.TYPE.RESULT) {
2095					callback.onRoleChangedSuccessful(nick);
2096				} else {
2097					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2098				}
2099			}
2100		});
2101	}
2102
2103	private void disconnect(Account account, boolean force) {
2104		if ((account.getStatus() == Account.State.ONLINE)
2105				|| (account.getStatus() == Account.State.DISABLED)) {
2106			if (!force) {
2107				List<Conversation> conversations = getConversations();
2108				for (Conversation conversation : conversations) {
2109					if (conversation.getAccount() == account) {
2110						if (conversation.getMode() == Conversation.MODE_MULTI) {
2111							leaveMuc(conversation, true);
2112						} else {
2113							if (conversation.endOtrIfNeeded()) {
2114								Log.d(Config.LOGTAG, account.getJid().toBareJid()
2115										+ ": ended otr session with "
2116										+ conversation.getJid());
2117							}
2118						}
2119					}
2120				}
2121				sendOfflinePresence(account);
2122			}
2123			account.getXmppConnection().disconnect(force);
2124		}
2125	}
2126
2127	@Override
2128	public IBinder onBind(Intent intent) {
2129		return mBinder;
2130	}
2131
2132	public void updateMessage(Message message) {
2133		databaseBackend.updateMessage(message);
2134		updateConversationUi();
2135	}
2136
2137	protected void syncDirtyContacts(Account account) {
2138		for (Contact contact : account.getRoster().getContacts()) {
2139			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2140				pushContactToServer(contact);
2141			}
2142			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2143				deleteContactOnServer(contact);
2144			}
2145		}
2146	}
2147
2148	public void createContact(Contact contact) {
2149		boolean autoGrant = getPreferences().getBoolean("grant_new_contacts", true);
2150		if (autoGrant) {
2151			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2152			contact.setOption(Contact.Options.ASKING);
2153		}
2154		pushContactToServer(contact);
2155	}
2156
2157	public void onOtrSessionEstablished(Conversation conversation) {
2158		final Account account = conversation.getAccount();
2159		final Session otrSession = conversation.getOtrSession();
2160		Log.d(Config.LOGTAG,
2161				account.getJid().toBareJid() + " otr session established with "
2162						+ conversation.getJid() + "/"
2163						+ otrSession.getSessionID().getUserID());
2164		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2165
2166			@Override
2167			public void onMessageFound(Message message) {
2168				SessionID id = otrSession.getSessionID();
2169				try {
2170					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2171				} catch (InvalidJidException e) {
2172					return;
2173				}
2174				if (message.needsUploading()) {
2175					mJingleConnectionManager.createNewConnection(message);
2176				} else {
2177					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2178					if (outPacket != null) {
2179						mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2180						message.setStatus(Message.STATUS_SEND);
2181						databaseBackend.updateMessage(message);
2182						sendMessagePacket(account, outPacket);
2183					}
2184				}
2185				updateConversationUi();
2186			}
2187		});
2188	}
2189
2190	public boolean renewSymmetricKey(Conversation conversation) {
2191		Account account = conversation.getAccount();
2192		byte[] symmetricKey = new byte[32];
2193		this.mRandom.nextBytes(symmetricKey);
2194		Session otrSession = conversation.getOtrSession();
2195		if (otrSession != null) {
2196			MessagePacket packet = new MessagePacket();
2197			packet.setType(MessagePacket.TYPE_CHAT);
2198			packet.setFrom(account.getJid());
2199			MessageGenerator.addMessageHints(packet);
2200			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2201					+ otrSession.getSessionID().getUserID());
2202			try {
2203				packet.setBody(otrSession
2204						.transformSending(CryptoHelper.FILETRANSFER
2205								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
2206				sendMessagePacket(account, packet);
2207				conversation.setSymmetricKey(symmetricKey);
2208				return true;
2209			} catch (OtrException e) {
2210				return false;
2211			}
2212		}
2213		return false;
2214	}
2215
2216	public void pushContactToServer(final Contact contact) {
2217		contact.resetOption(Contact.Options.DIRTY_DELETE);
2218		contact.setOption(Contact.Options.DIRTY_PUSH);
2219		final Account account = contact.getAccount();
2220		if (account.getStatus() == Account.State.ONLINE) {
2221			final boolean ask = contact.getOption(Contact.Options.ASKING);
2222			final boolean sendUpdates = contact
2223					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2224					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2225			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2226			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
2227			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2228			if (sendUpdates) {
2229				sendPresencePacket(account,
2230						mPresenceGenerator.sendPresenceUpdatesTo(contact));
2231			}
2232			if (ask) {
2233				sendPresencePacket(account,
2234						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2235			}
2236		}
2237	}
2238
2239	public void publishAvatar(final Account account,
2240							  final Uri image,
2241							  final UiCallback<Avatar> callback) {
2242		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2243		final int size = Config.AVATAR_SIZE;
2244		final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2245		if (avatar != null) {
2246			avatar.height = size;
2247			avatar.width = size;
2248			if (format.equals(Bitmap.CompressFormat.WEBP)) {
2249				avatar.type = "image/webp";
2250			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2251				avatar.type = "image/jpeg";
2252			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
2253				avatar.type = "image/png";
2254			}
2255			if (!getFileBackend().save(avatar)) {
2256				callback.error(R.string.error_saving_avatar, avatar);
2257				return;
2258			}
2259			final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2260			this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2261
2262				@Override
2263				public void onIqPacketReceived(Account account, IqPacket result) {
2264					if (result.getType() == IqPacket.TYPE.RESULT) {
2265						final IqPacket packet = XmppConnectionService.this.mIqGenerator
2266								.publishAvatarMetadata(avatar);
2267						sendIqPacket(account, packet, new OnIqPacketReceived() {
2268							@Override
2269							public void onIqPacketReceived(Account account, IqPacket result) {
2270								if (result.getType() == IqPacket.TYPE.RESULT) {
2271									if (account.setAvatar(avatar.getFilename())) {
2272										getAvatarService().clear(account);
2273										databaseBackend.updateAccount(account);
2274									}
2275									callback.success(avatar);
2276								} else {
2277									callback.error(
2278											R.string.error_publish_avatar_server_reject,
2279											avatar);
2280								}
2281							}
2282						});
2283					} else {
2284						callback.error(
2285								R.string.error_publish_avatar_server_reject,
2286								avatar);
2287					}
2288				}
2289			});
2290		} else {
2291			callback.error(R.string.error_publish_avatar_converting, null);
2292		}
2293	}
2294
2295	public void fetchAvatar(Account account, Avatar avatar) {
2296		fetchAvatar(account, avatar, null);
2297	}
2298
2299	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2300		final String KEY = generateFetchKey(account, avatar);
2301		synchronized (this.mInProgressAvatarFetches) {
2302			if (this.mInProgressAvatarFetches.contains(KEY)) {
2303				return;
2304			} else {
2305				switch (avatar.origin) {
2306					case PEP:
2307						this.mInProgressAvatarFetches.add(KEY);
2308						fetchAvatarPep(account, avatar, callback);
2309						break;
2310					case VCARD:
2311						this.mInProgressAvatarFetches.add(KEY);
2312						fetchAvatarVcard(account, avatar, callback);
2313						break;
2314				}
2315			}
2316		}
2317	}
2318
2319	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2320		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2321		sendIqPacket(account, packet, new OnIqPacketReceived() {
2322
2323			@Override
2324			public void onIqPacketReceived(Account account, IqPacket result) {
2325				synchronized (mInProgressAvatarFetches) {
2326					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2327				}
2328				final String ERROR = account.getJid().toBareJid()
2329						+ ": fetching avatar for " + avatar.owner + " failed ";
2330				if (result.getType() == IqPacket.TYPE.RESULT) {
2331					avatar.image = mIqParser.avatarData(result);
2332					if (avatar.image != null) {
2333						if (getFileBackend().save(avatar)) {
2334							if (account.getJid().toBareJid().equals(avatar.owner)) {
2335								if (account.setAvatar(avatar.getFilename())) {
2336									databaseBackend.updateAccount(account);
2337								}
2338								getAvatarService().clear(account);
2339								updateConversationUi();
2340								updateAccountUi();
2341							} else {
2342								Contact contact = account.getRoster()
2343										.getContact(avatar.owner);
2344								contact.setAvatar(avatar);
2345								getAvatarService().clear(contact);
2346								updateConversationUi();
2347								updateRosterUi();
2348							}
2349							if (callback != null) {
2350								callback.success(avatar);
2351							}
2352							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2353									+ ": succesfuly fetched pep avatar for " + avatar.owner);
2354							return;
2355						}
2356					} else {
2357
2358						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2359					}
2360				} else {
2361					Element error = result.findChild("error");
2362					if (error == null) {
2363						Log.d(Config.LOGTAG, ERROR + "(server error)");
2364					} else {
2365						Log.d(Config.LOGTAG, ERROR + error.toString());
2366					}
2367				}
2368				if (callback != null) {
2369					callback.error(0, null);
2370				}
2371
2372			}
2373		});
2374	}
2375
2376	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2377		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2378		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2379			@Override
2380			public void onIqPacketReceived(Account account, IqPacket packet) {
2381				synchronized (mInProgressAvatarFetches) {
2382					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2383				}
2384				if (packet.getType() == IqPacket.TYPE.RESULT) {
2385					Element vCard = packet.findChild("vCard", "vcard-temp");
2386					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2387					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2388					if (image != null) {
2389						avatar.image = image;
2390						if (getFileBackend().save(avatar)) {
2391							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2392									+ ": successfully fetched vCard avatar for " + avatar.owner);
2393							if (avatar.owner.isBareJid()) {
2394								Contact contact = account.getRoster()
2395										.getContact(avatar.owner);
2396								contact.setAvatar(avatar);
2397								getAvatarService().clear(contact);
2398								updateConversationUi();
2399								updateRosterUi();
2400							} else {
2401								Conversation conversation = find(account, avatar.owner.toBareJid());
2402								if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
2403									MucOptions.User user = conversation.getMucOptions().findUser(avatar.owner.getResourcepart());
2404									if (user != null) {
2405										if (user.setAvatar(avatar)) {
2406											getAvatarService().clear(user);
2407											updateConversationUi();
2408											updateMucRosterUi();
2409										}
2410									}
2411								}
2412							}
2413						}
2414					}
2415				}
2416			}
2417		});
2418	}
2419
2420	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2421		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2422		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2423
2424			@Override
2425			public void onIqPacketReceived(Account account, IqPacket packet) {
2426				if (packet.getType() == IqPacket.TYPE.RESULT) {
2427					Element pubsub = packet.findChild("pubsub",
2428							"http://jabber.org/protocol/pubsub");
2429					if (pubsub != null) {
2430						Element items = pubsub.findChild("items");
2431						if (items != null) {
2432							Avatar avatar = Avatar.parseMetadata(items);
2433							if (avatar != null) {
2434								avatar.owner = account.getJid().toBareJid();
2435								if (fileBackend.isAvatarCached(avatar)) {
2436									if (account.setAvatar(avatar.getFilename())) {
2437										databaseBackend.updateAccount(account);
2438									}
2439									getAvatarService().clear(account);
2440									callback.success(avatar);
2441								} else {
2442									fetchAvatarPep(account, avatar, callback);
2443								}
2444								return;
2445							}
2446						}
2447					}
2448				}
2449				callback.error(0, null);
2450			}
2451		});
2452	}
2453
2454	public void deleteContactOnServer(Contact contact) {
2455		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2456		contact.resetOption(Contact.Options.DIRTY_PUSH);
2457		contact.setOption(Contact.Options.DIRTY_DELETE);
2458		Account account = contact.getAccount();
2459		if (account.getStatus() == Account.State.ONLINE) {
2460			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2461			Element item = iq.query(Xmlns.ROSTER).addChild("item");
2462			item.setAttribute("jid", contact.getJid().toString());
2463			item.setAttribute("subscription", "remove");
2464			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2465		}
2466	}
2467
2468	public void updateConversation(Conversation conversation) {
2469		this.databaseBackend.updateConversation(conversation);
2470	}
2471
2472	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2473		synchronized (account) {
2474			XmppConnection connection = account.getXmppConnection();
2475			if (connection != null) {
2476				disconnect(account, force);
2477			} else {
2478				connection = createConnection(account);
2479				account.setXmppConnection(connection);
2480			}
2481			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2482				synchronized (this.mInProgressAvatarFetches) {
2483					for (Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
2484						final String KEY = iterator.next();
2485						if (KEY.startsWith(account.getJid().toBareJid() + "_")) {
2486							iterator.remove();
2487						}
2488					}
2489				}
2490				if (!force) {
2491					try {
2492						Log.d(Config.LOGTAG, "wait for disconnect");
2493						Thread.sleep(500); //sleep  wait for disconnect
2494					} catch (InterruptedException e) {
2495						//ignored
2496					}
2497				}
2498				Thread thread = new Thread(connection);
2499				connection.setInteractive(interactive);
2500				thread.start();
2501				scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2502			} else {
2503				account.getRoster().clearPresences();
2504				connection.resetEverything();
2505			}
2506		}
2507	}
2508
2509	public void reconnectAccountInBackground(final Account account) {
2510		new Thread(new Runnable() {
2511			@Override
2512			public void run() {
2513				reconnectAccount(account, false, true);
2514			}
2515		}).start();
2516	}
2517
2518	public void invite(Conversation conversation, Jid contact) {
2519		Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
2520		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2521		sendMessagePacket(conversation.getAccount(), packet);
2522	}
2523
2524	public void directInvite(Conversation conversation, Jid jid) {
2525		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2526		sendMessagePacket(conversation.getAccount(), packet);
2527	}
2528
2529	public void resetSendingToWaiting(Account account) {
2530		for (Conversation conversation : getConversations()) {
2531			if (conversation.getAccount() == account) {
2532				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2533
2534					@Override
2535					public void onMessageFound(Message message) {
2536						markMessage(message, Message.STATUS_WAITING);
2537					}
2538				});
2539			}
2540		}
2541	}
2542
2543	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2544		if (uuid == null) {
2545			return null;
2546		}
2547		for (Conversation conversation : getConversations()) {
2548			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2549				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
2550				if (message != null) {
2551					markMessage(message, status);
2552				}
2553				return message;
2554			}
2555		}
2556		return null;
2557	}
2558
2559	public boolean markMessage(Conversation conversation, String uuid, int status) {
2560		if (uuid == null) {
2561			return false;
2562		} else {
2563			Message message = conversation.findSentMessageWithUuid(uuid);
2564			if (message != null) {
2565				markMessage(message, status);
2566				return true;
2567			} else {
2568				return false;
2569			}
2570		}
2571	}
2572
2573	public void markMessage(Message message, int status) {
2574		if (status == Message.STATUS_SEND_FAILED
2575				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2576				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2577			return;
2578		}
2579		message.setStatus(status);
2580		databaseBackend.updateMessage(message);
2581		updateConversationUi();
2582	}
2583
2584	public SharedPreferences getPreferences() {
2585		return PreferenceManager
2586				.getDefaultSharedPreferences(getApplicationContext());
2587	}
2588
2589	public boolean confirmMessages() {
2590		return getPreferences().getBoolean("confirm_messages", true);
2591	}
2592
2593	public boolean sendChatStates() {
2594		return getPreferences().getBoolean("chat_states", false);
2595	}
2596
2597	public boolean saveEncryptedMessages() {
2598		return !getPreferences().getBoolean("dont_save_encrypted", false);
2599	}
2600
2601	private boolean respectAutojoin() {
2602		return getPreferences().getBoolean("autojoin", true);
2603	}
2604
2605	public boolean indicateReceived() {
2606		return getPreferences().getBoolean("indicate_received", false);
2607	}
2608
2609	public boolean useTorToConnect() {
2610		return Config.FORCE_ORBOT || getPreferences().getBoolean("use_tor", false);
2611	}
2612
2613	public boolean showExtendedConnectionOptions() {
2614		return getPreferences().getBoolean("show_connection_options", false);
2615	}
2616
2617	public int unreadCount() {
2618		int count = 0;
2619		for (Conversation conversation : getConversations()) {
2620			count += conversation.unreadCount();
2621		}
2622		return count;
2623	}
2624
2625
2626	public void showErrorToastInUi(int resId) {
2627		if (mOnShowErrorToast != null) {
2628			mOnShowErrorToast.onShowErrorToast(resId);
2629		}
2630	}
2631
2632	public void updateConversationUi() {
2633		if (mOnConversationUpdate != null) {
2634			mOnConversationUpdate.onConversationUpdate();
2635		}
2636	}
2637
2638	public void updateAccountUi() {
2639		if (mOnAccountUpdate != null) {
2640			mOnAccountUpdate.onAccountUpdate();
2641		}
2642	}
2643
2644	public void updateRosterUi() {
2645		if (mOnRosterUpdate != null) {
2646			mOnRosterUpdate.onRosterUpdate();
2647		}
2648	}
2649
2650	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
2651		boolean rc = false;
2652		if (mOnCaptchaRequested != null) {
2653			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
2654			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
2655					(int) (captcha.getHeight() * metrics.scaledDensity), false);
2656
2657			mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
2658			rc = true;
2659		}
2660
2661		return rc;
2662	}
2663
2664	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2665		if (mOnUpdateBlocklist != null) {
2666			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2667		}
2668	}
2669
2670	public void updateMucRosterUi() {
2671		if (mOnMucRosterUpdate != null) {
2672			mOnMucRosterUpdate.onMucRosterUpdate();
2673		}
2674	}
2675
2676	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
2677		if (mOnKeyStatusUpdated != null) {
2678			mOnKeyStatusUpdated.onKeyStatusUpdated(report);
2679		}
2680	}
2681
2682	public Account findAccountByJid(final Jid accountJid) {
2683		for (Account account : this.accounts) {
2684			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2685				return account;
2686			}
2687		}
2688		return null;
2689	}
2690
2691	public Conversation findConversationByUuid(String uuid) {
2692		for (Conversation conversation : getConversations()) {
2693			if (conversation.getUuid().equals(uuid)) {
2694				return conversation;
2695			}
2696		}
2697		return null;
2698	}
2699
2700	public void markRead(final Conversation conversation) {
2701		mNotificationService.clear(conversation);
2702		final List<Message> readMessages = conversation.markRead();
2703		if (readMessages.size() > 0) {
2704			Runnable runnable = new Runnable() {
2705				@Override
2706				public void run() {
2707					for (Message message : readMessages) {
2708						databaseBackend.updateMessage(message);
2709					}
2710				}
2711			};
2712			mDatabaseExecutor.execute(runnable);
2713		}
2714		updateUnreadCountBadge();
2715	}
2716
2717	public synchronized void updateUnreadCountBadge() {
2718		int count = unreadCount();
2719		if (unreadCount != count) {
2720			Log.d(Config.LOGTAG, "update unread count to " + count);
2721			if (count > 0) {
2722				ShortcutBadger.with(getApplicationContext()).count(count);
2723			} else {
2724				ShortcutBadger.with(getApplicationContext()).remove();
2725			}
2726			unreadCount = count;
2727		}
2728	}
2729
2730	public void sendReadMarker(final Conversation conversation) {
2731		final Message markable = conversation.getLatestMarkableMessage();
2732		this.markRead(conversation);
2733		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2734			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2735			Account account = conversation.getAccount();
2736			final Jid to = markable.getCounterpart();
2737			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2738			this.sendMessagePacket(conversation.getAccount(), packet);
2739		}
2740		updateConversationUi();
2741	}
2742
2743	public SecureRandom getRNG() {
2744		return this.mRandom;
2745	}
2746
2747	public MemorizingTrustManager getMemorizingTrustManager() {
2748		return this.mMemorizingTrustManager;
2749	}
2750
2751	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2752		this.mMemorizingTrustManager = trustManager;
2753	}
2754
2755	public void updateMemorizingTrustmanager() {
2756		final MemorizingTrustManager tm;
2757		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2758		if (dontTrustSystemCAs) {
2759			tm = new MemorizingTrustManager(getApplicationContext(), null);
2760		} else {
2761			tm = new MemorizingTrustManager(getApplicationContext());
2762		}
2763		setMemorizingTrustManager(tm);
2764	}
2765
2766	public PowerManager getPowerManager() {
2767		return this.pm;
2768	}
2769
2770	public LruCache<String, Bitmap> getBitmapCache() {
2771		return this.mBitmapCache;
2772	}
2773
2774	public void syncRosterToDisk(final Account account) {
2775		Runnable runnable = new Runnable() {
2776
2777			@Override
2778			public void run() {
2779				databaseBackend.writeRoster(account.getRoster());
2780			}
2781		};
2782		mDatabaseExecutor.execute(runnable);
2783
2784	}
2785
2786	public List<String> getKnownHosts() {
2787		final List<String> hosts = new ArrayList<>();
2788		for (final Account account : getAccounts()) {
2789			if (!hosts.contains(account.getServer().toString())) {
2790				hosts.add(account.getServer().toString());
2791			}
2792			for (final Contact contact : account.getRoster().getContacts()) {
2793				if (contact.showInRoster()) {
2794					final String server = contact.getServer().toString();
2795					if (server != null && !hosts.contains(server)) {
2796						hosts.add(server);
2797					}
2798				}
2799			}
2800		}
2801		return hosts;
2802	}
2803
2804	public List<String> getKnownConferenceHosts() {
2805		final ArrayList<String> mucServers = new ArrayList<>();
2806		for (final Account account : accounts) {
2807			if (account.getXmppConnection() != null) {
2808				final String server = account.getXmppConnection().getMucServer();
2809				if (server != null && !mucServers.contains(server)) {
2810					mucServers.add(server);
2811				}
2812			}
2813		}
2814		return mucServers;
2815	}
2816
2817	public void sendMessagePacket(Account account, MessagePacket packet) {
2818		XmppConnection connection = account.getXmppConnection();
2819		if (connection != null) {
2820			connection.sendMessagePacket(packet);
2821		}
2822	}
2823
2824	public void sendPresencePacket(Account account, PresencePacket packet) {
2825		XmppConnection connection = account.getXmppConnection();
2826		if (connection != null) {
2827			connection.sendPresencePacket(packet);
2828		}
2829	}
2830
2831	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
2832		XmppConnection connection = account.getXmppConnection();
2833		if (connection != null) {
2834			connection.sendCaptchaRegistryRequest(id, data);
2835		}
2836	}
2837
2838	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2839		final XmppConnection connection = account.getXmppConnection();
2840		if (connection != null) {
2841			connection.sendIqPacket(packet, callback);
2842		}
2843	}
2844
2845	public void sendPresence(final Account account) {
2846		sendPresencePacket(account, mPresenceGenerator.selfPresence(account, getTargetPresence()));
2847	}
2848
2849	public void refreshAllPresences() {
2850		for (Account account : getAccounts()) {
2851			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2852				sendPresence(account);
2853			}
2854		}
2855	}
2856
2857	private void refreshAllGcmTokens() {
2858		for(Account account : getAccounts()) {
2859			if (account.isOnlineAndConnected() && mPushManagementService.pushAvailable(account)) {
2860				mPushManagementService.registerPushTokenOnServer(account);
2861			}
2862		}
2863	}
2864
2865	public void sendOfflinePresence(final Account account) {
2866		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2867	}
2868
2869	public MessageGenerator getMessageGenerator() {
2870		return this.mMessageGenerator;
2871	}
2872
2873	public PresenceGenerator getPresenceGenerator() {
2874		return this.mPresenceGenerator;
2875	}
2876
2877	public IqGenerator getIqGenerator() {
2878		return this.mIqGenerator;
2879	}
2880
2881	public IqParser getIqParser() {
2882		return this.mIqParser;
2883	}
2884
2885	public JingleConnectionManager getJingleConnectionManager() {
2886		return this.mJingleConnectionManager;
2887	}
2888
2889	public MessageArchiveService getMessageArchiveService() {
2890		return this.mMessageArchiveService;
2891	}
2892
2893	public List<Contact> findContacts(Jid jid) {
2894		ArrayList<Contact> contacts = new ArrayList<>();
2895		for (Account account : getAccounts()) {
2896			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2897				Contact contact = account.getRoster().getContactFromRoster(jid);
2898				if (contact != null) {
2899					contacts.add(contact);
2900				}
2901			}
2902		}
2903		return contacts;
2904	}
2905
2906	public NotificationService getNotificationService() {
2907		return this.mNotificationService;
2908	}
2909
2910	public HttpConnectionManager getHttpConnectionManager() {
2911		return this.mHttpConnectionManager;
2912	}
2913
2914	public void resendFailedMessages(final Message message) {
2915		final Collection<Message> messages = new ArrayList<>();
2916		Message current = message;
2917		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2918			messages.add(current);
2919			if (current.mergeable(current.next())) {
2920				current = current.next();
2921			} else {
2922				break;
2923			}
2924		}
2925		for (final Message msg : messages) {
2926			msg.setTime(System.currentTimeMillis());
2927			markMessage(msg, Message.STATUS_WAITING);
2928			this.resendMessage(msg, false);
2929		}
2930	}
2931
2932	public void clearConversationHistory(final Conversation conversation) {
2933		conversation.clearMessages();
2934		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2935		conversation.setLastClearHistory(System.currentTimeMillis());
2936		Runnable runnable = new Runnable() {
2937			@Override
2938			public void run() {
2939				databaseBackend.deleteMessagesInConversation(conversation);
2940			}
2941		};
2942		mDatabaseExecutor.execute(runnable);
2943	}
2944
2945	public void sendBlockRequest(final Blockable blockable) {
2946		if (blockable != null && blockable.getBlockedJid() != null) {
2947			final Jid jid = blockable.getBlockedJid();
2948			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2949
2950				@Override
2951				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2952					if (packet.getType() == IqPacket.TYPE.RESULT) {
2953						account.getBlocklist().add(jid);
2954						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2955					}
2956				}
2957			});
2958		}
2959	}
2960
2961	public void sendUnblockRequest(final Blockable blockable) {
2962		if (blockable != null && blockable.getJid() != null) {
2963			final Jid jid = blockable.getBlockedJid();
2964			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2965				@Override
2966				public void onIqPacketReceived(final Account account, final IqPacket packet) {
2967					if (packet.getType() == IqPacket.TYPE.RESULT) {
2968						account.getBlocklist().remove(jid);
2969						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2970					}
2971				}
2972			});
2973		}
2974	}
2975
2976	public void publishDisplayName(Account account) {
2977		String displayName = account.getDisplayName();
2978		if (displayName != null && !displayName.isEmpty()) {
2979			IqPacket publish = mIqGenerator.publishNick(displayName);
2980			sendIqPacket(account, publish, new OnIqPacketReceived() {
2981				@Override
2982				public void onIqPacketReceived(Account account, IqPacket packet) {
2983					if (packet.getType() == IqPacket.TYPE.ERROR) {
2984						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not publish nick");
2985					}
2986				}
2987			});
2988		}
2989	}
2990
2991	private ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String,String> key) {
2992		ServiceDiscoveryResult result = discoCache.get(key);
2993		if (result != null) {
2994			return result;
2995		} else {
2996			result = databaseBackend.findDiscoveryResult(key.first, key.second);
2997			if (result != null) {
2998				discoCache.put(key, result);
2999			}
3000			return result;
3001		}
3002	}
3003
3004	public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3005		final Pair<String,String> key = new Pair<>(presence.getHash(), presence.getVer());
3006		ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3007		if (disco != null) {
3008			presence.setServiceDiscoveryResult(disco);
3009		} else {
3010			if (!account.inProgressDiscoFetches.contains(key)) {
3011				account.inProgressDiscoFetches.add(key);
3012				IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3013				request.setTo(jid);
3014				request.query("http://jabber.org/protocol/disco#info");
3015				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": making disco request for "+key.second+" to "+jid);
3016				sendIqPacket(account, request, new OnIqPacketReceived() {
3017					@Override
3018					public void onIqPacketReceived(Account account, IqPacket discoPacket) {
3019						if (discoPacket.getType() == IqPacket.TYPE.RESULT) {
3020							ServiceDiscoveryResult disco = new ServiceDiscoveryResult(discoPacket);
3021							if (presence.getVer().equals(disco.getVer())) {
3022								databaseBackend.insertDiscoveryResult(disco);
3023								injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco);
3024							} else {
3025								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco.getVer());
3026							}
3027						}
3028						account.inProgressDiscoFetches.remove(key);
3029					}
3030				});
3031			}
3032		}
3033	}
3034
3035	private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3036		for(Contact contact : roster.getContacts()) {
3037			for(Presence presence : contact.getPresences().getPresences().values()) {
3038				if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3039					presence.setServiceDiscoveryResult(disco);
3040				}
3041			}
3042		}
3043	}
3044
3045	public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3046		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3047		request.addChild("prefs","urn:xmpp:mam:0");
3048		sendIqPacket(account, request, new OnIqPacketReceived() {
3049			@Override
3050			public void onIqPacketReceived(Account account, IqPacket packet) {
3051				Element prefs = packet.findChild("prefs","urn:xmpp:mam:0");
3052				if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3053					callback.onPreferencesFetched(prefs);
3054				} else {
3055					callback.onPreferencesFetchFailed();
3056				}
3057			}
3058		});
3059	}
3060
3061	public PushManagementService getPushManagementService() {
3062		return mPushManagementService;
3063	}
3064
3065	public interface OnMamPreferencesFetched {
3066		void onPreferencesFetched(Element prefs);
3067		void onPreferencesFetchFailed();
3068	}
3069
3070	public void pushMamPreferences(Account account, Element prefs) {
3071		IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3072		set.addChild(prefs);
3073		sendIqPacket(account, set, null);
3074	}
3075
3076	public interface OnAccountCreated {
3077		void onAccountCreated(Account account);
3078
3079		void informUser(int r);
3080	}
3081
3082	public interface OnMoreMessagesLoaded {
3083		void onMoreMessagesLoaded(int count, Conversation conversation);
3084
3085		void informUser(int r);
3086	}
3087
3088	public interface OnAccountPasswordChanged {
3089		void onPasswordChangeSucceeded();
3090
3091		void onPasswordChangeFailed();
3092	}
3093
3094	public interface OnAffiliationChanged {
3095		void onAffiliationChangedSuccessful(Jid jid);
3096
3097		void onAffiliationChangeFailed(Jid jid, int resId);
3098	}
3099
3100	public interface OnRoleChanged {
3101		void onRoleChangedSuccessful(String nick);
3102
3103		void onRoleChangeFailed(String nick, int resid);
3104	}
3105
3106	public interface OnConversationUpdate {
3107		void onConversationUpdate();
3108	}
3109
3110	public interface OnAccountUpdate {
3111		void onAccountUpdate();
3112	}
3113
3114	public interface OnCaptchaRequested {
3115		void onCaptchaRequested(Account account,
3116								String id,
3117								Data data,
3118								Bitmap captcha);
3119	}
3120
3121	public interface OnRosterUpdate {
3122		void onRosterUpdate();
3123	}
3124
3125	public interface OnMucRosterUpdate {
3126		void onMucRosterUpdate();
3127	}
3128
3129	public interface OnConferenceConfigurationFetched {
3130		void onConferenceConfigurationFetched(Conversation conversation);
3131
3132		void onFetchFailed(Conversation conversation, Element error);
3133	}
3134
3135	public interface OnConferenceJoined {
3136		void onConferenceJoined(Conversation conversation);
3137	}
3138
3139	public interface OnConferenceOptionsPushed {
3140		void onPushSucceeded();
3141
3142		void onPushFailed();
3143	}
3144
3145	public interface OnShowErrorToast {
3146		void onShowErrorToast(int resId);
3147	}
3148
3149	public class XmppConnectionBinder extends Binder {
3150		public XmppConnectionService getService() {
3151			return XmppConnectionService.this;
3152		}
3153	}
3154}