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