XmppConnectionService.java

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