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