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