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