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