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 Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1356		for (final Conversation conversation : haystack) {
1357			if (conversation.getContact() == contact) {
1358				return conversation;
1359			}
1360		}
1361		return null;
1362	}
1363
1364	public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1365		if (jid == null) {
1366			return null;
1367		}
1368		for (final Conversation conversation : haystack) {
1369			if ((account == null || conversation.getAccount() == account)
1370					&& (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1371				return conversation;
1372			}
1373		}
1374		return null;
1375	}
1376
1377	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1378		return this.findOrCreateConversation(account, jid, muc, null);
1379	}
1380
1381	public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1382		synchronized (this.conversations) {
1383			Conversation conversation = find(account, jid);
1384			if (conversation != null) {
1385				return conversation;
1386			}
1387			conversation = databaseBackend.findConversation(account, jid);
1388			if (conversation != null) {
1389				conversation.setStatus(Conversation.STATUS_AVAILABLE);
1390				conversation.setAccount(account);
1391				if (muc) {
1392					conversation.setMode(Conversation.MODE_MULTI);
1393					conversation.setContactJid(jid);
1394				} else {
1395					conversation.setMode(Conversation.MODE_SINGLE);
1396					conversation.setContactJid(jid.toBareJid());
1397				}
1398				conversation.setNextEncryption(-1);
1399				conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1400				this.databaseBackend.updateConversation(conversation);
1401			} else {
1402				String conversationName;
1403				Contact contact = account.getRoster().getContact(jid);
1404				if (contact != null) {
1405					conversationName = contact.getDisplayName();
1406				} else {
1407					conversationName = jid.getLocalpart();
1408				}
1409				if (muc) {
1410					conversation = new Conversation(conversationName, account, jid,
1411							Conversation.MODE_MULTI);
1412				} else {
1413					conversation = new Conversation(conversationName, account, jid.toBareJid(),
1414							Conversation.MODE_SINGLE);
1415				}
1416				this.databaseBackend.createConversation(conversation);
1417			}
1418			if (account.getXmppConnection() != null
1419					&& account.getXmppConnection().getFeatures().mam()
1420					&& !muc) {
1421				if (query == null) {
1422					this.mMessageArchiveService.query(conversation);
1423				} else {
1424					if (query.getConversation() == null) {
1425						this.mMessageArchiveService.query(conversation, query.getStart());
1426					}
1427				}
1428			}
1429			checkDeletedFiles(conversation);
1430			this.conversations.add(conversation);
1431			updateConversationUi();
1432			return conversation;
1433		}
1434	}
1435
1436	public void archiveConversation(Conversation conversation) {
1437		getNotificationService().clear(conversation);
1438		conversation.setStatus(Conversation.STATUS_ARCHIVED);
1439		conversation.setNextEncryption(-1);
1440		synchronized (this.conversations) {
1441			if (conversation.getMode() == Conversation.MODE_MULTI) {
1442				if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1443					Bookmark bookmark = conversation.getBookmark();
1444					if (bookmark != null && bookmark.autojoin() && respectAutojoin()) {
1445						bookmark.setAutojoin(false);
1446						pushBookmarks(bookmark.getAccount());
1447					}
1448				}
1449				leaveMuc(conversation);
1450			} else {
1451				conversation.endOtrIfNeeded();
1452				if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1453					Log.d(Config.LOGTAG, "Canceling presence request from " + conversation.getJid().toString());
1454					sendPresencePacket(
1455							conversation.getAccount(),
1456							mPresenceGenerator.stopPresenceUpdatesTo(conversation.getContact())
1457					);
1458				}
1459			}
1460			this.databaseBackend.updateConversation(conversation);
1461			this.conversations.remove(conversation);
1462			updateConversationUi();
1463		}
1464	}
1465
1466	public void createAccount(final Account account) {
1467		account.initAccountServices(this);
1468		databaseBackend.createAccount(account);
1469		this.accounts.add(account);
1470		this.reconnectAccountInBackground(account);
1471		updateAccountUi();
1472	}
1473
1474	public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1475		new Thread(new Runnable() {
1476			@Override
1477			public void run() {
1478				try {
1479					X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1480					Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1481					if (findAccountByJid(info.first) == null) {
1482						Account account = new Account(info.first, "");
1483						account.setPrivateKeyAlias(alias);
1484						account.setOption(Account.OPTION_DISABLED, true);
1485						account.setDisplayName(info.second);
1486						createAccount(account);
1487						callback.onAccountCreated(account);
1488						if (Config.X509_VERIFICATION) {
1489							try {
1490								getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1491							} catch (CertificateException e) {
1492								callback.informUser(R.string.certificate_chain_is_not_trusted);
1493							}
1494						}
1495					} else {
1496						callback.informUser(R.string.account_already_exists);
1497					}
1498				} catch (Exception e) {
1499					e.printStackTrace();
1500					callback.informUser(R.string.unable_to_parse_certificate);
1501				}
1502			}
1503		}).start();
1504
1505	}
1506
1507	public void updateKeyInAccount(final Account account, final String alias) {
1508		Log.d(Config.LOGTAG, "update key in account " + alias);
1509		try {
1510			X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1511			Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1512			if (account.getJid().toBareJid().equals(info.first)) {
1513				account.setPrivateKeyAlias(alias);
1514				account.setDisplayName(info.second);
1515				databaseBackend.updateAccount(account);
1516				if (Config.X509_VERIFICATION) {
1517					try {
1518						getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1519					} catch (CertificateException e) {
1520						showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1521					}
1522					account.getAxolotlService().regenerateKeys(true);
1523				}
1524			} else {
1525				showErrorToastInUi(R.string.jid_does_not_match_certificate);
1526			}
1527		} catch (Exception e) {
1528			e.printStackTrace();
1529		}
1530	}
1531
1532	public void updateAccount(final Account account) {
1533		this.statusListener.onStatusChanged(account);
1534		databaseBackend.updateAccount(account);
1535		reconnectAccountInBackground(account);
1536		updateAccountUi();
1537		getNotificationService().updateErrorNotification();
1538	}
1539
1540	public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1541		final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1542		sendIqPacket(account, iq, new OnIqPacketReceived() {
1543			@Override
1544			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1545				if (packet.getType() == IqPacket.TYPE.RESULT) {
1546					account.setPassword(newPassword);
1547					account.setOption(Account.OPTION_MAGIC_CREATE, false);
1548					databaseBackend.updateAccount(account);
1549					callback.onPasswordChangeSucceeded();
1550				} else {
1551					callback.onPasswordChangeFailed();
1552				}
1553			}
1554		});
1555	}
1556
1557	public void deleteAccount(final Account account) {
1558		synchronized (this.conversations) {
1559			for (final Conversation conversation : conversations) {
1560				if (conversation.getAccount() == account) {
1561					if (conversation.getMode() == Conversation.MODE_MULTI) {
1562						leaveMuc(conversation);
1563					} else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1564						conversation.endOtrIfNeeded();
1565					}
1566					conversations.remove(conversation);
1567				}
1568			}
1569			if (account.getXmppConnection() != null) {
1570				new Thread(new Runnable() {
1571					@Override
1572					public void run() {
1573						disconnect(account, true);
1574					}
1575				});
1576			}
1577			Runnable runnable = new Runnable() {
1578				@Override
1579				public void run() {
1580					databaseBackend.deleteAccount(account);
1581				}
1582			};
1583			mDatabaseExecutor.execute(runnable);
1584			this.accounts.remove(account);
1585			updateAccountUi();
1586			getNotificationService().updateErrorNotification();
1587		}
1588	}
1589
1590	public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1591		synchronized (this) {
1592			this.mLastActivity = System.currentTimeMillis();
1593			if (checkListeners()) {
1594				switchToForeground();
1595			}
1596			this.mOnConversationUpdate = listener;
1597			this.mNotificationService.setIsInForeground(true);
1598			if (this.convChangedListenerCount < 2) {
1599				this.convChangedListenerCount++;
1600			}
1601		}
1602	}
1603
1604	public void removeOnConversationListChangedListener() {
1605		synchronized (this) {
1606			this.convChangedListenerCount--;
1607			if (this.convChangedListenerCount <= 0) {
1608				this.convChangedListenerCount = 0;
1609				this.mOnConversationUpdate = null;
1610				this.mNotificationService.setIsInForeground(false);
1611				if (checkListeners()) {
1612					switchToBackground();
1613				}
1614			}
1615		}
1616	}
1617
1618	public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1619		synchronized (this) {
1620			if (checkListeners()) {
1621				switchToForeground();
1622			}
1623			this.mOnShowErrorToast = onShowErrorToast;
1624			if (this.showErrorToastListenerCount < 2) {
1625				this.showErrorToastListenerCount++;
1626			}
1627		}
1628		this.mOnShowErrorToast = onShowErrorToast;
1629	}
1630
1631	public void removeOnShowErrorToastListener() {
1632		synchronized (this) {
1633			this.showErrorToastListenerCount--;
1634			if (this.showErrorToastListenerCount <= 0) {
1635				this.showErrorToastListenerCount = 0;
1636				this.mOnShowErrorToast = null;
1637				if (checkListeners()) {
1638					switchToBackground();
1639				}
1640			}
1641		}
1642	}
1643
1644	public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1645		synchronized (this) {
1646			if (checkListeners()) {
1647				switchToForeground();
1648			}
1649			this.mOnAccountUpdate = listener;
1650			if (this.accountChangedListenerCount < 2) {
1651				this.accountChangedListenerCount++;
1652			}
1653		}
1654	}
1655
1656	public void removeOnAccountListChangedListener() {
1657		synchronized (this) {
1658			this.accountChangedListenerCount--;
1659			if (this.accountChangedListenerCount <= 0) {
1660				this.mOnAccountUpdate = null;
1661				this.accountChangedListenerCount = 0;
1662				if (checkListeners()) {
1663					switchToBackground();
1664				}
1665			}
1666		}
1667	}
1668
1669	public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
1670		synchronized (this) {
1671			if (checkListeners()) {
1672				switchToForeground();
1673			}
1674			this.mOnCaptchaRequested = listener;
1675			if (this.captchaRequestedListenerCount < 2) {
1676				this.captchaRequestedListenerCount++;
1677			}
1678		}
1679	}
1680
1681	public void removeOnCaptchaRequestedListener() {
1682		synchronized (this) {
1683			this.captchaRequestedListenerCount--;
1684			if (this.captchaRequestedListenerCount <= 0) {
1685				this.mOnCaptchaRequested = null;
1686				this.captchaRequestedListenerCount = 0;
1687				if (checkListeners()) {
1688					switchToBackground();
1689				}
1690			}
1691		}
1692	}
1693
1694	public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1695		synchronized (this) {
1696			if (checkListeners()) {
1697				switchToForeground();
1698			}
1699			this.mOnRosterUpdate = listener;
1700			if (this.rosterChangedListenerCount < 2) {
1701				this.rosterChangedListenerCount++;
1702			}
1703		}
1704	}
1705
1706	public void removeOnRosterUpdateListener() {
1707		synchronized (this) {
1708			this.rosterChangedListenerCount--;
1709			if (this.rosterChangedListenerCount <= 0) {
1710				this.rosterChangedListenerCount = 0;
1711				this.mOnRosterUpdate = null;
1712				if (checkListeners()) {
1713					switchToBackground();
1714				}
1715			}
1716		}
1717	}
1718
1719	public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1720		synchronized (this) {
1721			if (checkListeners()) {
1722				switchToForeground();
1723			}
1724			this.mOnUpdateBlocklist = listener;
1725			if (this.updateBlocklistListenerCount < 2) {
1726				this.updateBlocklistListenerCount++;
1727			}
1728		}
1729	}
1730
1731	public void removeOnUpdateBlocklistListener() {
1732		synchronized (this) {
1733			this.updateBlocklistListenerCount--;
1734			if (this.updateBlocklistListenerCount <= 0) {
1735				this.updateBlocklistListenerCount = 0;
1736				this.mOnUpdateBlocklist = null;
1737				if (checkListeners()) {
1738					switchToBackground();
1739				}
1740			}
1741		}
1742	}
1743
1744	public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
1745		synchronized (this) {
1746			if (checkListeners()) {
1747				switchToForeground();
1748			}
1749			this.mOnKeyStatusUpdated = listener;
1750			if (this.keyStatusUpdatedListenerCount < 2) {
1751				this.keyStatusUpdatedListenerCount++;
1752			}
1753		}
1754	}
1755
1756	public void removeOnNewKeysAvailableListener() {
1757		synchronized (this) {
1758			this.keyStatusUpdatedListenerCount--;
1759			if (this.keyStatusUpdatedListenerCount <= 0) {
1760				this.keyStatusUpdatedListenerCount = 0;
1761				this.mOnKeyStatusUpdated = null;
1762				if (checkListeners()) {
1763					switchToBackground();
1764				}
1765			}
1766		}
1767	}
1768
1769	public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1770		synchronized (this) {
1771			if (checkListeners()) {
1772				switchToForeground();
1773			}
1774			this.mOnMucRosterUpdate = listener;
1775			if (this.mucRosterChangedListenerCount < 2) {
1776				this.mucRosterChangedListenerCount++;
1777			}
1778		}
1779	}
1780
1781	public void removeOnMucRosterUpdateListener() {
1782		synchronized (this) {
1783			this.mucRosterChangedListenerCount--;
1784			if (this.mucRosterChangedListenerCount <= 0) {
1785				this.mucRosterChangedListenerCount = 0;
1786				this.mOnMucRosterUpdate = null;
1787				if (checkListeners()) {
1788					switchToBackground();
1789				}
1790			}
1791		}
1792	}
1793
1794	public boolean checkListeners() {
1795		return (this.mOnAccountUpdate == null
1796				&& this.mOnConversationUpdate == null
1797				&& this.mOnRosterUpdate == null
1798				&& this.mOnCaptchaRequested == null
1799				&& this.mOnUpdateBlocklist == null
1800				&& this.mOnShowErrorToast == null
1801				&& this.mOnKeyStatusUpdated == null);
1802	}
1803
1804	private void switchToForeground() {
1805		final boolean broadcastLastActivity = broadcastLastActivity();
1806		for (Conversation conversation : getConversations()) {
1807			conversation.setIncomingChatState(ChatState.ACTIVE);
1808		}
1809		for (Account account : getAccounts()) {
1810			if (account.getStatus() == Account.State.ONLINE) {
1811				account.deactivateGracePeriod();
1812				final XmppConnection connection = account.getXmppConnection();
1813				if (connection != null ) {
1814					if (connection.getFeatures().csi()) {
1815						connection.sendActive();
1816					}
1817					if (broadcastLastActivity) {
1818						sendPresence(account, false); //send new presence but don't include idle because we are not
1819					}
1820				}
1821			}
1822		}
1823		Log.d(Config.LOGTAG, "app switched into foreground");
1824	}
1825
1826	private void switchToBackground() {
1827		final boolean broadcastLastActivity = broadcastLastActivity();
1828		for (Account account : getAccounts()) {
1829			if (account.getStatus() == Account.State.ONLINE) {
1830				XmppConnection connection = account.getXmppConnection();
1831				if (connection != null) {
1832					if (broadcastLastActivity) {
1833						sendPresence(account, broadcastLastActivity);
1834					}
1835					if (connection.getFeatures().csi()) {
1836						connection.sendInactive();
1837					}
1838					if (Config.CLOSE_TCP_WHEN_SWITCHING_TO_BACKGROUND && mPushManagementService.available(account)) {
1839						connection.waitForPush();
1840						cancelWakeUpCall(account.getUuid().hashCode());
1841					}
1842				}
1843			}
1844		}
1845		this.mNotificationService.setIsInForeground(false);
1846		Log.d(Config.LOGTAG, "app switched into background");
1847	}
1848
1849	private void connectMultiModeConversations(Account account) {
1850		List<Conversation> conversations = getConversations();
1851		for (Conversation conversation : conversations) {
1852			if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
1853				joinMuc(conversation);
1854			}
1855		}
1856	}
1857
1858	public void joinMuc(Conversation conversation) {
1859		joinMuc(conversation, null);
1860	}
1861
1862	private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
1863		Account account = conversation.getAccount();
1864		account.pendingConferenceJoins.remove(conversation);
1865		account.pendingConferenceLeaves.remove(conversation);
1866		if (account.getStatus() == Account.State.ONLINE) {
1867			conversation.resetMucOptions();
1868			if (onConferenceJoined != null) {
1869				conversation.getMucOptions().flagNoAutoPushConfiguration();
1870			}
1871			conversation.setHasMessagesLeftOnServer(false);
1872			fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
1873
1874				private void join(Conversation conversation) {
1875					Account account = conversation.getAccount();
1876					final MucOptions mucOptions = conversation.getMucOptions();
1877					final Jid joinJid = mucOptions.getSelf().getFullJid();
1878					Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1879					PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE);
1880					packet.setTo(joinJid);
1881					Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1882					if (conversation.getMucOptions().getPassword() != null) {
1883						x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1884					}
1885
1886					if (mucOptions.mamSupport()) {
1887						// Use MAM instead of the limited muc history to get history
1888						x.addChild("history").setAttribute("maxchars", "0");
1889					} else {
1890						// Fallback to muc history
1891						x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1892					}
1893					sendPresencePacket(account, packet);
1894					if (onConferenceJoined != null) {
1895						onConferenceJoined.onConferenceJoined(conversation);
1896					}
1897					if (!joinJid.equals(conversation.getJid())) {
1898						conversation.setContactJid(joinJid);
1899						databaseBackend.updateConversation(conversation);
1900					}
1901
1902					if (mucOptions.mamSupport()) {
1903						getMessageArchiveService().catchupMUC(conversation);
1904					}
1905					if (mucOptions.membersOnly() && mucOptions.nonanonymous()) {
1906						fetchConferenceMembers(conversation);
1907					}
1908					sendUnsentMessages(conversation);
1909				}
1910
1911				@Override
1912				public void onConferenceConfigurationFetched(Conversation conversation) {
1913					join(conversation);
1914				}
1915
1916				@Override
1917				public void onFetchFailed(final Conversation conversation, Element error) {
1918					join(conversation);
1919					fetchConferenceConfiguration(conversation);
1920				}
1921			});
1922			updateConversationUi();
1923		} else {
1924			account.pendingConferenceJoins.add(conversation);
1925			conversation.resetMucOptions();
1926			conversation.setHasMessagesLeftOnServer(false);
1927			updateConversationUi();
1928		}
1929	}
1930
1931	private void fetchConferenceMembers(final Conversation conversation) {
1932		final Account account = conversation.getAccount();
1933		final String[] affiliations = {"member","admin","owner"};
1934		OnIqPacketReceived callback = new OnIqPacketReceived() {
1935
1936			private int i = 0;
1937
1938			@Override
1939			public void onIqPacketReceived(Account account, IqPacket packet) {
1940
1941				Element query = packet.query("http://jabber.org/protocol/muc#admin");
1942				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
1943					for(Element child : query.getChildren()) {
1944						if ("item".equals(child.getName())) {
1945							MucOptions.User user = AbstractParser.parseItem(conversation,child);
1946							if (!user.realJidMatchesAccount()) {
1947								conversation.getMucOptions().addUser(user);
1948								getAvatarService().clear(conversation);
1949								updateMucRosterUi();
1950								updateConversationUi();
1951							}
1952						}
1953					}
1954				} else {
1955					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not request affiliation "+affiliations[i]+" in "+conversation.getJid().toBareJid());
1956				}
1957				++i;
1958				if (i >= affiliations.length) {
1959					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": retrieved members for "+conversation.getJid().toBareJid()+": "+conversation.getMucOptions().getMembers());
1960				}
1961			}
1962		};
1963		for(String affiliation : affiliations) {
1964			sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
1965		}
1966		Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetching members for "+conversation.getName());
1967	}
1968
1969	public void providePasswordForMuc(Conversation conversation, String password) {
1970		if (conversation.getMode() == Conversation.MODE_MULTI) {
1971			conversation.getMucOptions().setPassword(password);
1972			if (conversation.getBookmark() != null) {
1973				if (respectAutojoin()) {
1974					conversation.getBookmark().setAutojoin(true);
1975				}
1976				pushBookmarks(conversation.getAccount());
1977			}
1978			databaseBackend.updateConversation(conversation);
1979			joinMuc(conversation);
1980		}
1981	}
1982
1983	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1984		final MucOptions options = conversation.getMucOptions();
1985		final Jid joinJid = options.createJoinJid(nick);
1986		if (options.online()) {
1987			Account account = conversation.getAccount();
1988			options.setOnRenameListener(new OnRenameListener() {
1989
1990				@Override
1991				public void onSuccess() {
1992					conversation.setContactJid(joinJid);
1993					databaseBackend.updateConversation(conversation);
1994					Bookmark bookmark = conversation.getBookmark();
1995					if (bookmark != null) {
1996						bookmark.setNick(nick);
1997						pushBookmarks(bookmark.getAccount());
1998					}
1999					callback.success(conversation);
2000				}
2001
2002				@Override
2003				public void onFailure() {
2004					callback.error(R.string.nick_in_use, conversation);
2005				}
2006			});
2007
2008			PresencePacket packet = new PresencePacket();
2009			packet.setTo(joinJid);
2010			packet.setFrom(conversation.getAccount().getJid());
2011
2012			String sig = account.getPgpSignature();
2013			if (sig != null) {
2014				packet.addChild("status").setContent("online");
2015				packet.addChild("x", "jabber:x:signed").setContent(sig);
2016			}
2017			sendPresencePacket(account, packet);
2018		} else {
2019			conversation.setContactJid(joinJid);
2020			databaseBackend.updateConversation(conversation);
2021			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2022				Bookmark bookmark = conversation.getBookmark();
2023				if (bookmark != null) {
2024					bookmark.setNick(nick);
2025					pushBookmarks(bookmark.getAccount());
2026				}
2027				joinMuc(conversation);
2028			}
2029		}
2030	}
2031
2032	public void leaveMuc(Conversation conversation) {
2033		leaveMuc(conversation, false);
2034	}
2035
2036	private void leaveMuc(Conversation conversation, boolean now) {
2037		Account account = conversation.getAccount();
2038		account.pendingConferenceJoins.remove(conversation);
2039		account.pendingConferenceLeaves.remove(conversation);
2040		if (account.getStatus() == Account.State.ONLINE || now) {
2041			PresencePacket packet = new PresencePacket();
2042			packet.setTo(conversation.getMucOptions().getSelf().getFullJid());
2043			packet.setFrom(conversation.getAccount().getJid());
2044			packet.setAttribute("type", "unavailable");
2045			sendPresencePacket(conversation.getAccount(), packet);
2046			conversation.getMucOptions().setOffline();
2047			conversation.deregisterWithBookmark();
2048			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
2049					+ ": leaving muc " + conversation.getJid());
2050		} else {
2051			account.pendingConferenceLeaves.add(conversation);
2052		}
2053	}
2054
2055	private String findConferenceServer(final Account account) {
2056		String server;
2057		if (account.getXmppConnection() != null) {
2058			server = account.getXmppConnection().getMucServer();
2059			if (server != null) {
2060				return server;
2061			}
2062		}
2063		for (Account other : getAccounts()) {
2064			if (other != account && other.getXmppConnection() != null) {
2065				server = other.getXmppConnection().getMucServer();
2066				if (server != null) {
2067					return server;
2068				}
2069			}
2070		}
2071		return null;
2072	}
2073
2074	public void createAdhocConference(final Account account,
2075									  final String subject,
2076									  final Iterable<Jid> jids,
2077									  final UiCallback<Conversation> callback) {
2078		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2079		if (account.getStatus() == Account.State.ONLINE) {
2080			try {
2081				String server = findConferenceServer(account);
2082				if (server == null) {
2083					if (callback != null) {
2084						callback.error(R.string.no_conference_server_found, null);
2085					}
2086					return;
2087				}
2088				final Jid jid = Jid.fromParts(new BigInteger(64, getRNG()).toString(Character.MAX_RADIX), server, null);
2089				final Conversation conversation = findOrCreateConversation(account, jid, true);
2090				joinMuc(conversation, new OnConferenceJoined() {
2091					@Override
2092					public void onConferenceJoined(final Conversation conversation) {
2093						pushConferenceConfiguration(conversation, IqGenerator.defaultRoomConfiguration(), new OnConferenceOptionsPushed() {
2094							@Override
2095							public void onPushSucceeded() {
2096								if (subject != null && !subject.trim().isEmpty()) {
2097									pushSubjectToConference(conversation, subject.trim());
2098								}
2099								for (Jid invite : jids) {
2100									invite(conversation, invite);
2101								}
2102								if (account.countPresences() > 1) {
2103									directInvite(conversation, account.getJid().toBareJid());
2104								}
2105								saveConversationAsBookmark(conversation, subject);
2106								if (callback != null) {
2107									callback.success(conversation);
2108								}
2109							}
2110
2111							@Override
2112							public void onPushFailed() {
2113								archiveConversation(conversation);
2114								if (callback != null) {
2115									callback.error(R.string.conference_creation_failed, conversation);
2116								}
2117							}
2118						});
2119					}
2120				});
2121			} catch (InvalidJidException e) {
2122				if (callback != null) {
2123					callback.error(R.string.conference_creation_failed, null);
2124				}
2125			}
2126		} else {
2127			if (callback != null) {
2128				callback.error(R.string.not_connected_try_again, null);
2129			}
2130		}
2131	}
2132
2133	public void fetchConferenceConfiguration(final Conversation conversation) {
2134		fetchConferenceConfiguration(conversation, null);
2135	}
2136
2137	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2138		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2139		request.setTo(conversation.getJid().toBareJid());
2140		request.query("http://jabber.org/protocol/disco#info");
2141		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2142			@Override
2143			public void onIqPacketReceived(Account account, IqPacket packet) {
2144				Element query = packet.findChild("query","http://jabber.org/protocol/disco#info");
2145				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2146					ArrayList<String> features = new ArrayList<>();
2147					for (Element child : query.getChildren()) {
2148						if (child != null && child.getName().equals("feature")) {
2149							String var = child.getAttribute("var");
2150							if (var != null) {
2151								features.add(var);
2152							}
2153						}
2154					}
2155					Element form = query.findChild("x", "jabber:x:data");
2156					if (form != null) {
2157						conversation.getMucOptions().updateFormData(Data.parse(form));
2158					}
2159					conversation.getMucOptions().updateFeatures(features);
2160					if (callback != null) {
2161						callback.onConferenceConfigurationFetched(conversation);
2162					}
2163					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetched muc configuration for "+conversation.getJid().toBareJid()+" - "+features.toString());
2164					updateConversationUi();
2165				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
2166					if (callback != null) {
2167						callback.onFetchFailed(conversation, packet.getError());
2168					}
2169				}
2170			}
2171		});
2172	}
2173
2174	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
2175		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2176		request.setTo(conversation.getJid().toBareJid());
2177		request.query("http://jabber.org/protocol/muc#owner");
2178		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2179			@Override
2180			public void onIqPacketReceived(Account account, IqPacket packet) {
2181				if (packet.getType() == IqPacket.TYPE.RESULT) {
2182					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
2183					for (Field field : data.getFields()) {
2184						if (options.containsKey(field.getFieldName())) {
2185							field.setValue(options.getString(field.getFieldName()));
2186						}
2187					}
2188					data.submit();
2189					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2190					set.setTo(conversation.getJid().toBareJid());
2191					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2192					sendIqPacket(account, set, new OnIqPacketReceived() {
2193						@Override
2194						public void onIqPacketReceived(Account account, IqPacket packet) {
2195							if (callback != null) {
2196								if (packet.getType() == IqPacket.TYPE.RESULT) {
2197									callback.onPushSucceeded();
2198								} else {
2199									callback.onPushFailed();
2200								}
2201							}
2202						}
2203					});
2204				} else {
2205					if (callback != null) {
2206						callback.onPushFailed();
2207					}
2208				}
2209			}
2210		});
2211	}
2212
2213	public void pushSubjectToConference(final Conversation conference, final String subject) {
2214		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2215		this.sendMessagePacket(conference.getAccount(), packet);
2216		final MucOptions mucOptions = conference.getMucOptions();
2217		final MucOptions.User self = mucOptions.getSelf();
2218		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2219			Bundle options = new Bundle();
2220			options.putString("muc#roomconfig_persistentroom", "1");
2221			this.pushConferenceConfiguration(conference, options, null);
2222		}
2223	}
2224
2225	public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2226		final Jid jid = user.toBareJid();
2227		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2228		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2229			@Override
2230			public void onIqPacketReceived(Account account, IqPacket packet) {
2231				if (packet.getType() == IqPacket.TYPE.RESULT) {
2232					conference.getMucOptions().changeAffiliation(jid, affiliation);
2233					getAvatarService().clear(conference);
2234					callback.onAffiliationChangedSuccessful(jid);
2235				} else {
2236					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2237				}
2238			}
2239		});
2240	}
2241
2242	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2243		List<Jid> jids = new ArrayList<>();
2244		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2245			if (user.getAffiliation() == before && user.getRealJid() != null) {
2246				jids.add(user.getRealJid());
2247			}
2248		}
2249		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2250		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2251	}
2252
2253	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2254		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2255		Log.d(Config.LOGTAG, request.toString());
2256		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2257			@Override
2258			public void onIqPacketReceived(Account account, IqPacket packet) {
2259				Log.d(Config.LOGTAG, packet.toString());
2260				if (packet.getType() == IqPacket.TYPE.RESULT) {
2261					callback.onRoleChangedSuccessful(nick);
2262				} else {
2263					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2264				}
2265			}
2266		});
2267	}
2268
2269	private void disconnect(Account account, boolean force) {
2270		if ((account.getStatus() == Account.State.ONLINE)
2271				|| (account.getStatus() == Account.State.DISABLED)) {
2272			final XmppConnection connection = account.getXmppConnection();
2273			if (!force) {
2274				List<Conversation> conversations = getConversations();
2275				for (Conversation conversation : conversations) {
2276					if (conversation.getAccount() == account) {
2277						if (conversation.getMode() == Conversation.MODE_MULTI) {
2278							leaveMuc(conversation, true);
2279						} else {
2280							if (conversation.endOtrIfNeeded()) {
2281								Log.d(Config.LOGTAG, account.getJid().toBareJid()
2282										+ ": ended otr session with "
2283										+ conversation.getJid());
2284							}
2285						}
2286					}
2287				}
2288				sendOfflinePresence(account);
2289			}
2290			connection.disconnect(force);
2291		}
2292	}
2293
2294	@Override
2295	public IBinder onBind(Intent intent) {
2296		return mBinder;
2297	}
2298
2299	public void updateMessage(Message message) {
2300		databaseBackend.updateMessage(message);
2301		updateConversationUi();
2302	}
2303
2304	public void updateMessage(Message message, String uuid) {
2305		databaseBackend.updateMessage(message, uuid);
2306		updateConversationUi();
2307	}
2308
2309	protected void syncDirtyContacts(Account account) {
2310		for (Contact contact : account.getRoster().getContacts()) {
2311			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2312				pushContactToServer(contact);
2313			}
2314			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2315				deleteContactOnServer(contact);
2316			}
2317		}
2318	}
2319
2320	public void createContact(Contact contact) {
2321		boolean autoGrant = getPreferences().getBoolean("grant_new_contacts", true);
2322		if (autoGrant) {
2323			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2324			contact.setOption(Contact.Options.ASKING);
2325		}
2326		pushContactToServer(contact);
2327	}
2328
2329	public void onOtrSessionEstablished(Conversation conversation) {
2330		final Account account = conversation.getAccount();
2331		final Session otrSession = conversation.getOtrSession();
2332		Log.d(Config.LOGTAG,
2333				account.getJid().toBareJid() + " otr session established with "
2334						+ conversation.getJid() + "/"
2335						+ otrSession.getSessionID().getUserID());
2336		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2337
2338			@Override
2339			public void onMessageFound(Message message) {
2340				SessionID id = otrSession.getSessionID();
2341				try {
2342					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2343				} catch (InvalidJidException e) {
2344					return;
2345				}
2346				if (message.needsUploading()) {
2347					mJingleConnectionManager.createNewConnection(message);
2348				} else {
2349					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2350					if (outPacket != null) {
2351						mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2352						message.setStatus(Message.STATUS_SEND);
2353						databaseBackend.updateMessage(message);
2354						sendMessagePacket(account, outPacket);
2355					}
2356				}
2357				updateConversationUi();
2358			}
2359		});
2360	}
2361
2362	public boolean renewSymmetricKey(Conversation conversation) {
2363		Account account = conversation.getAccount();
2364		byte[] symmetricKey = new byte[32];
2365		this.mRandom.nextBytes(symmetricKey);
2366		Session otrSession = conversation.getOtrSession();
2367		if (otrSession != null) {
2368			MessagePacket packet = new MessagePacket();
2369			packet.setType(MessagePacket.TYPE_CHAT);
2370			packet.setFrom(account.getJid());
2371			MessageGenerator.addMessageHints(packet);
2372			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2373					+ otrSession.getSessionID().getUserID());
2374			try {
2375				packet.setBody(otrSession
2376						.transformSending(CryptoHelper.FILETRANSFER
2377								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
2378				sendMessagePacket(account, packet);
2379				conversation.setSymmetricKey(symmetricKey);
2380				return true;
2381			} catch (OtrException e) {
2382				return false;
2383			}
2384		}
2385		return false;
2386	}
2387
2388	public void pushContactToServer(final Contact contact) {
2389		contact.resetOption(Contact.Options.DIRTY_DELETE);
2390		contact.setOption(Contact.Options.DIRTY_PUSH);
2391		final Account account = contact.getAccount();
2392		if (account.getStatus() == Account.State.ONLINE) {
2393			final boolean ask = contact.getOption(Contact.Options.ASKING);
2394			final boolean sendUpdates = contact
2395					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2396					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2397			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2398			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
2399			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2400			if (sendUpdates) {
2401				sendPresencePacket(account,
2402						mPresenceGenerator.sendPresenceUpdatesTo(contact));
2403			}
2404			if (ask) {
2405				sendPresencePacket(account,
2406						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2407			}
2408		}
2409	}
2410
2411	public void publishAvatar(Account account, Uri image, UiCallback<Avatar> callback) {
2412		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2413		final int size = Config.AVATAR_SIZE;
2414		final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2415		if (avatar != null) {
2416			avatar.height = size;
2417			avatar.width = size;
2418			if (format.equals(Bitmap.CompressFormat.WEBP)) {
2419				avatar.type = "image/webp";
2420			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2421				avatar.type = "image/jpeg";
2422			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
2423				avatar.type = "image/png";
2424			}
2425			if (!getFileBackend().save(avatar)) {
2426				callback.error(R.string.error_saving_avatar, avatar);
2427				return;
2428			}
2429			publishAvatar(account, avatar, callback);
2430		} else {
2431			callback.error(R.string.error_publish_avatar_converting, null);
2432		}
2433	}
2434
2435	public void publishAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2436		final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2437		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2438
2439			@Override
2440			public void onIqPacketReceived(Account account, IqPacket result) {
2441				if (result.getType() == IqPacket.TYPE.RESULT) {
2442					final IqPacket packet = XmppConnectionService.this.mIqGenerator
2443							.publishAvatarMetadata(avatar);
2444					sendIqPacket(account, packet, new OnIqPacketReceived() {
2445						@Override
2446						public void onIqPacketReceived(Account account, IqPacket result) {
2447							if (result.getType() == IqPacket.TYPE.RESULT) {
2448								if (account.setAvatar(avatar.getFilename())) {
2449									getAvatarService().clear(account);
2450									databaseBackend.updateAccount(account);
2451								}
2452								if (callback != null) {
2453									callback.success(avatar);
2454								} else {
2455									Log.d(Config.LOGTAG,account.getJid().toBareJid()+": published avatar");
2456								}
2457							} else {
2458								if (callback != null) {
2459									callback.error(
2460											R.string.error_publish_avatar_server_reject,
2461											avatar);
2462								}
2463							}
2464						}
2465					});
2466				} else {
2467					if (callback != null) {
2468						callback.error(
2469								R.string.error_publish_avatar_server_reject,
2470								avatar);
2471					}
2472				}
2473			}
2474		});
2475	}
2476
2477	public void republishAvatarIfNeeded(Account account) {
2478		if (account.getAxolotlService().isPepBroken()) {
2479			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": skipping republication of avatar because pep is broken");
2480			return;
2481		}
2482		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2483		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2484
2485			private Avatar parseAvatar(IqPacket packet) {
2486				Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2487				if (pubsub != null) {
2488					Element items = pubsub.findChild("items");
2489					if (items != null) {
2490						return Avatar.parseMetadata(items);
2491					}
2492				}
2493				return null;
2494			}
2495
2496			private boolean errorIsItemNotFound(IqPacket packet) {
2497				Element error = packet.findChild("error");
2498				return packet.getType() == IqPacket.TYPE.ERROR
2499						&& error != null
2500						&& error.hasChild("item-not-found");
2501			}
2502
2503			@Override
2504			public void onIqPacketReceived(Account account, IqPacket packet) {
2505				if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2506					Avatar serverAvatar = parseAvatar(packet);
2507					if (serverAvatar == null && account.getAvatar() != null) {
2508						Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2509						if (avatar != null) {
2510							Log.d(Config.LOGTAG,account.getJid().toBareJid()+": avatar on server was null. republishing");
2511							publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2512						} else {
2513							Log.e(Config.LOGTAG, account.getJid().toBareJid()+": error rereading avatar");
2514						}
2515					}
2516				}
2517			}
2518		});
2519	}
2520
2521	public void fetchAvatar(Account account, Avatar avatar) {
2522		fetchAvatar(account, avatar, null);
2523	}
2524
2525	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2526		final String KEY = generateFetchKey(account, avatar);
2527		synchronized (this.mInProgressAvatarFetches) {
2528			if (!this.mInProgressAvatarFetches.contains(KEY)) {
2529				switch (avatar.origin) {
2530					case PEP:
2531						this.mInProgressAvatarFetches.add(KEY);
2532						fetchAvatarPep(account, avatar, callback);
2533						break;
2534					case VCARD:
2535						this.mInProgressAvatarFetches.add(KEY);
2536						fetchAvatarVcard(account, avatar, callback);
2537						break;
2538				}
2539			}
2540		}
2541	}
2542
2543	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2544		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2545		sendIqPacket(account, packet, new OnIqPacketReceived() {
2546
2547			@Override
2548			public void onIqPacketReceived(Account account, IqPacket result) {
2549				synchronized (mInProgressAvatarFetches) {
2550					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2551				}
2552				final String ERROR = account.getJid().toBareJid()
2553						+ ": fetching avatar for " + avatar.owner + " failed ";
2554				if (result.getType() == IqPacket.TYPE.RESULT) {
2555					avatar.image = mIqParser.avatarData(result);
2556					if (avatar.image != null) {
2557						if (getFileBackend().save(avatar)) {
2558							if (account.getJid().toBareJid().equals(avatar.owner)) {
2559								if (account.setAvatar(avatar.getFilename())) {
2560									databaseBackend.updateAccount(account);
2561								}
2562								getAvatarService().clear(account);
2563								updateConversationUi();
2564								updateAccountUi();
2565							} else {
2566								Contact contact = account.getRoster()
2567										.getContact(avatar.owner);
2568								contact.setAvatar(avatar);
2569								getAvatarService().clear(contact);
2570								updateConversationUi();
2571								updateRosterUi();
2572							}
2573							if (callback != null) {
2574								callback.success(avatar);
2575							}
2576							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2577									+ ": successfully fetched pep avatar for " + avatar.owner);
2578							return;
2579						}
2580					} else {
2581
2582						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2583					}
2584				} else {
2585					Element error = result.findChild("error");
2586					if (error == null) {
2587						Log.d(Config.LOGTAG, ERROR + "(server error)");
2588					} else {
2589						Log.d(Config.LOGTAG, ERROR + error.toString());
2590					}
2591				}
2592				if (callback != null) {
2593					callback.error(0, null);
2594				}
2595
2596			}
2597		});
2598	}
2599
2600	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2601		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2602		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2603			@Override
2604			public void onIqPacketReceived(Account account, IqPacket packet) {
2605				synchronized (mInProgressAvatarFetches) {
2606					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2607				}
2608				if (packet.getType() == IqPacket.TYPE.RESULT) {
2609					Element vCard = packet.findChild("vCard", "vcard-temp");
2610					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2611					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2612					if (image != null) {
2613						avatar.image = image;
2614						if (getFileBackend().save(avatar)) {
2615							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2616									+ ": successfully fetched vCard avatar for " + avatar.owner);
2617							if (avatar.owner.isBareJid()) {
2618								Contact contact = account.getRoster()
2619										.getContact(avatar.owner);
2620								contact.setAvatar(avatar);
2621								getAvatarService().clear(contact);
2622								updateConversationUi();
2623								updateRosterUi();
2624							} else {
2625								Conversation conversation = find(account, avatar.owner.toBareJid());
2626								if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
2627									MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
2628									if (user != null) {
2629										if (user.setAvatar(avatar)) {
2630											getAvatarService().clear(user);
2631											updateConversationUi();
2632											updateMucRosterUi();
2633										}
2634									}
2635								}
2636							}
2637						}
2638					}
2639				}
2640			}
2641		});
2642	}
2643
2644	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2645		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2646		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2647
2648			@Override
2649			public void onIqPacketReceived(Account account, IqPacket packet) {
2650				if (packet.getType() == IqPacket.TYPE.RESULT) {
2651					Element pubsub = packet.findChild("pubsub","http://jabber.org/protocol/pubsub");
2652					if (pubsub != null) {
2653						Element items = pubsub.findChild("items");
2654						if (items != null) {
2655							Avatar avatar = Avatar.parseMetadata(items);
2656							if (avatar != null) {
2657								avatar.owner = account.getJid().toBareJid();
2658								if (fileBackend.isAvatarCached(avatar)) {
2659									if (account.setAvatar(avatar.getFilename())) {
2660										databaseBackend.updateAccount(account);
2661									}
2662									getAvatarService().clear(account);
2663									callback.success(avatar);
2664								} else {
2665									fetchAvatarPep(account, avatar, callback);
2666								}
2667								return;
2668							}
2669						}
2670					}
2671				}
2672				callback.error(0, null);
2673			}
2674		});
2675	}
2676
2677	public void deleteContactOnServer(Contact contact) {
2678		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2679		contact.resetOption(Contact.Options.DIRTY_PUSH);
2680		contact.setOption(Contact.Options.DIRTY_DELETE);
2681		Account account = contact.getAccount();
2682		if (account.getStatus() == Account.State.ONLINE) {
2683			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2684			Element item = iq.query(Xmlns.ROSTER).addChild("item");
2685			item.setAttribute("jid", contact.getJid().toString());
2686			item.setAttribute("subscription", "remove");
2687			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2688		}
2689	}
2690
2691	public void updateConversation(Conversation conversation) {
2692		this.databaseBackend.updateConversation(conversation);
2693	}
2694
2695	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2696		synchronized (account) {
2697			XmppConnection connection = account.getXmppConnection();
2698			if (connection == null) {
2699				connection = createConnection(account);
2700				account.setXmppConnection(connection);
2701			} else {
2702				connection.interrupt();
2703			}
2704			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2705				if (!force) {
2706					disconnect(account, false);
2707				}
2708				Thread thread = new Thread(connection);
2709				connection.setInteractive(interactive);
2710				connection.prepareNewConnection();
2711				thread.start();
2712				scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2713			} else {
2714				disconnect(account, force);
2715				account.getRoster().clearPresences();
2716				connection.resetEverything();
2717				account.getAxolotlService().resetBrokenness();
2718			}
2719		}
2720	}
2721
2722	public void reconnectAccountInBackground(final Account account) {
2723		new Thread(new Runnable() {
2724			@Override
2725			public void run() {
2726				reconnectAccount(account, false, true);
2727			}
2728		}).start();
2729	}
2730
2731	public void invite(Conversation conversation, Jid contact) {
2732		Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
2733		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2734		sendMessagePacket(conversation.getAccount(), packet);
2735	}
2736
2737	public void directInvite(Conversation conversation, Jid jid) {
2738		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2739		sendMessagePacket(conversation.getAccount(), packet);
2740	}
2741
2742	public void resetSendingToWaiting(Account account) {
2743		for (Conversation conversation : getConversations()) {
2744			if (conversation.getAccount() == account) {
2745				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2746
2747					@Override
2748					public void onMessageFound(Message message) {
2749						markMessage(message, Message.STATUS_WAITING);
2750					}
2751				});
2752			}
2753		}
2754	}
2755
2756	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2757		if (uuid == null) {
2758			return null;
2759		}
2760		for (Conversation conversation : getConversations()) {
2761			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2762				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
2763				if (message != null) {
2764					markMessage(message, status);
2765				}
2766				return message;
2767			}
2768		}
2769		return null;
2770	}
2771
2772	public boolean markMessage(Conversation conversation, String uuid, int status) {
2773		if (uuid == null) {
2774			return false;
2775		} else {
2776			Message message = conversation.findSentMessageWithUuid(uuid);
2777			if (message != null) {
2778				markMessage(message, status);
2779				return true;
2780			} else {
2781				return false;
2782			}
2783		}
2784	}
2785
2786	public void markMessage(Message message, int status) {
2787		if (status == Message.STATUS_SEND_FAILED
2788				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2789				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2790			return;
2791		}
2792		message.setStatus(status);
2793		databaseBackend.updateMessage(message);
2794		updateConversationUi();
2795	}
2796
2797	public SharedPreferences getPreferences() {
2798		return PreferenceManager
2799				.getDefaultSharedPreferences(getApplicationContext());
2800	}
2801
2802	public boolean confirmMessages() {
2803		return getPreferences().getBoolean("confirm_messages", true);
2804	}
2805
2806	public boolean allowMessageCorrection() {
2807		return getPreferences().getBoolean("allow_message_correction", false);
2808	}
2809
2810	public boolean sendChatStates() {
2811		return getPreferences().getBoolean("chat_states", false);
2812	}
2813
2814	public boolean saveEncryptedMessages() {
2815		return !getPreferences().getBoolean("dont_save_encrypted", false);
2816	}
2817
2818	private boolean respectAutojoin() {
2819		return getPreferences().getBoolean("autojoin", true);
2820	}
2821
2822	public boolean indicateReceived() {
2823		return getPreferences().getBoolean("indicate_received", false);
2824	}
2825
2826	public boolean useTorToConnect() {
2827		return Config.FORCE_ORBOT || getPreferences().getBoolean("use_tor", false);
2828	}
2829
2830	public boolean showExtendedConnectionOptions() {
2831		return getPreferences().getBoolean("show_connection_options", false);
2832	}
2833
2834	public boolean broadcastLastActivity() {
2835		return getPreferences().getBoolean("last_activity", false);
2836	}
2837
2838	public int unreadCount() {
2839		int count = 0;
2840		for (Conversation conversation : getConversations()) {
2841			count += conversation.unreadCount();
2842		}
2843		return count;
2844	}
2845
2846
2847	public void showErrorToastInUi(int resId) {
2848		if (mOnShowErrorToast != null) {
2849			mOnShowErrorToast.onShowErrorToast(resId);
2850		}
2851	}
2852
2853	public void updateConversationUi() {
2854		if (mOnConversationUpdate != null) {
2855			mOnConversationUpdate.onConversationUpdate();
2856		}
2857	}
2858
2859	public void updateAccountUi() {
2860		if (mOnAccountUpdate != null) {
2861			mOnAccountUpdate.onAccountUpdate();
2862		}
2863	}
2864
2865	public void updateRosterUi() {
2866		if (mOnRosterUpdate != null) {
2867			mOnRosterUpdate.onRosterUpdate();
2868		}
2869	}
2870
2871	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
2872		if (mOnCaptchaRequested != null) {
2873			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
2874			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
2875					(int) (captcha.getHeight() * metrics.scaledDensity), false);
2876
2877			mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
2878			return true;
2879		}
2880		return false;
2881	}
2882
2883	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2884		if (mOnUpdateBlocklist != null) {
2885			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2886		}
2887	}
2888
2889	public void updateMucRosterUi() {
2890		if (mOnMucRosterUpdate != null) {
2891			mOnMucRosterUpdate.onMucRosterUpdate();
2892		}
2893	}
2894
2895	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
2896		if (mOnKeyStatusUpdated != null) {
2897			mOnKeyStatusUpdated.onKeyStatusUpdated(report);
2898		}
2899	}
2900
2901	public Account findAccountByJid(final Jid accountJid) {
2902		for (Account account : this.accounts) {
2903			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2904				return account;
2905			}
2906		}
2907		return null;
2908	}
2909
2910	public Conversation findConversationByUuid(String uuid) {
2911		for (Conversation conversation : getConversations()) {
2912			if (conversation.getUuid().equals(uuid)) {
2913				return conversation;
2914			}
2915		}
2916		return null;
2917	}
2918
2919	public boolean markRead(final Conversation conversation) {
2920		mNotificationService.clear(conversation);
2921		final List<Message> readMessages = conversation.markRead();
2922		if (readMessages.size() > 0) {
2923			Runnable runnable = new Runnable() {
2924				@Override
2925				public void run() {
2926					for (Message message : readMessages) {
2927						databaseBackend.updateMessage(message);
2928					}
2929				}
2930			};
2931			mDatabaseExecutor.execute(runnable);
2932			updateUnreadCountBadge();
2933			return true;
2934		} else {
2935			return false;
2936		}
2937	}
2938
2939	public synchronized void updateUnreadCountBadge() {
2940		int count = unreadCount();
2941		if (unreadCount != count) {
2942			Log.d(Config.LOGTAG, "update unread count to " + count);
2943			if (count > 0) {
2944				ShortcutBadger.applyCount(getApplicationContext(), count);
2945			} else {
2946				ShortcutBadger.removeCount(getApplicationContext());
2947			}
2948			unreadCount = count;
2949		}
2950	}
2951
2952	public void sendReadMarker(final Conversation conversation) {
2953		final Message markable = conversation.getLatestMarkableMessage();
2954		if (this.markRead(conversation)) {
2955			updateConversationUi();
2956		}
2957		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2958			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2959			Account account = conversation.getAccount();
2960			final Jid to = markable.getCounterpart();
2961			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2962			this.sendMessagePacket(conversation.getAccount(), packet);
2963		}
2964	}
2965
2966	public SecureRandom getRNG() {
2967		return this.mRandom;
2968	}
2969
2970	public MemorizingTrustManager getMemorizingTrustManager() {
2971		return this.mMemorizingTrustManager;
2972	}
2973
2974	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2975		this.mMemorizingTrustManager = trustManager;
2976	}
2977
2978	public void updateMemorizingTrustmanager() {
2979		final MemorizingTrustManager tm;
2980		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2981		if (dontTrustSystemCAs) {
2982			tm = new MemorizingTrustManager(getApplicationContext(), null);
2983		} else {
2984			tm = new MemorizingTrustManager(getApplicationContext());
2985		}
2986		setMemorizingTrustManager(tm);
2987	}
2988
2989	public PowerManager getPowerManager() {
2990		return this.pm;
2991	}
2992
2993	public LruCache<String, Bitmap> getBitmapCache() {
2994		return this.mBitmapCache;
2995	}
2996
2997	public void syncRosterToDisk(final Account account) {
2998		Runnable runnable = new Runnable() {
2999
3000			@Override
3001			public void run() {
3002				databaseBackend.writeRoster(account.getRoster());
3003			}
3004		};
3005		mDatabaseExecutor.execute(runnable);
3006
3007	}
3008
3009	public List<String> getKnownHosts() {
3010		final List<String> hosts = new ArrayList<>();
3011		for (final Account account : getAccounts()) {
3012			if (!hosts.contains(account.getServer().toString())) {
3013				hosts.add(account.getServer().toString());
3014			}
3015			for (final Contact contact : account.getRoster().getContacts()) {
3016				if (contact.showInRoster()) {
3017					final String server = contact.getServer().toString();
3018					if (server != null && !hosts.contains(server)) {
3019						hosts.add(server);
3020					}
3021				}
3022			}
3023		}
3024		if(Config.DOMAIN_LOCK != null && !hosts.contains(Config.DOMAIN_LOCK)) {
3025			hosts.add(Config.DOMAIN_LOCK);
3026		}
3027		if(Config.MAGIC_CREATE_DOMAIN != null && !hosts.contains(Config.MAGIC_CREATE_DOMAIN)) {
3028			hosts.add(Config.MAGIC_CREATE_DOMAIN);
3029		}
3030		return hosts;
3031	}
3032
3033	public List<String> getKnownConferenceHosts() {
3034		final ArrayList<String> mucServers = new ArrayList<>();
3035		for (final Account account : accounts) {
3036			if (account.getXmppConnection() != null) {
3037				final String server = account.getXmppConnection().getMucServer();
3038				if (server != null && !mucServers.contains(server)) {
3039					mucServers.add(server);
3040				}
3041			}
3042		}
3043		return mucServers;
3044	}
3045
3046	public void sendMessagePacket(Account account, MessagePacket packet) {
3047		XmppConnection connection = account.getXmppConnection();
3048		if (connection != null) {
3049			connection.sendMessagePacket(packet);
3050		}
3051	}
3052
3053	public void sendPresencePacket(Account account, PresencePacket packet) {
3054		XmppConnection connection = account.getXmppConnection();
3055		if (connection != null) {
3056			connection.sendPresencePacket(packet);
3057		}
3058	}
3059
3060	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3061		final XmppConnection connection = account.getXmppConnection();
3062		if (connection != null) {
3063			IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3064			sendIqPacket(account, request, connection.registrationResponseListener);
3065		}
3066	}
3067
3068	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3069		final XmppConnection connection = account.getXmppConnection();
3070		if (connection != null) {
3071			connection.sendIqPacket(packet, callback);
3072		}
3073	}
3074
3075	public void sendPresence(final Account account) {
3076		sendPresence(account, checkListeners() && broadcastLastActivity());
3077	}
3078
3079	private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3080		PresencePacket packet;
3081		if (manuallyChangePresence()) {
3082			packet =  mPresenceGenerator.selfPresence(account, account.getPresenceStatus());
3083			String message = account.getPresenceStatusMessage();
3084			if (message != null && !message.isEmpty()) {
3085				packet.addChild(new Element("status").setContent(message));
3086			}
3087		} else {
3088			packet = mPresenceGenerator.selfPresence(account, getTargetPresence());
3089		}
3090		if (mLastActivity > 0 && includeIdleTimestamp) {
3091			long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3092			packet.addChild("idle","urn:xmpp:idle:1").setAttribute("since", AbstractGenerator.getTimestamp(since));
3093		}
3094		sendPresencePacket(account, packet);
3095	}
3096
3097	private void deactivateGracePeriod() {
3098		for(Account account : getAccounts()) {
3099			account.deactivateGracePeriod();
3100		}
3101	}
3102
3103	public void refreshAllPresences() {
3104		boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3105		for (Account account : getAccounts()) {
3106			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3107				sendPresence(account, includeIdleTimestamp);
3108			}
3109		}
3110	}
3111
3112	private void refreshAllGcmTokens() {
3113		for(Account account : getAccounts()) {
3114			if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3115				mPushManagementService.registerPushTokenOnServer(account);
3116			}
3117		}
3118	}
3119
3120	public void sendOfflinePresence(final Account account) {
3121		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3122	}
3123
3124	public MessageGenerator getMessageGenerator() {
3125		return this.mMessageGenerator;
3126	}
3127
3128	public PresenceGenerator getPresenceGenerator() {
3129		return this.mPresenceGenerator;
3130	}
3131
3132	public IqGenerator getIqGenerator() {
3133		return this.mIqGenerator;
3134	}
3135
3136	public IqParser getIqParser() {
3137		return this.mIqParser;
3138	}
3139
3140	public JingleConnectionManager getJingleConnectionManager() {
3141		return this.mJingleConnectionManager;
3142	}
3143
3144	public MessageArchiveService getMessageArchiveService() {
3145		return this.mMessageArchiveService;
3146	}
3147
3148	public List<Contact> findContacts(Jid jid) {
3149		ArrayList<Contact> contacts = new ArrayList<>();
3150		for (Account account : getAccounts()) {
3151			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3152				Contact contact = account.getRoster().getContactFromRoster(jid);
3153				if (contact != null) {
3154					contacts.add(contact);
3155				}
3156			}
3157		}
3158		return contacts;
3159	}
3160
3161	public Conversation findFirstMuc(Jid jid) {
3162		for(Conversation conversation : getConversations()) {
3163			if (conversation.getJid().toBareJid().equals(jid.toBareJid())
3164					&& conversation.getMode() == Conversation.MODE_MULTI) {
3165				return conversation;
3166			}
3167		}
3168		return null;
3169	}
3170
3171	public NotificationService getNotificationService() {
3172		return this.mNotificationService;
3173	}
3174
3175	public HttpConnectionManager getHttpConnectionManager() {
3176		return this.mHttpConnectionManager;
3177	}
3178
3179	public void resendFailedMessages(final Message message) {
3180		final Collection<Message> messages = new ArrayList<>();
3181		Message current = message;
3182		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3183			messages.add(current);
3184			if (current.mergeable(current.next())) {
3185				current = current.next();
3186			} else {
3187				break;
3188			}
3189		}
3190		for (final Message msg : messages) {
3191			msg.setTime(System.currentTimeMillis());
3192			markMessage(msg, Message.STATUS_WAITING);
3193			this.resendMessage(msg, false);
3194		}
3195	}
3196
3197	public void clearConversationHistory(final Conversation conversation) {
3198		conversation.clearMessages();
3199		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3200		conversation.setLastClearHistory(System.currentTimeMillis());
3201		Runnable runnable = new Runnable() {
3202			@Override
3203			public void run() {
3204				databaseBackend.deleteMessagesInConversation(conversation);
3205			}
3206		};
3207		mDatabaseExecutor.execute(runnable);
3208	}
3209
3210	public void sendBlockRequest(final Blockable blockable) {
3211		if (blockable != null && blockable.getBlockedJid() != null) {
3212			final Jid jid = blockable.getBlockedJid();
3213			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
3214
3215				@Override
3216				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3217					if (packet.getType() == IqPacket.TYPE.RESULT) {
3218						account.getBlocklist().add(jid);
3219						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3220					}
3221				}
3222			});
3223		}
3224	}
3225
3226	public void sendUnblockRequest(final Blockable blockable) {
3227		if (blockable != null && blockable.getJid() != null) {
3228			final Jid jid = blockable.getBlockedJid();
3229			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3230				@Override
3231				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3232					if (packet.getType() == IqPacket.TYPE.RESULT) {
3233						account.getBlocklist().remove(jid);
3234						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3235					}
3236				}
3237			});
3238		}
3239	}
3240
3241	public void publishDisplayName(Account account) {
3242		String displayName = account.getDisplayName();
3243		if (displayName != null && !displayName.isEmpty()) {
3244			IqPacket publish = mIqGenerator.publishNick(displayName);
3245			sendIqPacket(account, publish, new OnIqPacketReceived() {
3246				@Override
3247				public void onIqPacketReceived(Account account, IqPacket packet) {
3248					if (packet.getType() == IqPacket.TYPE.ERROR) {
3249						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not publish nick");
3250					}
3251				}
3252			});
3253		}
3254	}
3255
3256	public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
3257		ServiceDiscoveryResult result = discoCache.get(key);
3258		if (result != null) {
3259			return result;
3260		} else {
3261			result = databaseBackend.findDiscoveryResult(key.first, key.second);
3262			if (result != null) {
3263				discoCache.put(key, result);
3264			}
3265			return result;
3266		}
3267	}
3268
3269	public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3270		final Pair<String,String> key = new Pair<>(presence.getHash(), presence.getVer());
3271		ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3272		if (disco != null) {
3273			presence.setServiceDiscoveryResult(disco);
3274		} else {
3275			if (!account.inProgressDiscoFetches.contains(key)) {
3276				account.inProgressDiscoFetches.add(key);
3277				IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3278				request.setTo(jid);
3279				request.query("http://jabber.org/protocol/disco#info");
3280				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": making disco request for "+key.second+" to "+jid);
3281				sendIqPacket(account, request, new OnIqPacketReceived() {
3282					@Override
3283					public void onIqPacketReceived(Account account, IqPacket discoPacket) {
3284						if (discoPacket.getType() == IqPacket.TYPE.RESULT) {
3285							ServiceDiscoveryResult disco = new ServiceDiscoveryResult(discoPacket);
3286							if (presence.getVer().equals(disco.getVer())) {
3287								databaseBackend.insertDiscoveryResult(disco);
3288								injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco);
3289							} else {
3290								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco.getVer());
3291							}
3292						}
3293						account.inProgressDiscoFetches.remove(key);
3294					}
3295				});
3296			}
3297		}
3298	}
3299
3300	private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3301		for(Contact contact : roster.getContacts()) {
3302			for(Presence presence : contact.getPresences().getPresences().values()) {
3303				if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3304					presence.setServiceDiscoveryResult(disco);
3305				}
3306			}
3307		}
3308	}
3309
3310	public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3311		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3312		request.addChild("prefs","urn:xmpp:mam:0");
3313		sendIqPacket(account, request, new OnIqPacketReceived() {
3314			@Override
3315			public void onIqPacketReceived(Account account, IqPacket packet) {
3316				Element prefs = packet.findChild("prefs","urn:xmpp:mam:0");
3317				if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3318					callback.onPreferencesFetched(prefs);
3319				} else {
3320					callback.onPreferencesFetchFailed();
3321				}
3322			}
3323		});
3324	}
3325
3326	public PushManagementService getPushManagementService() {
3327		return mPushManagementService;
3328	}
3329
3330	public Account getPendingAccount() {
3331		Account pending = null;
3332		for(Account account : getAccounts()) {
3333			if (account.isOptionSet(Account.OPTION_REGISTER)) {
3334				pending = account;
3335			} else {
3336				return null;
3337			}
3338		}
3339		return pending;
3340	}
3341
3342	public void changeStatus(Account account, Presence.Status status, String statusMessage, boolean send) {
3343		if (!statusMessage.isEmpty()) {
3344			databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3345		}
3346		changeStatusReal(account, status, statusMessage, send);
3347	}
3348
3349	private void changeStatusReal(Account account, Presence.Status status, String statusMessage, boolean send) {
3350		account.setPresenceStatus(status);
3351		account.setPresenceStatusMessage(statusMessage);
3352		databaseBackend.updateAccount(account);
3353		if (!account.isOptionSet(Account.OPTION_DISABLED) && send) {
3354			sendPresence(account);
3355		}
3356	}
3357
3358	public void changeStatus(Presence.Status status, String statusMessage) {
3359		if (!statusMessage.isEmpty()) {
3360			databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3361		}
3362		for(Account account : getAccounts()) {
3363			changeStatusReal(account, status, statusMessage, true);
3364		}
3365	}
3366
3367	public List<PresenceTemplate> getPresenceTemplates(Account account) {
3368		List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3369		for(PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3370			if (!templates.contains(template)) {
3371				templates.add(0, template);
3372			}
3373		}
3374		return templates;
3375	}
3376
3377	public void saveConversationAsBookmark(Conversation conversation, String name) {
3378		Account account = conversation.getAccount();
3379		Bookmark bookmark = new Bookmark(account, conversation.getJid().toBareJid());
3380		if (!conversation.getJid().isBareJid()) {
3381			bookmark.setNick(conversation.getJid().getResourcepart());
3382		}
3383		if (name != null && !name.trim().isEmpty()) {
3384			bookmark.setBookmarkName(name.trim());
3385		}
3386		bookmark.setAutojoin(getPreferences().getBoolean("autojoin",true));
3387		account.getBookmarks().add(bookmark);
3388		pushBookmarks(account);
3389		conversation.setBookmark(bookmark);
3390	}
3391
3392	public interface OnMamPreferencesFetched {
3393		void onPreferencesFetched(Element prefs);
3394		void onPreferencesFetchFailed();
3395	}
3396
3397	public void pushMamPreferences(Account account, Element prefs) {
3398		IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3399		set.addChild(prefs);
3400		sendIqPacket(account, set, null);
3401	}
3402
3403	public interface OnAccountCreated {
3404		void onAccountCreated(Account account);
3405
3406		void informUser(int r);
3407	}
3408
3409	public interface OnMoreMessagesLoaded {
3410		void onMoreMessagesLoaded(int count, Conversation conversation);
3411
3412		void informUser(int r);
3413	}
3414
3415	public interface OnAccountPasswordChanged {
3416		void onPasswordChangeSucceeded();
3417
3418		void onPasswordChangeFailed();
3419	}
3420
3421	public interface OnAffiliationChanged {
3422		void onAffiliationChangedSuccessful(Jid jid);
3423
3424		void onAffiliationChangeFailed(Jid jid, int resId);
3425	}
3426
3427	public interface OnRoleChanged {
3428		void onRoleChangedSuccessful(String nick);
3429
3430		void onRoleChangeFailed(String nick, int resid);
3431	}
3432
3433	public interface OnConversationUpdate {
3434		void onConversationUpdate();
3435	}
3436
3437	public interface OnAccountUpdate {
3438		void onAccountUpdate();
3439	}
3440
3441	public interface OnCaptchaRequested {
3442		void onCaptchaRequested(Account account,
3443								String id,
3444								Data data,
3445								Bitmap captcha);
3446	}
3447
3448	public interface OnRosterUpdate {
3449		void onRosterUpdate();
3450	}
3451
3452	public interface OnMucRosterUpdate {
3453		void onMucRosterUpdate();
3454	}
3455
3456	public interface OnConferenceConfigurationFetched {
3457		void onConferenceConfigurationFetched(Conversation conversation);
3458
3459		void onFetchFailed(Conversation conversation, Element error);
3460	}
3461
3462	public interface OnConferenceJoined {
3463		void onConferenceJoined(Conversation conversation);
3464	}
3465
3466	public interface OnConferenceOptionsPushed {
3467		void onPushSucceeded();
3468
3469		void onPushFailed();
3470	}
3471
3472	public interface OnShowErrorToast {
3473		void onShowErrorToast(int resId);
3474	}
3475
3476	public class XmppConnectionBinder extends Binder {
3477		public XmppConnectionService getService() {
3478			return XmppConnectionService.this;
3479		}
3480	}
3481}