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