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