XmppConnectionService.java

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