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