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