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