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