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