XmppConnectionService.java

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