XmppConnectionService.java

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