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