XmppConnectionService.java

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