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