XmppConnectionService.java

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