XmppConnectionService.java

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