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