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