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