XmppConnectionService.java

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