XmppConnectionService.java

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