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
1903				Element query = packet.query("http://jabber.org/protocol/muc#admin");
1904				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
1905					final String local = conversation.getJid().getLocalpart();
1906					final String domain = conversation.getJid().getDomainpart();
1907					for(Element child : query.getChildren()) {
1908						if ("item".equals(child.getName())) {
1909							String affiliation = child.getAttribute("affiliation");
1910							String role = child.getAttribute("role");
1911							String nick = child.getAttribute("nick");
1912							Jid fullJid;
1913							try {
1914								fullJid = nick != null ? Jid.fromParts(local, domain, nick) : null;
1915							} catch (InvalidJidException e) {
1916								fullJid = null;
1917							}
1918							Jid realJid = child.getAttributeAsJid("jid");
1919							if (realJid != null && !realJid.equals(account.getJid().toBareJid())) {
1920								conversation.getMucOptions().putMember(fullJid, realJid, affiliation, role);
1921							}
1922						}
1923					}
1924				} else {
1925					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not request affiliation "+affiliations[i]+" in "+conversation.getJid().toBareJid());
1926				}
1927				++i;
1928				if (i >= affiliations.length) {
1929					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": retrieved members for "+conversation.getJid().toBareJid()+": "+conversation.getMucOptions().getMembers());
1930				}
1931			}
1932		};
1933		for(String affiliation : affiliations) {
1934			sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
1935		}
1936		Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetching members for "+conversation.getName());
1937	}
1938
1939	public void providePasswordForMuc(Conversation conversation, String password) {
1940		if (conversation.getMode() == Conversation.MODE_MULTI) {
1941			conversation.getMucOptions().setPassword(password);
1942			if (conversation.getBookmark() != null) {
1943				if (respectAutojoin()) {
1944					conversation.getBookmark().setAutojoin(true);
1945				}
1946				pushBookmarks(conversation.getAccount());
1947			}
1948			databaseBackend.updateConversation(conversation);
1949			joinMuc(conversation);
1950		}
1951	}
1952
1953	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1954		final MucOptions options = conversation.getMucOptions();
1955		final Jid joinJid = options.createJoinJid(nick);
1956		if (options.online()) {
1957			Account account = conversation.getAccount();
1958			options.setOnRenameListener(new OnRenameListener() {
1959
1960				@Override
1961				public void onSuccess() {
1962					conversation.setContactJid(joinJid);
1963					databaseBackend.updateConversation(conversation);
1964					Bookmark bookmark = conversation.getBookmark();
1965					if (bookmark != null) {
1966						bookmark.setNick(nick);
1967						pushBookmarks(bookmark.getAccount());
1968					}
1969					callback.success(conversation);
1970				}
1971
1972				@Override
1973				public void onFailure() {
1974					callback.error(R.string.nick_in_use, conversation);
1975				}
1976			});
1977
1978			PresencePacket packet = new PresencePacket();
1979			packet.setTo(joinJid);
1980			packet.setFrom(conversation.getAccount().getJid());
1981
1982			String sig = account.getPgpSignature();
1983			if (sig != null) {
1984				packet.addChild("status").setContent("online");
1985				packet.addChild("x", "jabber:x:signed").setContent(sig);
1986			}
1987			sendPresencePacket(account, packet);
1988		} else {
1989			conversation.setContactJid(joinJid);
1990			databaseBackend.updateConversation(conversation);
1991			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1992				Bookmark bookmark = conversation.getBookmark();
1993				if (bookmark != null) {
1994					bookmark.setNick(nick);
1995					pushBookmarks(bookmark.getAccount());
1996				}
1997				joinMuc(conversation);
1998			}
1999		}
2000	}
2001
2002	public void leaveMuc(Conversation conversation) {
2003		leaveMuc(conversation, false);
2004	}
2005
2006	private void leaveMuc(Conversation conversation, boolean now) {
2007		Account account = conversation.getAccount();
2008		account.pendingConferenceJoins.remove(conversation);
2009		account.pendingConferenceLeaves.remove(conversation);
2010		if (account.getStatus() == Account.State.ONLINE || now) {
2011			PresencePacket packet = new PresencePacket();
2012			packet.setTo(conversation.getMucOptions().getSelf().getFullJid());
2013			packet.setFrom(conversation.getAccount().getJid());
2014			packet.setAttribute("type", "unavailable");
2015			sendPresencePacket(conversation.getAccount(), packet);
2016			conversation.getMucOptions().setOffline();
2017			conversation.deregisterWithBookmark();
2018			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
2019					+ ": leaving muc " + conversation.getJid());
2020		} else {
2021			account.pendingConferenceLeaves.add(conversation);
2022		}
2023	}
2024
2025	private String findConferenceServer(final Account account) {
2026		String server;
2027		if (account.getXmppConnection() != null) {
2028			server = account.getXmppConnection().getMucServer();
2029			if (server != null) {
2030				return server;
2031			}
2032		}
2033		for (Account other : getAccounts()) {
2034			if (other != account && other.getXmppConnection() != null) {
2035				server = other.getXmppConnection().getMucServer();
2036				if (server != null) {
2037					return server;
2038				}
2039			}
2040		}
2041		return null;
2042	}
2043
2044	public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
2045		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2046		if (account.getStatus() == Account.State.ONLINE) {
2047			try {
2048				String server = findConferenceServer(account);
2049				if (server == null) {
2050					if (callback != null) {
2051						callback.error(R.string.no_conference_server_found, null);
2052					}
2053					return;
2054				}
2055				String name = new BigInteger(75, getRNG()).toString(32);
2056				Jid jid = Jid.fromParts(name, server, null);
2057				final Conversation conversation = findOrCreateConversation(account, jid, true);
2058				joinMuc(conversation, new OnConferenceJoined() {
2059					@Override
2060					public void onConferenceJoined(final Conversation conversation) {
2061						Bundle options = new Bundle();
2062						options.putString("muc#roomconfig_persistentroom", "1");
2063						options.putString("muc#roomconfig_membersonly", "1");
2064						options.putString("muc#roomconfig_publicroom", "0");
2065						options.putString("muc#roomconfig_whois", "anyone");
2066						pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
2067							@Override
2068							public void onPushSucceeded() {
2069								for (Jid invite : jids) {
2070									invite(conversation, invite);
2071								}
2072								if (account.countPresences() > 1) {
2073									directInvite(conversation, account.getJid().toBareJid());
2074								}
2075								if (callback != null) {
2076									callback.success(conversation);
2077								}
2078							}
2079
2080							@Override
2081							public void onPushFailed() {
2082								if (callback != null) {
2083									callback.error(R.string.conference_creation_failed, conversation);
2084								}
2085							}
2086						});
2087					}
2088				});
2089			} catch (InvalidJidException e) {
2090				if (callback != null) {
2091					callback.error(R.string.conference_creation_failed, null);
2092				}
2093			}
2094		} else {
2095			if (callback != null) {
2096				callback.error(R.string.not_connected_try_again, null);
2097			}
2098		}
2099	}
2100
2101	public void fetchConferenceConfiguration(final Conversation conversation) {
2102		fetchConferenceConfiguration(conversation, null);
2103	}
2104
2105	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2106		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2107		request.setTo(conversation.getJid().toBareJid());
2108		request.query("http://jabber.org/protocol/disco#info");
2109		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2110			@Override
2111			public void onIqPacketReceived(Account account, IqPacket packet) {
2112				Element query = packet.findChild("query","http://jabber.org/protocol/disco#info");
2113				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2114					ArrayList<String> features = new ArrayList<>();
2115					for (Element child : query.getChildren()) {
2116						if (child != null && child.getName().equals("feature")) {
2117							String var = child.getAttribute("var");
2118							if (var != null) {
2119								features.add(var);
2120							}
2121						}
2122					}
2123					Element form = query.findChild("x", "jabber:x:data");
2124					if (form != null) {
2125						conversation.getMucOptions().updateFormData(Data.parse(form));
2126					}
2127					conversation.getMucOptions().updateFeatures(features);
2128					if (callback != null) {
2129						callback.onConferenceConfigurationFetched(conversation);
2130					}
2131					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetched muc configuration for "+conversation.getJid().toBareJid()+" - "+features.toString());
2132					updateConversationUi();
2133				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
2134					if (callback != null) {
2135						callback.onFetchFailed(conversation, packet.getError());
2136					}
2137				}
2138			}
2139		});
2140	}
2141
2142	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
2143		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2144		request.setTo(conversation.getJid().toBareJid());
2145		request.query("http://jabber.org/protocol/muc#owner");
2146		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2147			@Override
2148			public void onIqPacketReceived(Account account, IqPacket packet) {
2149				if (packet.getType() == IqPacket.TYPE.RESULT) {
2150					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
2151					for (Field field : data.getFields()) {
2152						if (options.containsKey(field.getFieldName())) {
2153							field.setValue(options.getString(field.getFieldName()));
2154						}
2155					}
2156					data.submit();
2157					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2158					set.setTo(conversation.getJid().toBareJid());
2159					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2160					sendIqPacket(account, set, new OnIqPacketReceived() {
2161						@Override
2162						public void onIqPacketReceived(Account account, IqPacket packet) {
2163							if (callback != null) {
2164								if (packet.getType() == IqPacket.TYPE.RESULT) {
2165									callback.onPushSucceeded();
2166								} else {
2167									callback.onPushFailed();
2168								}
2169							}
2170						}
2171					});
2172				} else {
2173					if (callback != null) {
2174						callback.onPushFailed();
2175					}
2176				}
2177			}
2178		});
2179	}
2180
2181	public void pushSubjectToConference(final Conversation conference, final String subject) {
2182		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2183		this.sendMessagePacket(conference.getAccount(), packet);
2184		final MucOptions mucOptions = conference.getMucOptions();
2185		final MucOptions.User self = mucOptions.getSelf();
2186		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2187			Bundle options = new Bundle();
2188			options.putString("muc#roomconfig_persistentroom", "1");
2189			this.pushConferenceConfiguration(conference, options, null);
2190		}
2191	}
2192
2193	public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2194		final Jid jid = user.toBareJid();
2195		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2196		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2197			@Override
2198			public void onIqPacketReceived(Account account, IqPacket packet) {
2199				if (packet.getType() == IqPacket.TYPE.RESULT) {
2200					conference.getMucOptions().changeAffiliation(jid, affiliation);
2201					getAvatarService().clear(conference);
2202					callback.onAffiliationChangedSuccessful(jid);
2203				} else {
2204					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2205				}
2206			}
2207		});
2208	}
2209
2210	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2211		List<Jid> jids = new ArrayList<>();
2212		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2213			if (user.getAffiliation() == before && user.getRealJid() != null) {
2214				jids.add(user.getRealJid());
2215			}
2216		}
2217		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2218		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2219	}
2220
2221	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2222		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2223		Log.d(Config.LOGTAG, request.toString());
2224		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2225			@Override
2226			public void onIqPacketReceived(Account account, IqPacket packet) {
2227				Log.d(Config.LOGTAG, packet.toString());
2228				if (packet.getType() == IqPacket.TYPE.RESULT) {
2229					callback.onRoleChangedSuccessful(nick);
2230				} else {
2231					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2232				}
2233			}
2234		});
2235	}
2236
2237	private void disconnect(Account account, boolean force) {
2238		if ((account.getStatus() == Account.State.ONLINE)
2239				|| (account.getStatus() == Account.State.DISABLED)) {
2240			if (!force) {
2241				List<Conversation> conversations = getConversations();
2242				for (Conversation conversation : conversations) {
2243					if (conversation.getAccount() == account) {
2244						if (conversation.getMode() == Conversation.MODE_MULTI) {
2245							leaveMuc(conversation, true);
2246						} else {
2247							if (conversation.endOtrIfNeeded()) {
2248								Log.d(Config.LOGTAG, account.getJid().toBareJid()
2249										+ ": ended otr session with "
2250										+ conversation.getJid());
2251							}
2252						}
2253					}
2254				}
2255				sendOfflinePresence(account);
2256			}
2257			account.getXmppConnection().disconnect(force);
2258		}
2259	}
2260
2261	@Override
2262	public IBinder onBind(Intent intent) {
2263		return mBinder;
2264	}
2265
2266	public void updateMessage(Message message) {
2267		databaseBackend.updateMessage(message);
2268		updateConversationUi();
2269	}
2270
2271	public void updateMessage(Message message, String uuid) {
2272		databaseBackend.updateMessage(message, uuid);
2273		updateConversationUi();
2274	}
2275
2276	protected void syncDirtyContacts(Account account) {
2277		for (Contact contact : account.getRoster().getContacts()) {
2278			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2279				pushContactToServer(contact);
2280			}
2281			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2282				deleteContactOnServer(contact);
2283			}
2284		}
2285	}
2286
2287	public void createContact(Contact contact) {
2288		boolean autoGrant = getPreferences().getBoolean("grant_new_contacts", true);
2289		if (autoGrant) {
2290			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2291			contact.setOption(Contact.Options.ASKING);
2292		}
2293		pushContactToServer(contact);
2294	}
2295
2296	public void onOtrSessionEstablished(Conversation conversation) {
2297		final Account account = conversation.getAccount();
2298		final Session otrSession = conversation.getOtrSession();
2299		Log.d(Config.LOGTAG,
2300				account.getJid().toBareJid() + " otr session established with "
2301						+ conversation.getJid() + "/"
2302						+ otrSession.getSessionID().getUserID());
2303		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2304
2305			@Override
2306			public void onMessageFound(Message message) {
2307				SessionID id = otrSession.getSessionID();
2308				try {
2309					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2310				} catch (InvalidJidException e) {
2311					return;
2312				}
2313				if (message.needsUploading()) {
2314					mJingleConnectionManager.createNewConnection(message);
2315				} else {
2316					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2317					if (outPacket != null) {
2318						mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2319						message.setStatus(Message.STATUS_SEND);
2320						databaseBackend.updateMessage(message);
2321						sendMessagePacket(account, outPacket);
2322					}
2323				}
2324				updateConversationUi();
2325			}
2326		});
2327	}
2328
2329	public boolean renewSymmetricKey(Conversation conversation) {
2330		Account account = conversation.getAccount();
2331		byte[] symmetricKey = new byte[32];
2332		this.mRandom.nextBytes(symmetricKey);
2333		Session otrSession = conversation.getOtrSession();
2334		if (otrSession != null) {
2335			MessagePacket packet = new MessagePacket();
2336			packet.setType(MessagePacket.TYPE_CHAT);
2337			packet.setFrom(account.getJid());
2338			MessageGenerator.addMessageHints(packet);
2339			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2340					+ otrSession.getSessionID().getUserID());
2341			try {
2342				packet.setBody(otrSession
2343						.transformSending(CryptoHelper.FILETRANSFER
2344								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
2345				sendMessagePacket(account, packet);
2346				conversation.setSymmetricKey(symmetricKey);
2347				return true;
2348			} catch (OtrException e) {
2349				return false;
2350			}
2351		}
2352		return false;
2353	}
2354
2355	public void pushContactToServer(final Contact contact) {
2356		contact.resetOption(Contact.Options.DIRTY_DELETE);
2357		contact.setOption(Contact.Options.DIRTY_PUSH);
2358		final Account account = contact.getAccount();
2359		if (account.getStatus() == Account.State.ONLINE) {
2360			final boolean ask = contact.getOption(Contact.Options.ASKING);
2361			final boolean sendUpdates = contact
2362					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2363					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2364			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2365			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
2366			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2367			if (sendUpdates) {
2368				sendPresencePacket(account,
2369						mPresenceGenerator.sendPresenceUpdatesTo(contact));
2370			}
2371			if (ask) {
2372				sendPresencePacket(account,
2373						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2374			}
2375		}
2376	}
2377
2378	public void publishAvatar(Account account, Uri image, UiCallback<Avatar> callback) {
2379		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2380		final int size = Config.AVATAR_SIZE;
2381		final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2382		if (avatar != null) {
2383			avatar.height = size;
2384			avatar.width = size;
2385			if (format.equals(Bitmap.CompressFormat.WEBP)) {
2386				avatar.type = "image/webp";
2387			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2388				avatar.type = "image/jpeg";
2389			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
2390				avatar.type = "image/png";
2391			}
2392			if (!getFileBackend().save(avatar)) {
2393				callback.error(R.string.error_saving_avatar, avatar);
2394				return;
2395			}
2396			publishAvatar(account, avatar, callback);
2397		} else {
2398			callback.error(R.string.error_publish_avatar_converting, null);
2399		}
2400	}
2401
2402	public void publishAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2403		final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2404		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2405
2406			@Override
2407			public void onIqPacketReceived(Account account, IqPacket result) {
2408				if (result.getType() == IqPacket.TYPE.RESULT) {
2409					final IqPacket packet = XmppConnectionService.this.mIqGenerator
2410							.publishAvatarMetadata(avatar);
2411					sendIqPacket(account, packet, new OnIqPacketReceived() {
2412						@Override
2413						public void onIqPacketReceived(Account account, IqPacket result) {
2414							if (result.getType() == IqPacket.TYPE.RESULT) {
2415								if (account.setAvatar(avatar.getFilename())) {
2416									getAvatarService().clear(account);
2417									databaseBackend.updateAccount(account);
2418								}
2419								if (callback != null) {
2420									callback.success(avatar);
2421								} else {
2422									Log.d(Config.LOGTAG,account.getJid().toBareJid()+": published avatar");
2423								}
2424							} else {
2425								if (callback != null) {
2426									callback.error(
2427											R.string.error_publish_avatar_server_reject,
2428											avatar);
2429								}
2430							}
2431						}
2432					});
2433				} else {
2434					if (callback != null) {
2435						callback.error(
2436								R.string.error_publish_avatar_server_reject,
2437								avatar);
2438					}
2439				}
2440			}
2441		});
2442	}
2443
2444	public void republishAvatarIfNeeded(Account account) {
2445		if (account.getAxolotlService().isPepBroken()) {
2446			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": skipping republication of avatar because pep is broken");
2447			return;
2448		}
2449		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2450		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2451
2452			private Avatar parseAvatar(IqPacket packet) {
2453				Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2454				if (pubsub != null) {
2455					Element items = pubsub.findChild("items");
2456					if (items != null) {
2457						return Avatar.parseMetadata(items);
2458					}
2459				}
2460				return null;
2461			}
2462
2463			private boolean errorIsItemNotFound(IqPacket packet) {
2464				Element error = packet.findChild("error");
2465				return packet.getType() == IqPacket.TYPE.ERROR
2466						&& error != null
2467						&& error.hasChild("item-not-found");
2468			}
2469
2470			@Override
2471			public void onIqPacketReceived(Account account, IqPacket packet) {
2472				if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2473					Avatar serverAvatar = parseAvatar(packet);
2474					if (serverAvatar == null && account.getAvatar() != null) {
2475						Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2476						if (avatar != null) {
2477							Log.d(Config.LOGTAG,account.getJid().toBareJid()+": avatar on server was null. republishing");
2478							publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2479						} else {
2480							Log.e(Config.LOGTAG, account.getJid().toBareJid()+": error rereading avatar");
2481						}
2482					}
2483				}
2484			}
2485		});
2486	}
2487
2488	public void fetchAvatar(Account account, Avatar avatar) {
2489		fetchAvatar(account, avatar, null);
2490	}
2491
2492	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2493		final String KEY = generateFetchKey(account, avatar);
2494		synchronized (this.mInProgressAvatarFetches) {
2495			if (!this.mInProgressAvatarFetches.contains(KEY)) {
2496				switch (avatar.origin) {
2497					case PEP:
2498						this.mInProgressAvatarFetches.add(KEY);
2499						fetchAvatarPep(account, avatar, callback);
2500						break;
2501					case VCARD:
2502						this.mInProgressAvatarFetches.add(KEY);
2503						fetchAvatarVcard(account, avatar, callback);
2504						break;
2505				}
2506			}
2507		}
2508	}
2509
2510	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2511		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2512		sendIqPacket(account, packet, new OnIqPacketReceived() {
2513
2514			@Override
2515			public void onIqPacketReceived(Account account, IqPacket result) {
2516				synchronized (mInProgressAvatarFetches) {
2517					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2518				}
2519				final String ERROR = account.getJid().toBareJid()
2520						+ ": fetching avatar for " + avatar.owner + " failed ";
2521				if (result.getType() == IqPacket.TYPE.RESULT) {
2522					avatar.image = mIqParser.avatarData(result);
2523					if (avatar.image != null) {
2524						if (getFileBackend().save(avatar)) {
2525							if (account.getJid().toBareJid().equals(avatar.owner)) {
2526								if (account.setAvatar(avatar.getFilename())) {
2527									databaseBackend.updateAccount(account);
2528								}
2529								getAvatarService().clear(account);
2530								updateConversationUi();
2531								updateAccountUi();
2532							} else {
2533								Contact contact = account.getRoster()
2534										.getContact(avatar.owner);
2535								contact.setAvatar(avatar);
2536								getAvatarService().clear(contact);
2537								updateConversationUi();
2538								updateRosterUi();
2539							}
2540							if (callback != null) {
2541								callback.success(avatar);
2542							}
2543							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2544									+ ": successfully fetched pep avatar for " + avatar.owner);
2545							return;
2546						}
2547					} else {
2548
2549						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2550					}
2551				} else {
2552					Element error = result.findChild("error");
2553					if (error == null) {
2554						Log.d(Config.LOGTAG, ERROR + "(server error)");
2555					} else {
2556						Log.d(Config.LOGTAG, ERROR + error.toString());
2557					}
2558				}
2559				if (callback != null) {
2560					callback.error(0, null);
2561				}
2562
2563			}
2564		});
2565	}
2566
2567	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2568		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2569		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2570			@Override
2571			public void onIqPacketReceived(Account account, IqPacket packet) {
2572				synchronized (mInProgressAvatarFetches) {
2573					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2574				}
2575				if (packet.getType() == IqPacket.TYPE.RESULT) {
2576					Element vCard = packet.findChild("vCard", "vcard-temp");
2577					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2578					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2579					if (image != null) {
2580						avatar.image = image;
2581						if (getFileBackend().save(avatar)) {
2582							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2583									+ ": successfully fetched vCard avatar for " + avatar.owner);
2584							if (avatar.owner.isBareJid()) {
2585								Contact contact = account.getRoster()
2586										.getContact(avatar.owner);
2587								contact.setAvatar(avatar);
2588								getAvatarService().clear(contact);
2589								updateConversationUi();
2590								updateRosterUi();
2591							} else {
2592								Conversation conversation = find(account, avatar.owner.toBareJid());
2593								if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
2594									MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
2595									if (user != null) {
2596										if (user.setAvatar(avatar)) {
2597											getAvatarService().clear(user);
2598											updateConversationUi();
2599											updateMucRosterUi();
2600										}
2601									}
2602								}
2603							}
2604						}
2605					}
2606				}
2607			}
2608		});
2609	}
2610
2611	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2612		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2613		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2614
2615			@Override
2616			public void onIqPacketReceived(Account account, IqPacket packet) {
2617				if (packet.getType() == IqPacket.TYPE.RESULT) {
2618					Element pubsub = packet.findChild("pubsub","http://jabber.org/protocol/pubsub");
2619					if (pubsub != null) {
2620						Element items = pubsub.findChild("items");
2621						if (items != null) {
2622							Avatar avatar = Avatar.parseMetadata(items);
2623							if (avatar != null) {
2624								avatar.owner = account.getJid().toBareJid();
2625								if (fileBackend.isAvatarCached(avatar)) {
2626									if (account.setAvatar(avatar.getFilename())) {
2627										databaseBackend.updateAccount(account);
2628									}
2629									getAvatarService().clear(account);
2630									callback.success(avatar);
2631								} else {
2632									fetchAvatarPep(account, avatar, callback);
2633								}
2634								return;
2635							}
2636						}
2637					}
2638				}
2639				callback.error(0, null);
2640			}
2641		});
2642	}
2643
2644	public void deleteContactOnServer(Contact contact) {
2645		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2646		contact.resetOption(Contact.Options.DIRTY_PUSH);
2647		contact.setOption(Contact.Options.DIRTY_DELETE);
2648		Account account = contact.getAccount();
2649		if (account.getStatus() == Account.State.ONLINE) {
2650			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2651			Element item = iq.query(Xmlns.ROSTER).addChild("item");
2652			item.setAttribute("jid", contact.getJid().toString());
2653			item.setAttribute("subscription", "remove");
2654			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2655		}
2656	}
2657
2658	public void updateConversation(Conversation conversation) {
2659		this.databaseBackend.updateConversation(conversation);
2660	}
2661
2662	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2663		synchronized (account) {
2664			XmppConnection connection = account.getXmppConnection();
2665			if (connection == null) {
2666				connection = createConnection(account);
2667				account.setXmppConnection(connection);
2668			} else {
2669				connection.interrupt();
2670			}
2671			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2672				if (!force) {
2673					disconnect(account, false);
2674				}
2675				Thread thread = new Thread(connection);
2676				connection.setInteractive(interactive);
2677				connection.prepareNewConnection();
2678				thread.start();
2679				scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2680			} else {
2681				disconnect(account, force);
2682				account.getRoster().clearPresences();
2683				connection.resetEverything();
2684				account.getAxolotlService().resetBrokenness();
2685			}
2686		}
2687	}
2688
2689	public void reconnectAccountInBackground(final Account account) {
2690		new Thread(new Runnable() {
2691			@Override
2692			public void run() {
2693				reconnectAccount(account, false, true);
2694			}
2695		}).start();
2696	}
2697
2698	public void invite(Conversation conversation, Jid contact) {
2699		Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
2700		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2701		sendMessagePacket(conversation.getAccount(), packet);
2702	}
2703
2704	public void directInvite(Conversation conversation, Jid jid) {
2705		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2706		sendMessagePacket(conversation.getAccount(), packet);
2707	}
2708
2709	public void resetSendingToWaiting(Account account) {
2710		for (Conversation conversation : getConversations()) {
2711			if (conversation.getAccount() == account) {
2712				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2713
2714					@Override
2715					public void onMessageFound(Message message) {
2716						markMessage(message, Message.STATUS_WAITING);
2717					}
2718				});
2719			}
2720		}
2721	}
2722
2723	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2724		if (uuid == null) {
2725			return null;
2726		}
2727		for (Conversation conversation : getConversations()) {
2728			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2729				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
2730				if (message != null) {
2731					markMessage(message, status);
2732				}
2733				return message;
2734			}
2735		}
2736		return null;
2737	}
2738
2739	public boolean markMessage(Conversation conversation, String uuid, int status) {
2740		if (uuid == null) {
2741			return false;
2742		} else {
2743			Message message = conversation.findSentMessageWithUuid(uuid);
2744			if (message != null) {
2745				markMessage(message, status);
2746				return true;
2747			} else {
2748				return false;
2749			}
2750		}
2751	}
2752
2753	public void markMessage(Message message, int status) {
2754		if (status == Message.STATUS_SEND_FAILED
2755				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2756				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2757			return;
2758		}
2759		message.setStatus(status);
2760		databaseBackend.updateMessage(message);
2761		updateConversationUi();
2762	}
2763
2764	public SharedPreferences getPreferences() {
2765		return PreferenceManager
2766				.getDefaultSharedPreferences(getApplicationContext());
2767	}
2768
2769	public boolean confirmMessages() {
2770		return getPreferences().getBoolean("confirm_messages", true);
2771	}
2772
2773	public boolean allowMessageCorrection() {
2774		return getPreferences().getBoolean("allow_message_correction", false);
2775	}
2776
2777	public boolean sendChatStates() {
2778		return getPreferences().getBoolean("chat_states", false);
2779	}
2780
2781	public boolean saveEncryptedMessages() {
2782		return !getPreferences().getBoolean("dont_save_encrypted", false);
2783	}
2784
2785	private boolean respectAutojoin() {
2786		return getPreferences().getBoolean("autojoin", true);
2787	}
2788
2789	public boolean indicateReceived() {
2790		return getPreferences().getBoolean("indicate_received", false);
2791	}
2792
2793	public boolean useTorToConnect() {
2794		return Config.FORCE_ORBOT || getPreferences().getBoolean("use_tor", false);
2795	}
2796
2797	public boolean showExtendedConnectionOptions() {
2798		return getPreferences().getBoolean("show_connection_options", false);
2799	}
2800
2801	public int unreadCount() {
2802		int count = 0;
2803		for (Conversation conversation : getConversations()) {
2804			count += conversation.unreadCount();
2805		}
2806		return count;
2807	}
2808
2809
2810	public void showErrorToastInUi(int resId) {
2811		if (mOnShowErrorToast != null) {
2812			mOnShowErrorToast.onShowErrorToast(resId);
2813		}
2814	}
2815
2816	public void updateConversationUi() {
2817		if (mOnConversationUpdate != null) {
2818			mOnConversationUpdate.onConversationUpdate();
2819		}
2820	}
2821
2822	public void updateAccountUi() {
2823		if (mOnAccountUpdate != null) {
2824			mOnAccountUpdate.onAccountUpdate();
2825		}
2826	}
2827
2828	public void updateRosterUi() {
2829		if (mOnRosterUpdate != null) {
2830			mOnRosterUpdate.onRosterUpdate();
2831		}
2832	}
2833
2834	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
2835		if (mOnCaptchaRequested != null) {
2836			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
2837			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
2838					(int) (captcha.getHeight() * metrics.scaledDensity), false);
2839
2840			mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
2841			return true;
2842		}
2843		return false;
2844	}
2845
2846	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2847		if (mOnUpdateBlocklist != null) {
2848			mOnUpdateBlocklist.OnUpdateBlocklist(status);
2849		}
2850	}
2851
2852	public void updateMucRosterUi() {
2853		if (mOnMucRosterUpdate != null) {
2854			mOnMucRosterUpdate.onMucRosterUpdate();
2855		}
2856	}
2857
2858	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
2859		if (mOnKeyStatusUpdated != null) {
2860			mOnKeyStatusUpdated.onKeyStatusUpdated(report);
2861		}
2862	}
2863
2864	public Account findAccountByJid(final Jid accountJid) {
2865		for (Account account : this.accounts) {
2866			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2867				return account;
2868			}
2869		}
2870		return null;
2871	}
2872
2873	public Conversation findConversationByUuid(String uuid) {
2874		for (Conversation conversation : getConversations()) {
2875			if (conversation.getUuid().equals(uuid)) {
2876				return conversation;
2877			}
2878		}
2879		return null;
2880	}
2881
2882	public boolean markRead(final Conversation conversation) {
2883		mNotificationService.clear(conversation);
2884		final List<Message> readMessages = conversation.markRead();
2885		if (readMessages.size() > 0) {
2886			Runnable runnable = new Runnable() {
2887				@Override
2888				public void run() {
2889					for (Message message : readMessages) {
2890						databaseBackend.updateMessage(message);
2891					}
2892				}
2893			};
2894			mDatabaseExecutor.execute(runnable);
2895			updateUnreadCountBadge();
2896			return true;
2897		} else {
2898			return false;
2899		}
2900	}
2901
2902	public synchronized void updateUnreadCountBadge() {
2903		int count = unreadCount();
2904		if (unreadCount != count) {
2905			Log.d(Config.LOGTAG, "update unread count to " + count);
2906			if (count > 0) {
2907				ShortcutBadger.applyCount(getApplicationContext(), count);
2908			} else {
2909				ShortcutBadger.removeCount(getApplicationContext());
2910			}
2911			unreadCount = count;
2912		}
2913	}
2914
2915	public void sendReadMarker(final Conversation conversation) {
2916		final Message markable = conversation.getLatestMarkableMessage();
2917		if (this.markRead(conversation)) {
2918			updateConversationUi();
2919		}
2920		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2921			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2922			Account account = conversation.getAccount();
2923			final Jid to = markable.getCounterpart();
2924			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2925			this.sendMessagePacket(conversation.getAccount(), packet);
2926		}
2927	}
2928
2929	public SecureRandom getRNG() {
2930		return this.mRandom;
2931	}
2932
2933	public MemorizingTrustManager getMemorizingTrustManager() {
2934		return this.mMemorizingTrustManager;
2935	}
2936
2937	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2938		this.mMemorizingTrustManager = trustManager;
2939	}
2940
2941	public void updateMemorizingTrustmanager() {
2942		final MemorizingTrustManager tm;
2943		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2944		if (dontTrustSystemCAs) {
2945			tm = new MemorizingTrustManager(getApplicationContext(), null);
2946		} else {
2947			tm = new MemorizingTrustManager(getApplicationContext());
2948		}
2949		setMemorizingTrustManager(tm);
2950	}
2951
2952	public PowerManager getPowerManager() {
2953		return this.pm;
2954	}
2955
2956	public LruCache<String, Bitmap> getBitmapCache() {
2957		return this.mBitmapCache;
2958	}
2959
2960	public void syncRosterToDisk(final Account account) {
2961		Runnable runnable = new Runnable() {
2962
2963			@Override
2964			public void run() {
2965				databaseBackend.writeRoster(account.getRoster());
2966			}
2967		};
2968		mDatabaseExecutor.execute(runnable);
2969
2970	}
2971
2972	public List<String> getKnownHosts() {
2973		final List<String> hosts = new ArrayList<>();
2974		for (final Account account : getAccounts()) {
2975			if (!hosts.contains(account.getServer().toString())) {
2976				hosts.add(account.getServer().toString());
2977			}
2978			for (final Contact contact : account.getRoster().getContacts()) {
2979				if (contact.showInRoster()) {
2980					final String server = contact.getServer().toString();
2981					if (server != null && !hosts.contains(server)) {
2982						hosts.add(server);
2983					}
2984				}
2985			}
2986		}
2987		if(Config.DOMAIN_LOCK != null && !hosts.contains(Config.DOMAIN_LOCK)) {
2988			hosts.add(Config.DOMAIN_LOCK);
2989		}
2990		if(Config.MAGIC_CREATE_DOMAIN != null && !hosts.contains(Config.MAGIC_CREATE_DOMAIN)) {
2991			hosts.add(Config.MAGIC_CREATE_DOMAIN);
2992		}
2993		return hosts;
2994	}
2995
2996	public List<String> getKnownConferenceHosts() {
2997		final ArrayList<String> mucServers = new ArrayList<>();
2998		for (final Account account : accounts) {
2999			if (account.getXmppConnection() != null) {
3000				final String server = account.getXmppConnection().getMucServer();
3001				if (server != null && !mucServers.contains(server)) {
3002					mucServers.add(server);
3003				}
3004			}
3005		}
3006		return mucServers;
3007	}
3008
3009	public void sendMessagePacket(Account account, MessagePacket packet) {
3010		XmppConnection connection = account.getXmppConnection();
3011		if (connection != null) {
3012			connection.sendMessagePacket(packet);
3013		}
3014	}
3015
3016	public void sendPresencePacket(Account account, PresencePacket packet) {
3017		XmppConnection connection = account.getXmppConnection();
3018		if (connection != null) {
3019			connection.sendPresencePacket(packet);
3020		}
3021	}
3022
3023	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3024		final XmppConnection connection = account.getXmppConnection();
3025		if (connection != null) {
3026			IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3027			sendIqPacket(account, request, connection.registrationResponseListener);
3028		}
3029	}
3030
3031	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3032		final XmppConnection connection = account.getXmppConnection();
3033		if (connection != null) {
3034			connection.sendIqPacket(packet, callback);
3035		}
3036	}
3037
3038	public void sendPresence(final Account account) {
3039		PresencePacket packet;
3040		if (manuallyChangePresence()) {
3041			packet =  mPresenceGenerator.selfPresence(account, account.getPresenceStatus());
3042			String message = account.getPresenceStatusMessage();
3043			if (message != null && !message.isEmpty()) {
3044				packet.addChild(new Element("status").setContent(message));
3045			}
3046		} else {
3047			packet = mPresenceGenerator.selfPresence(account, getTargetPresence());
3048		}
3049		sendPresencePacket(account, packet);
3050	}
3051
3052	public void refreshAllPresences() {
3053		for (Account account : getAccounts()) {
3054			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3055				sendPresence(account);
3056			}
3057		}
3058	}
3059
3060	private void refreshAllGcmTokens() {
3061		for(Account account : getAccounts()) {
3062			if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3063				mPushManagementService.registerPushTokenOnServer(account);
3064			}
3065		}
3066	}
3067
3068	public void sendOfflinePresence(final Account account) {
3069		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3070	}
3071
3072	public MessageGenerator getMessageGenerator() {
3073		return this.mMessageGenerator;
3074	}
3075
3076	public PresenceGenerator getPresenceGenerator() {
3077		return this.mPresenceGenerator;
3078	}
3079
3080	public IqGenerator getIqGenerator() {
3081		return this.mIqGenerator;
3082	}
3083
3084	public IqParser getIqParser() {
3085		return this.mIqParser;
3086	}
3087
3088	public JingleConnectionManager getJingleConnectionManager() {
3089		return this.mJingleConnectionManager;
3090	}
3091
3092	public MessageArchiveService getMessageArchiveService() {
3093		return this.mMessageArchiveService;
3094	}
3095
3096	public List<Contact> findContacts(Jid jid) {
3097		ArrayList<Contact> contacts = new ArrayList<>();
3098		for (Account account : getAccounts()) {
3099			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3100				Contact contact = account.getRoster().getContactFromRoster(jid);
3101				if (contact != null) {
3102					contacts.add(contact);
3103				}
3104			}
3105		}
3106		return contacts;
3107	}
3108
3109	public NotificationService getNotificationService() {
3110		return this.mNotificationService;
3111	}
3112
3113	public HttpConnectionManager getHttpConnectionManager() {
3114		return this.mHttpConnectionManager;
3115	}
3116
3117	public void resendFailedMessages(final Message message) {
3118		final Collection<Message> messages = new ArrayList<>();
3119		Message current = message;
3120		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3121			messages.add(current);
3122			if (current.mergeable(current.next())) {
3123				current = current.next();
3124			} else {
3125				break;
3126			}
3127		}
3128		for (final Message msg : messages) {
3129			msg.setTime(System.currentTimeMillis());
3130			markMessage(msg, Message.STATUS_WAITING);
3131			this.resendMessage(msg, false);
3132		}
3133	}
3134
3135	public void clearConversationHistory(final Conversation conversation) {
3136		conversation.clearMessages();
3137		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3138		conversation.setLastClearHistory(System.currentTimeMillis());
3139		Runnable runnable = new Runnable() {
3140			@Override
3141			public void run() {
3142				databaseBackend.deleteMessagesInConversation(conversation);
3143			}
3144		};
3145		mDatabaseExecutor.execute(runnable);
3146	}
3147
3148	public void sendBlockRequest(final Blockable blockable) {
3149		if (blockable != null && blockable.getBlockedJid() != null) {
3150			final Jid jid = blockable.getBlockedJid();
3151			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
3152
3153				@Override
3154				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3155					if (packet.getType() == IqPacket.TYPE.RESULT) {
3156						account.getBlocklist().add(jid);
3157						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3158					}
3159				}
3160			});
3161		}
3162	}
3163
3164	public void sendUnblockRequest(final Blockable blockable) {
3165		if (blockable != null && blockable.getJid() != null) {
3166			final Jid jid = blockable.getBlockedJid();
3167			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3168				@Override
3169				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3170					if (packet.getType() == IqPacket.TYPE.RESULT) {
3171						account.getBlocklist().remove(jid);
3172						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3173					}
3174				}
3175			});
3176		}
3177	}
3178
3179	public void publishDisplayName(Account account) {
3180		String displayName = account.getDisplayName();
3181		if (displayName != null && !displayName.isEmpty()) {
3182			IqPacket publish = mIqGenerator.publishNick(displayName);
3183			sendIqPacket(account, publish, new OnIqPacketReceived() {
3184				@Override
3185				public void onIqPacketReceived(Account account, IqPacket packet) {
3186					if (packet.getType() == IqPacket.TYPE.ERROR) {
3187						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not publish nick");
3188					}
3189				}
3190			});
3191		}
3192	}
3193
3194	private ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String,String> key) {
3195		ServiceDiscoveryResult result = discoCache.get(key);
3196		if (result != null) {
3197			return result;
3198		} else {
3199			result = databaseBackend.findDiscoveryResult(key.first, key.second);
3200			if (result != null) {
3201				discoCache.put(key, result);
3202			}
3203			return result;
3204		}
3205	}
3206
3207	public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3208		final Pair<String,String> key = new Pair<>(presence.getHash(), presence.getVer());
3209		ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3210		if (disco != null) {
3211			presence.setServiceDiscoveryResult(disco);
3212		} else {
3213			if (!account.inProgressDiscoFetches.contains(key)) {
3214				account.inProgressDiscoFetches.add(key);
3215				IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3216				request.setTo(jid);
3217				request.query("http://jabber.org/protocol/disco#info");
3218				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": making disco request for "+key.second+" to "+jid);
3219				sendIqPacket(account, request, new OnIqPacketReceived() {
3220					@Override
3221					public void onIqPacketReceived(Account account, IqPacket discoPacket) {
3222						if (discoPacket.getType() == IqPacket.TYPE.RESULT) {
3223							ServiceDiscoveryResult disco = new ServiceDiscoveryResult(discoPacket);
3224							if (presence.getVer().equals(disco.getVer())) {
3225								databaseBackend.insertDiscoveryResult(disco);
3226								injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco);
3227							} else {
3228								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco.getVer());
3229							}
3230						}
3231						account.inProgressDiscoFetches.remove(key);
3232					}
3233				});
3234			}
3235		}
3236	}
3237
3238	private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3239		for(Contact contact : roster.getContacts()) {
3240			for(Presence presence : contact.getPresences().getPresences().values()) {
3241				if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3242					presence.setServiceDiscoveryResult(disco);
3243				}
3244			}
3245		}
3246	}
3247
3248	public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3249		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3250		request.addChild("prefs","urn:xmpp:mam:0");
3251		sendIqPacket(account, request, new OnIqPacketReceived() {
3252			@Override
3253			public void onIqPacketReceived(Account account, IqPacket packet) {
3254				Element prefs = packet.findChild("prefs","urn:xmpp:mam:0");
3255				if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3256					callback.onPreferencesFetched(prefs);
3257				} else {
3258					callback.onPreferencesFetchFailed();
3259				}
3260			}
3261		});
3262	}
3263
3264	public PushManagementService getPushManagementService() {
3265		return mPushManagementService;
3266	}
3267
3268	public Account getPendingAccount() {
3269		Account pending = null;
3270		for(Account account : getAccounts()) {
3271			if (account.isOptionSet(Account.OPTION_REGISTER)) {
3272				pending = account;
3273			} else {
3274				return null;
3275			}
3276		}
3277		return pending;
3278	}
3279
3280	public void changeStatus(Account account, Presence.Status status, String statusMessage, boolean send) {
3281		if (!statusMessage.isEmpty()) {
3282			databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3283		}
3284		changeStatusReal(account, status, statusMessage, send);
3285	}
3286
3287	private void changeStatusReal(Account account, Presence.Status status, String statusMessage, boolean send) {
3288		account.setPresenceStatus(status);
3289		account.setPresenceStatusMessage(statusMessage);
3290		databaseBackend.updateAccount(account);
3291		if (!account.isOptionSet(Account.OPTION_DISABLED) && send) {
3292			sendPresence(account);
3293		}
3294	}
3295
3296	public void changeStatus(Presence.Status status, String statusMessage) {
3297		if (!statusMessage.isEmpty()) {
3298			databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3299		}
3300		for(Account account : getAccounts()) {
3301			changeStatusReal(account, status, statusMessage, true);
3302		}
3303	}
3304
3305	public List<PresenceTemplate> getPresenceTemplates(Account account) {
3306		List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3307		for(PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3308			if (!templates.contains(template)) {
3309				templates.add(0, template);
3310			}
3311		}
3312		return templates;
3313	}
3314
3315	public interface OnMamPreferencesFetched {
3316		void onPreferencesFetched(Element prefs);
3317		void onPreferencesFetchFailed();
3318	}
3319
3320	public void pushMamPreferences(Account account, Element prefs) {
3321		IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3322		set.addChild(prefs);
3323		sendIqPacket(account, set, null);
3324	}
3325
3326	public interface OnAccountCreated {
3327		void onAccountCreated(Account account);
3328
3329		void informUser(int r);
3330	}
3331
3332	public interface OnMoreMessagesLoaded {
3333		void onMoreMessagesLoaded(int count, Conversation conversation);
3334
3335		void informUser(int r);
3336	}
3337
3338	public interface OnAccountPasswordChanged {
3339		void onPasswordChangeSucceeded();
3340
3341		void onPasswordChangeFailed();
3342	}
3343
3344	public interface OnAffiliationChanged {
3345		void onAffiliationChangedSuccessful(Jid jid);
3346
3347		void onAffiliationChangeFailed(Jid jid, int resId);
3348	}
3349
3350	public interface OnRoleChanged {
3351		void onRoleChangedSuccessful(String nick);
3352
3353		void onRoleChangeFailed(String nick, int resid);
3354	}
3355
3356	public interface OnConversationUpdate {
3357		void onConversationUpdate();
3358	}
3359
3360	public interface OnAccountUpdate {
3361		void onAccountUpdate();
3362	}
3363
3364	public interface OnCaptchaRequested {
3365		void onCaptchaRequested(Account account,
3366								String id,
3367								Data data,
3368								Bitmap captcha);
3369	}
3370
3371	public interface OnRosterUpdate {
3372		void onRosterUpdate();
3373	}
3374
3375	public interface OnMucRosterUpdate {
3376		void onMucRosterUpdate();
3377	}
3378
3379	public interface OnConferenceConfigurationFetched {
3380		void onConferenceConfigurationFetched(Conversation conversation);
3381
3382		void onFetchFailed(Conversation conversation, Element error);
3383	}
3384
3385	public interface OnConferenceJoined {
3386		void onConferenceJoined(Conversation conversation);
3387	}
3388
3389	public interface OnConferenceOptionsPushed {
3390		void onPushSucceeded();
3391
3392		void onPushFailed();
3393	}
3394
3395	public interface OnShowErrorToast {
3396		void onShowErrorToast(int resId);
3397	}
3398
3399	public class XmppConnectionBinder extends Binder {
3400		public XmppConnectionService getService() {
3401			return XmppConnectionService.this;
3402		}
3403	}
3404}