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