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				this.disconnect(account, true);
1566			}
1567			Runnable runnable = new Runnable() {
1568				@Override
1569				public void run() {
1570					databaseBackend.deleteAccount(account);
1571				}
1572			};
1573			mDatabaseExecutor.execute(runnable);
1574			this.accounts.remove(account);
1575			updateAccountUi();
1576			getNotificationService().updateErrorNotification();
1577		}
1578	}
1579
1580	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1581		synchronized (this) {
1582			if (checkListeners()) {
1583				switchToForeground();
1584			}
1585			this.mOnConversationUpdate = listener;
1586			this.mNotificationService.setIsInForeground(true);
1587			if (this.convChangedListenerCount < 2) {
1588				this.convChangedListenerCount++;
1589			}
1590		}
1591	}
1592
1593	public void removeOnConversationListChangedListener() {
1594		synchronized (this) {
1595			this.convChangedListenerCount--;
1596			if (this.convChangedListenerCount <= 0) {
1597				this.convChangedListenerCount = 0;
1598				this.mOnConversationUpdate = null;
1599				this.mNotificationService.setIsInForeground(false);
1600				if (checkListeners()) {
1601					switchToBackground();
1602				}
1603			}
1604		}
1605	}
1606
1607	public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1608		synchronized (this) {
1609			if (checkListeners()) {
1610				switchToForeground();
1611			}
1612			this.mOnShowErrorToast = onShowErrorToast;
1613			if (this.showErrorToastListenerCount < 2) {
1614				this.showErrorToastListenerCount++;
1615			}
1616		}
1617		this.mOnShowErrorToast = onShowErrorToast;
1618	}
1619
1620	public void removeOnShowErrorToastListener() {
1621		synchronized (this) {
1622			this.showErrorToastListenerCount--;
1623			if (this.showErrorToastListenerCount <= 0) {
1624				this.showErrorToastListenerCount = 0;
1625				this.mOnShowErrorToast = null;
1626				if (checkListeners()) {
1627					switchToBackground();
1628				}
1629			}
1630		}
1631	}
1632
1633	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1634		synchronized (this) {
1635			if (checkListeners()) {
1636				switchToForeground();
1637			}
1638			this.mOnAccountUpdate = listener;
1639			if (this.accountChangedListenerCount < 2) {
1640				this.accountChangedListenerCount++;
1641			}
1642		}
1643	}
1644
1645	public void removeOnAccountListChangedListener() {
1646		synchronized (this) {
1647			this.accountChangedListenerCount--;
1648			if (this.accountChangedListenerCount <= 0) {
1649				this.mOnAccountUpdate = null;
1650				this.accountChangedListenerCount = 0;
1651				if (checkListeners()) {
1652					switchToBackground();
1653				}
1654			}
1655		}
1656	}
1657
1658	public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
1659		synchronized (this) {
1660			if (checkListeners()) {
1661				switchToForeground();
1662			}
1663			this.mOnCaptchaRequested = listener;
1664			if (this.captchaRequestedListenerCount < 2) {
1665				this.captchaRequestedListenerCount++;
1666			}
1667		}
1668	}
1669
1670	public void removeOnCaptchaRequestedListener() {
1671		synchronized (this) {
1672			this.captchaRequestedListenerCount--;
1673			if (this.captchaRequestedListenerCount <= 0) {
1674				this.mOnCaptchaRequested = null;
1675				this.captchaRequestedListenerCount = 0;
1676				if (checkListeners()) {
1677					switchToBackground();
1678				}
1679			}
1680		}
1681	}
1682
1683	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1684		synchronized (this) {
1685			if (checkListeners()) {
1686				switchToForeground();
1687			}
1688			this.mOnRosterUpdate = listener;
1689			if (this.rosterChangedListenerCount < 2) {
1690				this.rosterChangedListenerCount++;
1691			}
1692		}
1693	}
1694
1695	public void removeOnRosterUpdateListener() {
1696		synchronized (this) {
1697			this.rosterChangedListenerCount--;
1698			if (this.rosterChangedListenerCount <= 0) {
1699				this.rosterChangedListenerCount = 0;
1700				this.mOnRosterUpdate = null;
1701				if (checkListeners()) {
1702					switchToBackground();
1703				}
1704			}
1705		}
1706	}
1707
1708	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1709		synchronized (this) {
1710			if (checkListeners()) {
1711				switchToForeground();
1712			}
1713			this.mOnUpdateBlocklist = listener;
1714			if (this.updateBlocklistListenerCount < 2) {
1715				this.updateBlocklistListenerCount++;
1716			}
1717		}
1718	}
1719
1720	public void removeOnUpdateBlocklistListener() {
1721		synchronized (this) {
1722			this.updateBlocklistListenerCount--;
1723			if (this.updateBlocklistListenerCount <= 0) {
1724				this.updateBlocklistListenerCount = 0;
1725				this.mOnUpdateBlocklist = null;
1726				if (checkListeners()) {
1727					switchToBackground();
1728				}
1729			}
1730		}
1731	}
1732
1733	public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
1734		synchronized (this) {
1735			if (checkListeners()) {
1736				switchToForeground();
1737			}
1738			this.mOnKeyStatusUpdated = listener;
1739			if (this.keyStatusUpdatedListenerCount < 2) {
1740				this.keyStatusUpdatedListenerCount++;
1741			}
1742		}
1743	}
1744
1745	public void removeOnNewKeysAvailableListener() {
1746		synchronized (this) {
1747			this.keyStatusUpdatedListenerCount--;
1748			if (this.keyStatusUpdatedListenerCount <= 0) {
1749				this.keyStatusUpdatedListenerCount = 0;
1750				this.mOnKeyStatusUpdated = null;
1751				if (checkListeners()) {
1752					switchToBackground();
1753				}
1754			}
1755		}
1756	}
1757
1758	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1759		synchronized (this) {
1760			if (checkListeners()) {
1761				switchToForeground();
1762			}
1763			this.mOnMucRosterUpdate = listener;
1764			if (this.mucRosterChangedListenerCount < 2) {
1765				this.mucRosterChangedListenerCount++;
1766			}
1767		}
1768	}
1769
1770	public void removeOnMucRosterUpdateListener() {
1771		synchronized (this) {
1772			this.mucRosterChangedListenerCount--;
1773			if (this.mucRosterChangedListenerCount <= 0) {
1774				this.mucRosterChangedListenerCount = 0;
1775				this.mOnMucRosterUpdate = null;
1776				if (checkListeners()) {
1777					switchToBackground();
1778				}
1779			}
1780		}
1781	}
1782
1783	public boolean checkListeners() {
1784		return (this.mOnAccountUpdate == null
1785				&& this.mOnConversationUpdate == null
1786				&& this.mOnRosterUpdate == null
1787				&& this.mOnCaptchaRequested == null
1788				&& this.mOnUpdateBlocklist == null
1789				&& this.mOnShowErrorToast == null
1790				&& this.mOnKeyStatusUpdated == null);
1791	}
1792
1793	private void switchToForeground() {
1794		for (Conversation conversation : getConversations()) {
1795			conversation.setIncomingChatState(ChatState.ACTIVE);
1796		}
1797		for (Account account : getAccounts()) {
1798			if (account.getStatus() == Account.State.ONLINE) {
1799				account.deactivateGracePeriod();
1800				XmppConnection connection = account.getXmppConnection();
1801				if (connection != null && connection.getFeatures().csi()) {
1802					connection.sendActive();
1803				}
1804			}
1805		}
1806		Log.d(Config.LOGTAG, "app switched into foreground");
1807	}
1808
1809	private void switchToBackground() {
1810		for (Account account : getAccounts()) {
1811			if (account.getStatus() == Account.State.ONLINE) {
1812				XmppConnection connection = account.getXmppConnection();
1813				if (connection != null) {
1814					if (connection.getFeatures().csi()) {
1815						connection.sendInactive();
1816					}
1817					if (Config.CLOSE_TCP_WHEN_SWITCHING_TO_BACKGROUND && mPushManagementService.available(account)) {
1818						connection.waitForPush();
1819						cancelWakeUpCall(account.getUuid().hashCode());
1820					}
1821				}
1822			}
1823		}
1824		this.mNotificationService.setIsInForeground(false);
1825		Log.d(Config.LOGTAG, "app switched into background");
1826	}
1827
1828	private void connectMultiModeConversations(Account account) {
1829		List<Conversation> conversations = getConversations();
1830		for (Conversation conversation : conversations) {
1831			if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
1832				joinMuc(conversation);
1833			}
1834		}
1835	}
1836
1837	public void joinMuc(Conversation conversation) {
1838		joinMuc(conversation, null);
1839	}
1840
1841	private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
1842		Account account = conversation.getAccount();
1843		account.pendingConferenceJoins.remove(conversation);
1844		account.pendingConferenceLeaves.remove(conversation);
1845		if (account.getStatus() == Account.State.ONLINE) {
1846			conversation.resetMucOptions();
1847			if (onConferenceJoined != null) {
1848				conversation.getMucOptions().flagNoAutoPushConfiguration();
1849			}
1850			conversation.setHasMessagesLeftOnServer(false);
1851			fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
1852
1853				private void join(Conversation conversation) {
1854					Account account = conversation.getAccount();
1855					final MucOptions mucOptions = conversation.getMucOptions();
1856					final Jid joinJid = mucOptions.getSelf().getFullJid();
1857					Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1858					PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE);
1859					packet.setTo(joinJid);
1860					Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1861					if (conversation.getMucOptions().getPassword() != null) {
1862						x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1863					}
1864
1865					if (mucOptions.mamSupport()) {
1866						// Use MAM instead of the limited muc history to get history
1867						x.addChild("history").setAttribute("maxchars", "0");
1868					} else {
1869						// Fallback to muc history
1870						x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1871					}
1872					sendPresencePacket(account, packet);
1873					if (onConferenceJoined != null) {
1874						onConferenceJoined.onConferenceJoined(conversation);
1875					}
1876					if (!joinJid.equals(conversation.getJid())) {
1877						conversation.setContactJid(joinJid);
1878						databaseBackend.updateConversation(conversation);
1879					}
1880
1881					if (mucOptions.mamSupport()) {
1882						getMessageArchiveService().catchupMUC(conversation);
1883					}
1884					if (mucOptions.membersOnly() && mucOptions.nonanonymous()) {
1885						fetchConferenceMembers(conversation);
1886					}
1887					sendUnsentMessages(conversation);
1888				}
1889
1890				@Override
1891				public void onConferenceConfigurationFetched(Conversation conversation) {
1892					join(conversation);
1893				}
1894
1895				@Override
1896				public void onFetchFailed(final Conversation conversation, Element error) {
1897					join(conversation);
1898					fetchConferenceConfiguration(conversation);
1899				}
1900			});
1901			updateConversationUi();
1902		} else {
1903			account.pendingConferenceJoins.add(conversation);
1904			conversation.resetMucOptions();
1905			conversation.setHasMessagesLeftOnServer(false);
1906			updateConversationUi();
1907		}
1908	}
1909
1910	private void fetchConferenceMembers(final Conversation conversation) {
1911		final Account account = conversation.getAccount();
1912		final String[] affiliations = {"member","admin","owner"};
1913		OnIqPacketReceived callback = new OnIqPacketReceived() {
1914
1915			private int i = 0;
1916
1917			@Override
1918			public void onIqPacketReceived(Account account, IqPacket packet) {
1919
1920				Element query = packet.query("http://jabber.org/protocol/muc#admin");
1921				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
1922					for(Element child : query.getChildren()) {
1923						if ("item".equals(child.getName())) {
1924							MucOptions.User user = AbstractParser.parseItem(conversation,child);
1925							if (!user.realJidMatchesAccount()) {
1926								conversation.getMucOptions().addUser(user);
1927								getAvatarService().clear(conversation);
1928								updateMucRosterUi();
1929								updateConversationUi();
1930							}
1931						}
1932					}
1933				} else {
1934					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not request affiliation "+affiliations[i]+" in "+conversation.getJid().toBareJid());
1935				}
1936				++i;
1937				if (i >= affiliations.length) {
1938					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": retrieved members for "+conversation.getJid().toBareJid()+": "+conversation.getMucOptions().getMembers());
1939				}
1940			}
1941		};
1942		for(String affiliation : affiliations) {
1943			sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
1944		}
1945		Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetching members for "+conversation.getName());
1946	}
1947
1948	public void providePasswordForMuc(Conversation conversation, String password) {
1949		if (conversation.getMode() == Conversation.MODE_MULTI) {
1950			conversation.getMucOptions().setPassword(password);
1951			if (conversation.getBookmark() != null) {
1952				if (respectAutojoin()) {
1953					conversation.getBookmark().setAutojoin(true);
1954				}
1955				pushBookmarks(conversation.getAccount());
1956			}
1957			databaseBackend.updateConversation(conversation);
1958			joinMuc(conversation);
1959		}
1960	}
1961
1962	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1963		final MucOptions options = conversation.getMucOptions();
1964		final Jid joinJid = options.createJoinJid(nick);
1965		if (options.online()) {
1966			Account account = conversation.getAccount();
1967			options.setOnRenameListener(new OnRenameListener() {
1968
1969				@Override
1970				public void onSuccess() {
1971					conversation.setContactJid(joinJid);
1972					databaseBackend.updateConversation(conversation);
1973					Bookmark bookmark = conversation.getBookmark();
1974					if (bookmark != null) {
1975						bookmark.setNick(nick);
1976						pushBookmarks(bookmark.getAccount());
1977					}
1978					callback.success(conversation);
1979				}
1980
1981				@Override
1982				public void onFailure() {
1983					callback.error(R.string.nick_in_use, conversation);
1984				}
1985			});
1986
1987			PresencePacket packet = new PresencePacket();
1988			packet.setTo(joinJid);
1989			packet.setFrom(conversation.getAccount().getJid());
1990
1991			String sig = account.getPgpSignature();
1992			if (sig != null) {
1993				packet.addChild("status").setContent("online");
1994				packet.addChild("x", "jabber:x:signed").setContent(sig);
1995			}
1996			sendPresencePacket(account, packet);
1997		} else {
1998			conversation.setContactJid(joinJid);
1999			databaseBackend.updateConversation(conversation);
2000			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2001				Bookmark bookmark = conversation.getBookmark();
2002				if (bookmark != null) {
2003					bookmark.setNick(nick);
2004					pushBookmarks(bookmark.getAccount());
2005				}
2006				joinMuc(conversation);
2007			}
2008		}
2009	}
2010
2011	public void leaveMuc(Conversation conversation) {
2012		leaveMuc(conversation, false);
2013	}
2014
2015	private void leaveMuc(Conversation conversation, boolean now) {
2016		Account account = conversation.getAccount();
2017		account.pendingConferenceJoins.remove(conversation);
2018		account.pendingConferenceLeaves.remove(conversation);
2019		if (account.getStatus() == Account.State.ONLINE || now) {
2020			PresencePacket packet = new PresencePacket();
2021			packet.setTo(conversation.getMucOptions().getSelf().getFullJid());
2022			packet.setFrom(conversation.getAccount().getJid());
2023			packet.setAttribute("type", "unavailable");
2024			sendPresencePacket(conversation.getAccount(), packet);
2025			conversation.getMucOptions().setOffline();
2026			conversation.deregisterWithBookmark();
2027			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
2028					+ ": leaving muc " + conversation.getJid());
2029		} else {
2030			account.pendingConferenceLeaves.add(conversation);
2031		}
2032	}
2033
2034	private String findConferenceServer(final Account account) {
2035		String server;
2036		if (account.getXmppConnection() != null) {
2037			server = account.getXmppConnection().getMucServer();
2038			if (server != null) {
2039				return server;
2040			}
2041		}
2042		for (Account other : getAccounts()) {
2043			if (other != account && other.getXmppConnection() != null) {
2044				server = other.getXmppConnection().getMucServer();
2045				if (server != null) {
2046					return server;
2047				}
2048			}
2049		}
2050		return null;
2051	}
2052
2053	public void createAdhocConference(final Account account,
2054									  final String subject,
2055									  final Iterable<Jid> jids,
2056									  final UiCallback<Conversation> callback) {
2057		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2058		if (account.getStatus() == Account.State.ONLINE) {
2059			try {
2060				String server = findConferenceServer(account);
2061				if (server == null) {
2062					if (callback != null) {
2063						callback.error(R.string.no_conference_server_found, null);
2064					}
2065					return;
2066				}
2067				final Jid jid = Jid.fromParts(new BigInteger(64, getRNG()).toString(Character.MAX_RADIX), server, null);
2068				final Conversation conversation = findOrCreateConversation(account, jid, true);
2069				joinMuc(conversation, new OnConferenceJoined() {
2070					@Override
2071					public void onConferenceJoined(final Conversation conversation) {
2072						pushConferenceConfiguration(conversation, IqGenerator.defaultRoomConfiguration(), new OnConferenceOptionsPushed() {
2073							@Override
2074							public void onPushSucceeded() {
2075								if (subject != null && !subject.trim().isEmpty()) {
2076									pushSubjectToConference(conversation, subject.trim());
2077								}
2078								for (Jid invite : jids) {
2079									invite(conversation, invite);
2080								}
2081								if (account.countPresences() > 1) {
2082									directInvite(conversation, account.getJid().toBareJid());
2083								}
2084								saveConversationAsBookmark(conversation, subject);
2085								if (callback != null) {
2086									callback.success(conversation);
2087								}
2088							}
2089
2090							@Override
2091							public void onPushFailed() {
2092								archiveConversation(conversation);
2093								if (callback != null) {
2094									callback.error(R.string.conference_creation_failed, conversation);
2095								}
2096							}
2097						});
2098					}
2099				});
2100			} catch (InvalidJidException e) {
2101				if (callback != null) {
2102					callback.error(R.string.conference_creation_failed, null);
2103				}
2104			}
2105		} else {
2106			if (callback != null) {
2107				callback.error(R.string.not_connected_try_again, null);
2108			}
2109		}
2110	}
2111
2112	public void fetchConferenceConfiguration(final Conversation conversation) {
2113		fetchConferenceConfiguration(conversation, null);
2114	}
2115
2116	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2117		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2118		request.setTo(conversation.getJid().toBareJid());
2119		request.query("http://jabber.org/protocol/disco#info");
2120		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2121			@Override
2122			public void onIqPacketReceived(Account account, IqPacket packet) {
2123				Element query = packet.findChild("query","http://jabber.org/protocol/disco#info");
2124				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2125					ArrayList<String> features = new ArrayList<>();
2126					for (Element child : query.getChildren()) {
2127						if (child != null && child.getName().equals("feature")) {
2128							String var = child.getAttribute("var");
2129							if (var != null) {
2130								features.add(var);
2131							}
2132						}
2133					}
2134					Element form = query.findChild("x", "jabber:x:data");
2135					if (form != null) {
2136						conversation.getMucOptions().updateFormData(Data.parse(form));
2137					}
2138					conversation.getMucOptions().updateFeatures(features);
2139					if (callback != null) {
2140						callback.onConferenceConfigurationFetched(conversation);
2141					}
2142					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetched muc configuration for "+conversation.getJid().toBareJid()+" - "+features.toString());
2143					updateConversationUi();
2144				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
2145					if (callback != null) {
2146						callback.onFetchFailed(conversation, packet.getError());
2147					}
2148				}
2149			}
2150		});
2151	}
2152
2153	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
2154		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2155		request.setTo(conversation.getJid().toBareJid());
2156		request.query("http://jabber.org/protocol/muc#owner");
2157		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2158			@Override
2159			public void onIqPacketReceived(Account account, IqPacket packet) {
2160				if (packet.getType() == IqPacket.TYPE.RESULT) {
2161					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
2162					for (Field field : data.getFields()) {
2163						if (options.containsKey(field.getFieldName())) {
2164							field.setValue(options.getString(field.getFieldName()));
2165						}
2166					}
2167					data.submit();
2168					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2169					set.setTo(conversation.getJid().toBareJid());
2170					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2171					sendIqPacket(account, set, new OnIqPacketReceived() {
2172						@Override
2173						public void onIqPacketReceived(Account account, IqPacket packet) {
2174							if (callback != null) {
2175								if (packet.getType() == IqPacket.TYPE.RESULT) {
2176									callback.onPushSucceeded();
2177								} else {
2178									callback.onPushFailed();
2179								}
2180							}
2181						}
2182					});
2183				} else {
2184					if (callback != null) {
2185						callback.onPushFailed();
2186					}
2187				}
2188			}
2189		});
2190	}
2191
2192	public void pushSubjectToConference(final Conversation conference, final String subject) {
2193		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2194		this.sendMessagePacket(conference.getAccount(), packet);
2195		final MucOptions mucOptions = conference.getMucOptions();
2196		final MucOptions.User self = mucOptions.getSelf();
2197		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2198			Bundle options = new Bundle();
2199			options.putString("muc#roomconfig_persistentroom", "1");
2200			this.pushConferenceConfiguration(conference, options, null);
2201		}
2202	}
2203
2204	public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2205		final Jid jid = user.toBareJid();
2206		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2207		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2208			@Override
2209			public void onIqPacketReceived(Account account, IqPacket packet) {
2210				if (packet.getType() == IqPacket.TYPE.RESULT) {
2211					conference.getMucOptions().changeAffiliation(jid, affiliation);
2212					getAvatarService().clear(conference);
2213					callback.onAffiliationChangedSuccessful(jid);
2214				} else {
2215					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2216				}
2217			}
2218		});
2219	}
2220
2221	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2222		List<Jid> jids = new ArrayList<>();
2223		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2224			if (user.getAffiliation() == before && user.getRealJid() != null) {
2225				jids.add(user.getRealJid());
2226			}
2227		}
2228		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2229		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2230	}
2231
2232	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2233		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2234		Log.d(Config.LOGTAG, request.toString());
2235		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2236			@Override
2237			public void onIqPacketReceived(Account account, IqPacket packet) {
2238				Log.d(Config.LOGTAG, packet.toString());
2239				if (packet.getType() == IqPacket.TYPE.RESULT) {
2240					callback.onRoleChangedSuccessful(nick);
2241				} else {
2242					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2243				}
2244			}
2245		});
2246	}
2247
2248	private void disconnect(Account account, boolean force) {
2249		if ((account.getStatus() == Account.State.ONLINE)
2250				|| (account.getStatus() == Account.State.DISABLED)) {
2251			if (!force) {
2252				List<Conversation> conversations = getConversations();
2253				for (Conversation conversation : conversations) {
2254					if (conversation.getAccount() == account) {
2255						if (conversation.getMode() == Conversation.MODE_MULTI) {
2256							leaveMuc(conversation, true);
2257						} else {
2258							if (conversation.endOtrIfNeeded()) {
2259								Log.d(Config.LOGTAG, account.getJid().toBareJid()
2260										+ ": ended otr session with "
2261										+ conversation.getJid());
2262							}
2263						}
2264					}
2265				}
2266				sendOfflinePresence(account);
2267			}
2268			account.getXmppConnection().disconnect(force);
2269		}
2270	}
2271
2272	@Override
2273	public IBinder onBind(Intent intent) {
2274		return mBinder;
2275	}
2276
2277	public void updateMessage(Message message) {
2278		databaseBackend.updateMessage(message);
2279		updateConversationUi();
2280	}
2281
2282	public void updateMessage(Message message, String uuid) {
2283		databaseBackend.updateMessage(message, uuid);
2284		updateConversationUi();
2285	}
2286
2287	protected void syncDirtyContacts(Account account) {
2288		for (Contact contact : account.getRoster().getContacts()) {
2289			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2290				pushContactToServer(contact);
2291			}
2292			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2293				deleteContactOnServer(contact);
2294			}
2295		}
2296	}
2297
2298	public void createContact(Contact contact) {
2299		boolean autoGrant = getPreferences().getBoolean("grant_new_contacts", true);
2300		if (autoGrant) {
2301			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2302			contact.setOption(Contact.Options.ASKING);
2303		}
2304		pushContactToServer(contact);
2305	}
2306
2307	public void onOtrSessionEstablished(Conversation conversation) {
2308		final Account account = conversation.getAccount();
2309		final Session otrSession = conversation.getOtrSession();
2310		Log.d(Config.LOGTAG,
2311				account.getJid().toBareJid() + " otr session established with "
2312						+ conversation.getJid() + "/"
2313						+ otrSession.getSessionID().getUserID());
2314		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2315
2316			@Override
2317			public void onMessageFound(Message message) {
2318				SessionID id = otrSession.getSessionID();
2319				try {
2320					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2321				} catch (InvalidJidException e) {
2322					return;
2323				}
2324				if (message.needsUploading()) {
2325					mJingleConnectionManager.createNewConnection(message);
2326				} else {
2327					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2328					if (outPacket != null) {
2329						mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2330						message.setStatus(Message.STATUS_SEND);
2331						databaseBackend.updateMessage(message);
2332						sendMessagePacket(account, outPacket);
2333					}
2334				}
2335				updateConversationUi();
2336			}
2337		});
2338	}
2339
2340	public boolean renewSymmetricKey(Conversation conversation) {
2341		Account account = conversation.getAccount();
2342		byte[] symmetricKey = new byte[32];
2343		this.mRandom.nextBytes(symmetricKey);
2344		Session otrSession = conversation.getOtrSession();
2345		if (otrSession != null) {
2346			MessagePacket packet = new MessagePacket();
2347			packet.setType(MessagePacket.TYPE_CHAT);
2348			packet.setFrom(account.getJid());
2349			MessageGenerator.addMessageHints(packet);
2350			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2351					+ otrSession.getSessionID().getUserID());
2352			try {
2353				packet.setBody(otrSession
2354						.transformSending(CryptoHelper.FILETRANSFER
2355								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
2356				sendMessagePacket(account, packet);
2357				conversation.setSymmetricKey(symmetricKey);
2358				return true;
2359			} catch (OtrException e) {
2360				return false;
2361			}
2362		}
2363		return false;
2364	}
2365
2366	public void pushContactToServer(final Contact contact) {
2367		contact.resetOption(Contact.Options.DIRTY_DELETE);
2368		contact.setOption(Contact.Options.DIRTY_PUSH);
2369		final Account account = contact.getAccount();
2370		if (account.getStatus() == Account.State.ONLINE) {
2371			final boolean ask = contact.getOption(Contact.Options.ASKING);
2372			final boolean sendUpdates = contact
2373					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2374					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2375			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2376			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
2377			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2378			if (sendUpdates) {
2379				sendPresencePacket(account,
2380						mPresenceGenerator.sendPresenceUpdatesTo(contact));
2381			}
2382			if (ask) {
2383				sendPresencePacket(account,
2384						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2385			}
2386		}
2387	}
2388
2389	public void publishAvatar(Account account, Uri image, UiCallback<Avatar> callback) {
2390		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2391		final int size = Config.AVATAR_SIZE;
2392		final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2393		if (avatar != null) {
2394			avatar.height = size;
2395			avatar.width = size;
2396			if (format.equals(Bitmap.CompressFormat.WEBP)) {
2397				avatar.type = "image/webp";
2398			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2399				avatar.type = "image/jpeg";
2400			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
2401				avatar.type = "image/png";
2402			}
2403			if (!getFileBackend().save(avatar)) {
2404				callback.error(R.string.error_saving_avatar, avatar);
2405				return;
2406			}
2407			publishAvatar(account, avatar, callback);
2408		} else {
2409			callback.error(R.string.error_publish_avatar_converting, null);
2410		}
2411	}
2412
2413	public void publishAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2414		final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2415		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2416
2417			@Override
2418			public void onIqPacketReceived(Account account, IqPacket result) {
2419				if (result.getType() == IqPacket.TYPE.RESULT) {
2420					final IqPacket packet = XmppConnectionService.this.mIqGenerator
2421							.publishAvatarMetadata(avatar);
2422					sendIqPacket(account, packet, new OnIqPacketReceived() {
2423						@Override
2424						public void onIqPacketReceived(Account account, IqPacket result) {
2425							if (result.getType() == IqPacket.TYPE.RESULT) {
2426								if (account.setAvatar(avatar.getFilename())) {
2427									getAvatarService().clear(account);
2428									databaseBackend.updateAccount(account);
2429								}
2430								if (callback != null) {
2431									callback.success(avatar);
2432								} else {
2433									Log.d(Config.LOGTAG,account.getJid().toBareJid()+": published avatar");
2434								}
2435							} else {
2436								if (callback != null) {
2437									callback.error(
2438											R.string.error_publish_avatar_server_reject,
2439											avatar);
2440								}
2441							}
2442						}
2443					});
2444				} else {
2445					if (callback != null) {
2446						callback.error(
2447								R.string.error_publish_avatar_server_reject,
2448								avatar);
2449					}
2450				}
2451			}
2452		});
2453	}
2454
2455	public void republishAvatarIfNeeded(Account account) {
2456		if (account.getAxolotlService().isPepBroken()) {
2457			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": skipping republication of avatar because pep is broken");
2458			return;
2459		}
2460		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2461		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2462
2463			private Avatar parseAvatar(IqPacket packet) {
2464				Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2465				if (pubsub != null) {
2466					Element items = pubsub.findChild("items");
2467					if (items != null) {
2468						return Avatar.parseMetadata(items);
2469					}
2470				}
2471				return null;
2472			}
2473
2474			private boolean errorIsItemNotFound(IqPacket packet) {
2475				Element error = packet.findChild("error");
2476				return packet.getType() == IqPacket.TYPE.ERROR
2477						&& error != null
2478						&& error.hasChild("item-not-found");
2479			}
2480
2481			@Override
2482			public void onIqPacketReceived(Account account, IqPacket packet) {
2483				if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2484					Avatar serverAvatar = parseAvatar(packet);
2485					if (serverAvatar == null && account.getAvatar() != null) {
2486						Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2487						if (avatar != null) {
2488							Log.d(Config.LOGTAG,account.getJid().toBareJid()+": avatar on server was null. republishing");
2489							publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2490						} else {
2491							Log.e(Config.LOGTAG, account.getJid().toBareJid()+": error rereading avatar");
2492						}
2493					}
2494				}
2495			}
2496		});
2497	}
2498
2499	public void fetchAvatar(Account account, Avatar avatar) {
2500		fetchAvatar(account, avatar, null);
2501	}
2502
2503	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2504		final String KEY = generateFetchKey(account, avatar);
2505		synchronized (this.mInProgressAvatarFetches) {
2506			if (!this.mInProgressAvatarFetches.contains(KEY)) {
2507				switch (avatar.origin) {
2508					case PEP:
2509						this.mInProgressAvatarFetches.add(KEY);
2510						fetchAvatarPep(account, avatar, callback);
2511						break;
2512					case VCARD:
2513						this.mInProgressAvatarFetches.add(KEY);
2514						fetchAvatarVcard(account, avatar, callback);
2515						break;
2516				}
2517			}
2518		}
2519	}
2520
2521	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2522		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2523		sendIqPacket(account, packet, new OnIqPacketReceived() {
2524
2525			@Override
2526			public void onIqPacketReceived(Account account, IqPacket result) {
2527				synchronized (mInProgressAvatarFetches) {
2528					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2529				}
2530				final String ERROR = account.getJid().toBareJid()
2531						+ ": fetching avatar for " + avatar.owner + " failed ";
2532				if (result.getType() == IqPacket.TYPE.RESULT) {
2533					avatar.image = mIqParser.avatarData(result);
2534					if (avatar.image != null) {
2535						if (getFileBackend().save(avatar)) {
2536							if (account.getJid().toBareJid().equals(avatar.owner)) {
2537								if (account.setAvatar(avatar.getFilename())) {
2538									databaseBackend.updateAccount(account);
2539								}
2540								getAvatarService().clear(account);
2541								updateConversationUi();
2542								updateAccountUi();
2543							} else {
2544								Contact contact = account.getRoster()
2545										.getContact(avatar.owner);
2546								contact.setAvatar(avatar);
2547								getAvatarService().clear(contact);
2548								updateConversationUi();
2549								updateRosterUi();
2550							}
2551							if (callback != null) {
2552								callback.success(avatar);
2553							}
2554							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2555									+ ": successfully fetched pep avatar for " + avatar.owner);
2556							return;
2557						}
2558					} else {
2559
2560						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2561					}
2562				} else {
2563					Element error = result.findChild("error");
2564					if (error == null) {
2565						Log.d(Config.LOGTAG, ERROR + "(server error)");
2566					} else {
2567						Log.d(Config.LOGTAG, ERROR + error.toString());
2568					}
2569				}
2570				if (callback != null) {
2571					callback.error(0, null);
2572				}
2573
2574			}
2575		});
2576	}
2577
2578	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2579		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2580		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2581			@Override
2582			public void onIqPacketReceived(Account account, IqPacket packet) {
2583				synchronized (mInProgressAvatarFetches) {
2584					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2585				}
2586				if (packet.getType() == IqPacket.TYPE.RESULT) {
2587					Element vCard = packet.findChild("vCard", "vcard-temp");
2588					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2589					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2590					if (image != null) {
2591						avatar.image = image;
2592						if (getFileBackend().save(avatar)) {
2593							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2594									+ ": successfully fetched vCard avatar for " + avatar.owner);
2595							if (avatar.owner.isBareJid()) {
2596								Contact contact = account.getRoster()
2597										.getContact(avatar.owner);
2598								contact.setAvatar(avatar);
2599								getAvatarService().clear(contact);
2600								updateConversationUi();
2601								updateRosterUi();
2602							} else {
2603								Conversation conversation = find(account, avatar.owner.toBareJid());
2604								if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
2605									MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
2606									if (user != null) {
2607										if (user.setAvatar(avatar)) {
2608											getAvatarService().clear(user);
2609											updateConversationUi();
2610											updateMucRosterUi();
2611										}
2612									}
2613								}
2614							}
2615						}
2616					}
2617				}
2618			}
2619		});
2620	}
2621
2622	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2623		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2624		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2625
2626			@Override
2627			public void onIqPacketReceived(Account account, IqPacket packet) {
2628				if (packet.getType() == IqPacket.TYPE.RESULT) {
2629					Element pubsub = packet.findChild("pubsub","http://jabber.org/protocol/pubsub");
2630					if (pubsub != null) {
2631						Element items = pubsub.findChild("items");
2632						if (items != null) {
2633							Avatar avatar = Avatar.parseMetadata(items);
2634							if (avatar != null) {
2635								avatar.owner = account.getJid().toBareJid();
2636								if (fileBackend.isAvatarCached(avatar)) {
2637									if (account.setAvatar(avatar.getFilename())) {
2638										databaseBackend.updateAccount(account);
2639									}
2640									getAvatarService().clear(account);
2641									callback.success(avatar);
2642								} else {
2643									fetchAvatarPep(account, avatar, callback);
2644								}
2645								return;
2646							}
2647						}
2648					}
2649				}
2650				callback.error(0, null);
2651			}
2652		});
2653	}
2654
2655	public void deleteContactOnServer(Contact contact) {
2656		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2657		contact.resetOption(Contact.Options.DIRTY_PUSH);
2658		contact.setOption(Contact.Options.DIRTY_DELETE);
2659		Account account = contact.getAccount();
2660		if (account.getStatus() == Account.State.ONLINE) {
2661			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2662			Element item = iq.query(Xmlns.ROSTER).addChild("item");
2663			item.setAttribute("jid", contact.getJid().toString());
2664			item.setAttribute("subscription", "remove");
2665			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2666		}
2667	}
2668
2669	public void updateConversation(Conversation conversation) {
2670		this.databaseBackend.updateConversation(conversation);
2671	}
2672
2673	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2674		synchronized (account) {
2675			XmppConnection connection = account.getXmppConnection();
2676			if (connection == null) {
2677				connection = createConnection(account);
2678				account.setXmppConnection(connection);
2679			} else {
2680				connection.interrupt();
2681			}
2682			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2683				if (!force) {
2684					disconnect(account, false);
2685				}
2686				Thread thread = new Thread(connection);
2687				connection.setInteractive(interactive);
2688				connection.prepareNewConnection();
2689				thread.start();
2690				scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2691			} else {
2692				disconnect(account, force);
2693				account.getRoster().clearPresences();
2694				connection.resetEverything();
2695				account.getAxolotlService().resetBrokenness();
2696			}
2697		}
2698	}
2699
2700	public void reconnectAccountInBackground(final Account account) {
2701		new Thread(new Runnable() {
2702			@Override
2703			public void run() {
2704				reconnectAccount(account, false, true);
2705			}
2706		}).start();
2707	}
2708
2709	public void invite(Conversation conversation, Jid contact) {
2710		Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
2711		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2712		sendMessagePacket(conversation.getAccount(), packet);
2713	}
2714
2715	public void directInvite(Conversation conversation, Jid jid) {
2716		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2717		sendMessagePacket(conversation.getAccount(), packet);
2718	}
2719
2720	public void resetSendingToWaiting(Account account) {
2721		for (Conversation conversation : getConversations()) {
2722			if (conversation.getAccount() == account) {
2723				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2724
2725					@Override
2726					public void onMessageFound(Message message) {
2727						markMessage(message, Message.STATUS_WAITING);
2728					}
2729				});
2730			}
2731		}
2732	}
2733
2734	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2735		if (uuid == null) {
2736			return null;
2737		}
2738		for (Conversation conversation : getConversations()) {
2739			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2740				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
2741				if (message != null) {
2742					markMessage(message, status);
2743				}
2744				return message;
2745			}
2746		}
2747		return null;
2748	}
2749
2750	public boolean markMessage(Conversation conversation, String uuid, int status) {
2751		if (uuid == null) {
2752			return false;
2753		} else {
2754			Message message = conversation.findSentMessageWithUuid(uuid);
2755			if (message != null) {
2756				markMessage(message, status);
2757				return true;
2758			} else {
2759				return false;
2760			}
2761		}
2762	}
2763
2764	public void markMessage(Message message, int status) {
2765		if (status == Message.STATUS_SEND_FAILED
2766				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2767				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2768			return;
2769		}
2770		message.setStatus(status);
2771		databaseBackend.updateMessage(message);
2772		updateConversationUi();
2773	}
2774
2775	public SharedPreferences getPreferences() {
2776		return PreferenceManager
2777				.getDefaultSharedPreferences(getApplicationContext());
2778	}
2779
2780	public boolean confirmMessages() {
2781		return getPreferences().getBoolean("confirm_messages", true);
2782	}
2783
2784	public boolean allowMessageCorrection() {
2785		return getPreferences().getBoolean("allow_message_correction", false);
2786	}
2787
2788	public boolean sendChatStates() {
2789		return getPreferences().getBoolean("chat_states", false);
2790	}
2791
2792	public boolean saveEncryptedMessages() {
2793		return !getPreferences().getBoolean("dont_save_encrypted", false);
2794	}
2795
2796	private boolean respectAutojoin() {
2797		return getPreferences().getBoolean("autojoin", true);
2798	}
2799
2800	public boolean indicateReceived() {
2801		return getPreferences().getBoolean("indicate_received", false);
2802	}
2803
2804	public boolean useTorToConnect() {
2805		return Config.FORCE_ORBOT || getPreferences().getBoolean("use_tor", false);
2806	}
2807
2808	public boolean showExtendedConnectionOptions() {
2809		return getPreferences().getBoolean("show_connection_options", false);
2810	}
2811
2812	public int unreadCount() {
2813		int count = 0;
2814		for (Conversation conversation : getConversations()) {
2815			count += conversation.unreadCount();
2816		}
2817		return count;
2818	}
2819
2820
2821	public void showErrorToastInUi(int resId) {
2822		if (mOnShowErrorToast != null) {
2823			mOnShowErrorToast.onShowErrorToast(resId);
2824		}
2825	}
2826
2827	public void updateConversationUi() {
2828		if (mOnConversationUpdate != null) {
2829			mOnConversationUpdate.onConversationUpdate();
2830		}
2831	}
2832
2833	public void updateAccountUi() {
2834		if (mOnAccountUpdate != null) {
2835			mOnAccountUpdate.onAccountUpdate();
2836		}
2837	}
2838
2839	public void updateRosterUi() {
2840		if (mOnRosterUpdate != null) {
2841			mOnRosterUpdate.onRosterUpdate();
2842		}
2843	}
2844
2845	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
2846		if (mOnCaptchaRequested != null) {
2847			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
2848			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
2849					(int) (captcha.getHeight() * metrics.scaledDensity), false);
2850
2851			mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
2852			return true;
2853		}
2854		return false;
2855	}
2856
2857	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2858		if (mOnUpdateBlocklist != null) {
2859			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2860		}
2861	}
2862
2863	public void updateMucRosterUi() {
2864		if (mOnMucRosterUpdate != null) {
2865			mOnMucRosterUpdate.onMucRosterUpdate();
2866		}
2867	}
2868
2869	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
2870		if (mOnKeyStatusUpdated != null) {
2871			mOnKeyStatusUpdated.onKeyStatusUpdated(report);
2872		}
2873	}
2874
2875	public Account findAccountByJid(final Jid accountJid) {
2876		for (Account account : this.accounts) {
2877			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2878				return account;
2879			}
2880		}
2881		return null;
2882	}
2883
2884	public Conversation findConversationByUuid(String uuid) {
2885		for (Conversation conversation : getConversations()) {
2886			if (conversation.getUuid().equals(uuid)) {
2887				return conversation;
2888			}
2889		}
2890		return null;
2891	}
2892
2893	public boolean markRead(final Conversation conversation) {
2894		mNotificationService.clear(conversation);
2895		final List<Message> readMessages = conversation.markRead();
2896		if (readMessages.size() > 0) {
2897			Runnable runnable = new Runnable() {
2898				@Override
2899				public void run() {
2900					for (Message message : readMessages) {
2901						databaseBackend.updateMessage(message);
2902					}
2903				}
2904			};
2905			mDatabaseExecutor.execute(runnable);
2906			updateUnreadCountBadge();
2907			return true;
2908		} else {
2909			return false;
2910		}
2911	}
2912
2913	public synchronized void updateUnreadCountBadge() {
2914		int count = unreadCount();
2915		if (unreadCount != count) {
2916			Log.d(Config.LOGTAG, "update unread count to " + count);
2917			if (count > 0) {
2918				ShortcutBadger.applyCount(getApplicationContext(), count);
2919			} else {
2920				ShortcutBadger.removeCount(getApplicationContext());
2921			}
2922			unreadCount = count;
2923		}
2924	}
2925
2926	public void sendReadMarker(final Conversation conversation) {
2927		final Message markable = conversation.getLatestMarkableMessage();
2928		if (this.markRead(conversation)) {
2929			updateConversationUi();
2930		}
2931		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2932			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2933			Account account = conversation.getAccount();
2934			final Jid to = markable.getCounterpart();
2935			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2936			this.sendMessagePacket(conversation.getAccount(), packet);
2937		}
2938	}
2939
2940	public SecureRandom getRNG() {
2941		return this.mRandom;
2942	}
2943
2944	public MemorizingTrustManager getMemorizingTrustManager() {
2945		return this.mMemorizingTrustManager;
2946	}
2947
2948	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2949		this.mMemorizingTrustManager = trustManager;
2950	}
2951
2952	public void updateMemorizingTrustmanager() {
2953		final MemorizingTrustManager tm;
2954		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2955		if (dontTrustSystemCAs) {
2956			tm = new MemorizingTrustManager(getApplicationContext(), null);
2957		} else {
2958			tm = new MemorizingTrustManager(getApplicationContext());
2959		}
2960		setMemorizingTrustManager(tm);
2961	}
2962
2963	public PowerManager getPowerManager() {
2964		return this.pm;
2965	}
2966
2967	public LruCache<String, Bitmap> getBitmapCache() {
2968		return this.mBitmapCache;
2969	}
2970
2971	public void syncRosterToDisk(final Account account) {
2972		Runnable runnable = new Runnable() {
2973
2974			@Override
2975			public void run() {
2976				databaseBackend.writeRoster(account.getRoster());
2977			}
2978		};
2979		mDatabaseExecutor.execute(runnable);
2980
2981	}
2982
2983	public List<String> getKnownHosts() {
2984		final List<String> hosts = new ArrayList<>();
2985		for (final Account account : getAccounts()) {
2986			if (!hosts.contains(account.getServer().toString())) {
2987				hosts.add(account.getServer().toString());
2988			}
2989			for (final Contact contact : account.getRoster().getContacts()) {
2990				if (contact.showInRoster()) {
2991					final String server = contact.getServer().toString();
2992					if (server != null && !hosts.contains(server)) {
2993						hosts.add(server);
2994					}
2995				}
2996			}
2997		}
2998		if(Config.DOMAIN_LOCK != null && !hosts.contains(Config.DOMAIN_LOCK)) {
2999			hosts.add(Config.DOMAIN_LOCK);
3000		}
3001		if(Config.MAGIC_CREATE_DOMAIN != null && !hosts.contains(Config.MAGIC_CREATE_DOMAIN)) {
3002			hosts.add(Config.MAGIC_CREATE_DOMAIN);
3003		}
3004		return hosts;
3005	}
3006
3007	public List<String> getKnownConferenceHosts() {
3008		final ArrayList<String> mucServers = new ArrayList<>();
3009		for (final Account account : accounts) {
3010			if (account.getXmppConnection() != null) {
3011				final String server = account.getXmppConnection().getMucServer();
3012				if (server != null && !mucServers.contains(server)) {
3013					mucServers.add(server);
3014				}
3015			}
3016		}
3017		return mucServers;
3018	}
3019
3020	public void sendMessagePacket(Account account, MessagePacket packet) {
3021		XmppConnection connection = account.getXmppConnection();
3022		if (connection != null) {
3023			connection.sendMessagePacket(packet);
3024		}
3025	}
3026
3027	public void sendPresencePacket(Account account, PresencePacket packet) {
3028		XmppConnection connection = account.getXmppConnection();
3029		if (connection != null) {
3030			connection.sendPresencePacket(packet);
3031		}
3032	}
3033
3034	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3035		final XmppConnection connection = account.getXmppConnection();
3036		if (connection != null) {
3037			IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3038			sendIqPacket(account, request, connection.registrationResponseListener);
3039		}
3040	}
3041
3042	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3043		final XmppConnection connection = account.getXmppConnection();
3044		if (connection != null) {
3045			connection.sendIqPacket(packet, callback);
3046		}
3047	}
3048
3049	public void sendPresence(final Account account) {
3050		PresencePacket packet;
3051		if (manuallyChangePresence()) {
3052			packet =  mPresenceGenerator.selfPresence(account, account.getPresenceStatus());
3053			String message = account.getPresenceStatusMessage();
3054			if (message != null && !message.isEmpty()) {
3055				packet.addChild(new Element("status").setContent(message));
3056			}
3057		} else {
3058			packet = mPresenceGenerator.selfPresence(account, getTargetPresence());
3059		}
3060		sendPresencePacket(account, packet);
3061	}
3062
3063	private void deactivateGracePeriod() {
3064		for(Account account : getAccounts()) {
3065			account.deactivateGracePeriod();
3066		}
3067	}
3068
3069	public void refreshAllPresences() {
3070		for (Account account : getAccounts()) {
3071			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3072				sendPresence(account);
3073			}
3074		}
3075	}
3076
3077	private void refreshAllGcmTokens() {
3078		for(Account account : getAccounts()) {
3079			if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3080				mPushManagementService.registerPushTokenOnServer(account);
3081			}
3082		}
3083	}
3084
3085	public void sendOfflinePresence(final Account account) {
3086		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3087	}
3088
3089	public MessageGenerator getMessageGenerator() {
3090		return this.mMessageGenerator;
3091	}
3092
3093	public PresenceGenerator getPresenceGenerator() {
3094		return this.mPresenceGenerator;
3095	}
3096
3097	public IqGenerator getIqGenerator() {
3098		return this.mIqGenerator;
3099	}
3100
3101	public IqParser getIqParser() {
3102		return this.mIqParser;
3103	}
3104
3105	public JingleConnectionManager getJingleConnectionManager() {
3106		return this.mJingleConnectionManager;
3107	}
3108
3109	public MessageArchiveService getMessageArchiveService() {
3110		return this.mMessageArchiveService;
3111	}
3112
3113	public List<Contact> findContacts(Jid jid) {
3114		ArrayList<Contact> contacts = new ArrayList<>();
3115		for (Account account : getAccounts()) {
3116			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3117				Contact contact = account.getRoster().getContactFromRoster(jid);
3118				if (contact != null) {
3119					contacts.add(contact);
3120				}
3121			}
3122		}
3123		return contacts;
3124	}
3125
3126	public Conversation findFirstMuc(Jid jid) {
3127		for(Conversation conversation : getConversations()) {
3128			if (conversation.getJid().toBareJid().equals(jid.toBareJid())
3129					&& conversation.getMode() == Conversation.MODE_MULTI) {
3130				return conversation;
3131			}
3132		}
3133		return null;
3134	}
3135
3136	public NotificationService getNotificationService() {
3137		return this.mNotificationService;
3138	}
3139
3140	public HttpConnectionManager getHttpConnectionManager() {
3141		return this.mHttpConnectionManager;
3142	}
3143
3144	public void resendFailedMessages(final Message message) {
3145		final Collection<Message> messages = new ArrayList<>();
3146		Message current = message;
3147		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3148			messages.add(current);
3149			if (current.mergeable(current.next())) {
3150				current = current.next();
3151			} else {
3152				break;
3153			}
3154		}
3155		for (final Message msg : messages) {
3156			msg.setTime(System.currentTimeMillis());
3157			markMessage(msg, Message.STATUS_WAITING);
3158			this.resendMessage(msg, false);
3159		}
3160	}
3161
3162	public void clearConversationHistory(final Conversation conversation) {
3163		conversation.clearMessages();
3164		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3165		conversation.setLastClearHistory(System.currentTimeMillis());
3166		Runnable runnable = new Runnable() {
3167			@Override
3168			public void run() {
3169				databaseBackend.deleteMessagesInConversation(conversation);
3170			}
3171		};
3172		mDatabaseExecutor.execute(runnable);
3173	}
3174
3175	public void sendBlockRequest(final Blockable blockable) {
3176		if (blockable != null && blockable.getBlockedJid() != null) {
3177			final Jid jid = blockable.getBlockedJid();
3178			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
3179
3180				@Override
3181				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3182					if (packet.getType() == IqPacket.TYPE.RESULT) {
3183						account.getBlocklist().add(jid);
3184						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3185					}
3186				}
3187			});
3188		}
3189	}
3190
3191	public void sendUnblockRequest(final Blockable blockable) {
3192		if (blockable != null && blockable.getJid() != null) {
3193			final Jid jid = blockable.getBlockedJid();
3194			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3195				@Override
3196				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3197					if (packet.getType() == IqPacket.TYPE.RESULT) {
3198						account.getBlocklist().remove(jid);
3199						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3200					}
3201				}
3202			});
3203		}
3204	}
3205
3206	public void publishDisplayName(Account account) {
3207		String displayName = account.getDisplayName();
3208		if (displayName != null && !displayName.isEmpty()) {
3209			IqPacket publish = mIqGenerator.publishNick(displayName);
3210			sendIqPacket(account, publish, new OnIqPacketReceived() {
3211				@Override
3212				public void onIqPacketReceived(Account account, IqPacket packet) {
3213					if (packet.getType() == IqPacket.TYPE.ERROR) {
3214						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not publish nick");
3215					}
3216				}
3217			});
3218		}
3219	}
3220
3221	public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
3222		ServiceDiscoveryResult result = discoCache.get(key);
3223		if (result != null) {
3224			return result;
3225		} else {
3226			result = databaseBackend.findDiscoveryResult(key.first, key.second);
3227			if (result != null) {
3228				discoCache.put(key, result);
3229			}
3230			return result;
3231		}
3232	}
3233
3234	public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3235		final Pair<String,String> key = new Pair<>(presence.getHash(), presence.getVer());
3236		ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3237		if (disco != null) {
3238			presence.setServiceDiscoveryResult(disco);
3239		} else {
3240			if (!account.inProgressDiscoFetches.contains(key)) {
3241				account.inProgressDiscoFetches.add(key);
3242				IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3243				request.setTo(jid);
3244				request.query("http://jabber.org/protocol/disco#info");
3245				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": making disco request for "+key.second+" to "+jid);
3246				sendIqPacket(account, request, new OnIqPacketReceived() {
3247					@Override
3248					public void onIqPacketReceived(Account account, IqPacket discoPacket) {
3249						if (discoPacket.getType() == IqPacket.TYPE.RESULT) {
3250							ServiceDiscoveryResult disco = new ServiceDiscoveryResult(discoPacket);
3251							if (presence.getVer().equals(disco.getVer())) {
3252								databaseBackend.insertDiscoveryResult(disco);
3253								injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco);
3254							} else {
3255								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco.getVer());
3256							}
3257						}
3258						account.inProgressDiscoFetches.remove(key);
3259					}
3260				});
3261			}
3262		}
3263	}
3264
3265	private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3266		for(Contact contact : roster.getContacts()) {
3267			for(Presence presence : contact.getPresences().getPresences().values()) {
3268				if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3269					presence.setServiceDiscoveryResult(disco);
3270				}
3271			}
3272		}
3273	}
3274
3275	public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3276		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3277		request.addChild("prefs","urn:xmpp:mam:0");
3278		sendIqPacket(account, request, new OnIqPacketReceived() {
3279			@Override
3280			public void onIqPacketReceived(Account account, IqPacket packet) {
3281				Element prefs = packet.findChild("prefs","urn:xmpp:mam:0");
3282				if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3283					callback.onPreferencesFetched(prefs);
3284				} else {
3285					callback.onPreferencesFetchFailed();
3286				}
3287			}
3288		});
3289	}
3290
3291	public PushManagementService getPushManagementService() {
3292		return mPushManagementService;
3293	}
3294
3295	public Account getPendingAccount() {
3296		Account pending = null;
3297		for(Account account : getAccounts()) {
3298			if (account.isOptionSet(Account.OPTION_REGISTER)) {
3299				pending = account;
3300			} else {
3301				return null;
3302			}
3303		}
3304		return pending;
3305	}
3306
3307	public void changeStatus(Account account, Presence.Status status, String statusMessage, boolean send) {
3308		if (!statusMessage.isEmpty()) {
3309			databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3310		}
3311		changeStatusReal(account, status, statusMessage, send);
3312	}
3313
3314	private void changeStatusReal(Account account, Presence.Status status, String statusMessage, boolean send) {
3315		account.setPresenceStatus(status);
3316		account.setPresenceStatusMessage(statusMessage);
3317		databaseBackend.updateAccount(account);
3318		if (!account.isOptionSet(Account.OPTION_DISABLED) && send) {
3319			sendPresence(account);
3320		}
3321	}
3322
3323	public void changeStatus(Presence.Status status, String statusMessage) {
3324		if (!statusMessage.isEmpty()) {
3325			databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3326		}
3327		for(Account account : getAccounts()) {
3328			changeStatusReal(account, status, statusMessage, true);
3329		}
3330	}
3331
3332	public List<PresenceTemplate> getPresenceTemplates(Account account) {
3333		List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3334		for(PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3335			if (!templates.contains(template)) {
3336				templates.add(0, template);
3337			}
3338		}
3339		return templates;
3340	}
3341
3342	public void saveConversationAsBookmark(Conversation conversation, String name) {
3343		Account account = conversation.getAccount();
3344		Bookmark bookmark = new Bookmark(account, conversation.getJid().toBareJid());
3345		if (!conversation.getJid().isBareJid()) {
3346			bookmark.setNick(conversation.getJid().getResourcepart());
3347		}
3348		if (name != null && !name.trim().isEmpty()) {
3349			bookmark.setBookmarkName(name.trim());
3350		}
3351		bookmark.setAutojoin(getPreferences().getBoolean("autojoin",true));
3352		account.getBookmarks().add(bookmark);
3353		pushBookmarks(account);
3354		conversation.setBookmark(bookmark);
3355	}
3356
3357	public interface OnMamPreferencesFetched {
3358		void onPreferencesFetched(Element prefs);
3359		void onPreferencesFetchFailed();
3360	}
3361
3362	public void pushMamPreferences(Account account, Element prefs) {
3363		IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3364		set.addChild(prefs);
3365		sendIqPacket(account, set, null);
3366	}
3367
3368	public interface OnAccountCreated {
3369		void onAccountCreated(Account account);
3370
3371		void informUser(int r);
3372	}
3373
3374	public interface OnMoreMessagesLoaded {
3375		void onMoreMessagesLoaded(int count, Conversation conversation);
3376
3377		void informUser(int r);
3378	}
3379
3380	public interface OnAccountPasswordChanged {
3381		void onPasswordChangeSucceeded();
3382
3383		void onPasswordChangeFailed();
3384	}
3385
3386	public interface OnAffiliationChanged {
3387		void onAffiliationChangedSuccessful(Jid jid);
3388
3389		void onAffiliationChangeFailed(Jid jid, int resId);
3390	}
3391
3392	public interface OnRoleChanged {
3393		void onRoleChangedSuccessful(String nick);
3394
3395		void onRoleChangeFailed(String nick, int resid);
3396	}
3397
3398	public interface OnConversationUpdate {
3399		void onConversationUpdate();
3400	}
3401
3402	public interface OnAccountUpdate {
3403		void onAccountUpdate();
3404	}
3405
3406	public interface OnCaptchaRequested {
3407		void onCaptchaRequested(Account account,
3408								String id,
3409								Data data,
3410								Bitmap captcha);
3411	}
3412
3413	public interface OnRosterUpdate {
3414		void onRosterUpdate();
3415	}
3416
3417	public interface OnMucRosterUpdate {
3418		void onMucRosterUpdate();
3419	}
3420
3421	public interface OnConferenceConfigurationFetched {
3422		void onConferenceConfigurationFetched(Conversation conversation);
3423
3424		void onFetchFailed(Conversation conversation, Element error);
3425	}
3426
3427	public interface OnConferenceJoined {
3428		void onConferenceJoined(Conversation conversation);
3429	}
3430
3431	public interface OnConferenceOptionsPushed {
3432		void onPushSucceeded();
3433
3434		void onPushFailed();
3435	}
3436
3437	public interface OnShowErrorToast {
3438		void onShowErrorToast(int resId);
3439	}
3440
3441	public class XmppConnectionBinder extends Binder {
3442		public XmppConnectionService getService() {
3443			return XmppConnectionService.this;
3444		}
3445	}
3446}