XmppConnectionService.java

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