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					if (error != null && "remote-server-not-found".equals(error.getName())) {
2032						conversation.getMucOptions().setError(MucOptions.Error.SEVRER_NOT_FOUND);
2033					} else {
2034						join(conversation);
2035						fetchConferenceConfiguration(conversation);
2036					}
2037				}
2038			});
2039			updateConversationUi();
2040		} else {
2041			account.pendingConferenceJoins.add(conversation);
2042			conversation.resetMucOptions();
2043			conversation.setHasMessagesLeftOnServer(false);
2044			updateConversationUi();
2045		}
2046	}
2047
2048	private void fetchConferenceMembers(final Conversation conversation) {
2049		final Account account = conversation.getAccount();
2050		final String[] affiliations = {"member","admin","owner"};
2051		OnIqPacketReceived callback = new OnIqPacketReceived() {
2052
2053			private int i = 0;
2054
2055			@Override
2056			public void onIqPacketReceived(Account account, IqPacket packet) {
2057
2058				Element query = packet.query("http://jabber.org/protocol/muc#admin");
2059				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2060					for(Element child : query.getChildren()) {
2061						if ("item".equals(child.getName())) {
2062							MucOptions.User user = AbstractParser.parseItem(conversation,child);
2063							if (!user.realJidMatchesAccount()) {
2064								conversation.getMucOptions().addUser(user);
2065								getAvatarService().clear(conversation);
2066								updateMucRosterUi();
2067								updateConversationUi();
2068							}
2069						}
2070					}
2071				} else {
2072					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not request affiliation "+affiliations[i]+" in "+conversation.getJid().toBareJid());
2073				}
2074				++i;
2075				if (i >= affiliations.length) {
2076					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": retrieved members for "+conversation.getJid().toBareJid()+": "+conversation.getMucOptions().getMembers());
2077				}
2078			}
2079		};
2080		for(String affiliation : affiliations) {
2081			sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2082		}
2083		Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetching members for "+conversation.getName());
2084	}
2085
2086	public void providePasswordForMuc(Conversation conversation, String password) {
2087		if (conversation.getMode() == Conversation.MODE_MULTI) {
2088			conversation.getMucOptions().setPassword(password);
2089			if (conversation.getBookmark() != null) {
2090				if (respectAutojoin()) {
2091					conversation.getBookmark().setAutojoin(true);
2092				}
2093				pushBookmarks(conversation.getAccount());
2094			}
2095			databaseBackend.updateConversation(conversation);
2096			joinMuc(conversation);
2097		}
2098	}
2099
2100	public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2101		final MucOptions options = conversation.getMucOptions();
2102		final Jid joinJid = options.createJoinJid(nick);
2103		if (options.online()) {
2104			Account account = conversation.getAccount();
2105			options.setOnRenameListener(new OnRenameListener() {
2106
2107				@Override
2108				public void onSuccess() {
2109					conversation.setContactJid(joinJid);
2110					databaseBackend.updateConversation(conversation);
2111					Bookmark bookmark = conversation.getBookmark();
2112					if (bookmark != null) {
2113						bookmark.setNick(nick);
2114						pushBookmarks(bookmark.getAccount());
2115					}
2116					callback.success(conversation);
2117				}
2118
2119				@Override
2120				public void onFailure() {
2121					callback.error(R.string.nick_in_use, conversation);
2122				}
2123			});
2124
2125			PresencePacket packet = new PresencePacket();
2126			packet.setTo(joinJid);
2127			packet.setFrom(conversation.getAccount().getJid());
2128
2129			String sig = account.getPgpSignature();
2130			if (sig != null) {
2131				packet.addChild("status").setContent("online");
2132				packet.addChild("x", "jabber:x:signed").setContent(sig);
2133			}
2134			sendPresencePacket(account, packet);
2135		} else {
2136			conversation.setContactJid(joinJid);
2137			databaseBackend.updateConversation(conversation);
2138			if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2139				Bookmark bookmark = conversation.getBookmark();
2140				if (bookmark != null) {
2141					bookmark.setNick(nick);
2142					pushBookmarks(bookmark.getAccount());
2143				}
2144				joinMuc(conversation);
2145			}
2146		}
2147	}
2148
2149	public void leaveMuc(Conversation conversation) {
2150		leaveMuc(conversation, false);
2151	}
2152
2153	private void leaveMuc(Conversation conversation, boolean now) {
2154		Account account = conversation.getAccount();
2155		account.pendingConferenceJoins.remove(conversation);
2156		account.pendingConferenceLeaves.remove(conversation);
2157		if (account.getStatus() == Account.State.ONLINE || now) {
2158			PresencePacket packet = new PresencePacket();
2159			packet.setTo(conversation.getMucOptions().getSelf().getFullJid());
2160			packet.setFrom(conversation.getAccount().getJid());
2161			packet.setAttribute("type", "unavailable");
2162			sendPresencePacket(conversation.getAccount(), packet);
2163			conversation.getMucOptions().setOffline();
2164			conversation.deregisterWithBookmark();
2165			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
2166					+ ": leaving muc " + conversation.getJid());
2167		} else {
2168			account.pendingConferenceLeaves.add(conversation);
2169		}
2170	}
2171
2172	private String findConferenceServer(final Account account) {
2173		String server;
2174		if (account.getXmppConnection() != null) {
2175			server = account.getXmppConnection().getMucServer();
2176			if (server != null) {
2177				return server;
2178			}
2179		}
2180		for (Account other : getAccounts()) {
2181			if (other != account && other.getXmppConnection() != null) {
2182				server = other.getXmppConnection().getMucServer();
2183				if (server != null) {
2184					return server;
2185				}
2186			}
2187		}
2188		return null;
2189	}
2190
2191	public void createAdhocConference(final Account account,
2192									  final String subject,
2193									  final Iterable<Jid> jids,
2194									  final UiCallback<Conversation> callback) {
2195		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2196		if (account.getStatus() == Account.State.ONLINE) {
2197			try {
2198				String server = findConferenceServer(account);
2199				if (server == null) {
2200					if (callback != null) {
2201						callback.error(R.string.no_conference_server_found, null);
2202					}
2203					return;
2204				}
2205				final Jid jid = Jid.fromParts(new BigInteger(64, getRNG()).toString(Character.MAX_RADIX), server, null);
2206				final Conversation conversation = findOrCreateConversation(account, jid, true);
2207				joinMuc(conversation, new OnConferenceJoined() {
2208					@Override
2209					public void onConferenceJoined(final Conversation conversation) {
2210						pushConferenceConfiguration(conversation, IqGenerator.defaultRoomConfiguration(), new OnConferenceOptionsPushed() {
2211							@Override
2212							public void onPushSucceeded() {
2213								if (subject != null && !subject.trim().isEmpty()) {
2214									pushSubjectToConference(conversation, subject.trim());
2215								}
2216								for (Jid invite : jids) {
2217									invite(conversation, invite);
2218								}
2219								if (account.countPresences() > 1) {
2220									directInvite(conversation, account.getJid().toBareJid());
2221								}
2222								saveConversationAsBookmark(conversation, subject);
2223								if (callback != null) {
2224									callback.success(conversation);
2225								}
2226							}
2227
2228							@Override
2229							public void onPushFailed() {
2230								archiveConversation(conversation);
2231								if (callback != null) {
2232									callback.error(R.string.conference_creation_failed, conversation);
2233								}
2234							}
2235						});
2236					}
2237				});
2238			} catch (InvalidJidException e) {
2239				if (callback != null) {
2240					callback.error(R.string.conference_creation_failed, null);
2241				}
2242			}
2243		} else {
2244			if (callback != null) {
2245				callback.error(R.string.not_connected_try_again, null);
2246			}
2247		}
2248	}
2249
2250	public void fetchConferenceConfiguration(final Conversation conversation) {
2251		fetchConferenceConfiguration(conversation, null);
2252	}
2253
2254	public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2255		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2256		request.setTo(conversation.getJid().toBareJid());
2257		request.query("http://jabber.org/protocol/disco#info");
2258		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2259			@Override
2260			public void onIqPacketReceived(Account account, IqPacket packet) {
2261				Element query = packet.findChild("query","http://jabber.org/protocol/disco#info");
2262				if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2263					ArrayList<String> features = new ArrayList<>();
2264					for (Element child : query.getChildren()) {
2265						if (child != null && child.getName().equals("feature")) {
2266							String var = child.getAttribute("var");
2267							if (var != null) {
2268								features.add(var);
2269							}
2270						}
2271					}
2272					Element form = query.findChild("x", "jabber:x:data");
2273					if (form != null) {
2274						conversation.getMucOptions().updateFormData(Data.parse(form));
2275					}
2276					conversation.getMucOptions().updateFeatures(features);
2277					if (callback != null) {
2278						callback.onConferenceConfigurationFetched(conversation);
2279					}
2280					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetched muc configuration for "+conversation.getJid().toBareJid()+" - "+features.toString());
2281					updateConversationUi();
2282				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
2283					if (callback != null) {
2284						callback.onFetchFailed(conversation, packet.getError());
2285					}
2286				}
2287			}
2288		});
2289	}
2290
2291	public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
2292		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2293		request.setTo(conversation.getJid().toBareJid());
2294		request.query("http://jabber.org/protocol/muc#owner");
2295		sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2296			@Override
2297			public void onIqPacketReceived(Account account, IqPacket packet) {
2298				if (packet.getType() == IqPacket.TYPE.RESULT) {
2299					Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
2300					for (Field field : data.getFields()) {
2301						if (options.containsKey(field.getFieldName())) {
2302							field.setValue(options.getString(field.getFieldName()));
2303						}
2304					}
2305					data.submit();
2306					IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2307					set.setTo(conversation.getJid().toBareJid());
2308					set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2309					sendIqPacket(account, set, new OnIqPacketReceived() {
2310						@Override
2311						public void onIqPacketReceived(Account account, IqPacket packet) {
2312							if (callback != null) {
2313								if (packet.getType() == IqPacket.TYPE.RESULT) {
2314									callback.onPushSucceeded();
2315								} else {
2316									callback.onPushFailed();
2317								}
2318							}
2319						}
2320					});
2321				} else {
2322					if (callback != null) {
2323						callback.onPushFailed();
2324					}
2325				}
2326			}
2327		});
2328	}
2329
2330	public void pushSubjectToConference(final Conversation conference, final String subject) {
2331		MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2332		this.sendMessagePacket(conference.getAccount(), packet);
2333		final MucOptions mucOptions = conference.getMucOptions();
2334		final MucOptions.User self = mucOptions.getSelf();
2335		if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2336			Bundle options = new Bundle();
2337			options.putString("muc#roomconfig_persistentroom", "1");
2338			this.pushConferenceConfiguration(conference, options, null);
2339		}
2340	}
2341
2342	public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2343		final Jid jid = user.toBareJid();
2344		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2345		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2346			@Override
2347			public void onIqPacketReceived(Account account, IqPacket packet) {
2348				if (packet.getType() == IqPacket.TYPE.RESULT) {
2349					conference.getMucOptions().changeAffiliation(jid, affiliation);
2350					getAvatarService().clear(conference);
2351					callback.onAffiliationChangedSuccessful(jid);
2352				} else {
2353					callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2354				}
2355			}
2356		});
2357	}
2358
2359	public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2360		List<Jid> jids = new ArrayList<>();
2361		for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2362			if (user.getAffiliation() == before && user.getRealJid() != null) {
2363				jids.add(user.getRealJid());
2364			}
2365		}
2366		IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2367		sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2368	}
2369
2370	public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2371		IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2372		Log.d(Config.LOGTAG, request.toString());
2373		sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2374			@Override
2375			public void onIqPacketReceived(Account account, IqPacket packet) {
2376				Log.d(Config.LOGTAG, packet.toString());
2377				if (packet.getType() == IqPacket.TYPE.RESULT) {
2378					callback.onRoleChangedSuccessful(nick);
2379				} else {
2380					callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2381				}
2382			}
2383		});
2384	}
2385
2386	private void disconnect(Account account, boolean force) {
2387		if ((account.getStatus() == Account.State.ONLINE)
2388				|| (account.getStatus() == Account.State.DISABLED)) {
2389			final XmppConnection connection = account.getXmppConnection();
2390			if (!force) {
2391				List<Conversation> conversations = getConversations();
2392				for (Conversation conversation : conversations) {
2393					if (conversation.getAccount() == account) {
2394						if (conversation.getMode() == Conversation.MODE_MULTI) {
2395							leaveMuc(conversation, true);
2396						} else {
2397							if (conversation.endOtrIfNeeded()) {
2398								Log.d(Config.LOGTAG, account.getJid().toBareJid()
2399										+ ": ended otr session with "
2400										+ conversation.getJid());
2401							}
2402						}
2403					}
2404				}
2405				sendOfflinePresence(account);
2406			}
2407			connection.disconnect(force);
2408		}
2409	}
2410
2411	@Override
2412	public IBinder onBind(Intent intent) {
2413		return mBinder;
2414	}
2415
2416	public void updateMessage(Message message) {
2417		databaseBackend.updateMessage(message);
2418		updateConversationUi();
2419	}
2420
2421	public void updateMessage(Message message, String uuid) {
2422		databaseBackend.updateMessage(message, uuid);
2423		updateConversationUi();
2424	}
2425
2426	protected void syncDirtyContacts(Account account) {
2427		for (Contact contact : account.getRoster().getContacts()) {
2428			if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2429				pushContactToServer(contact);
2430			}
2431			if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2432				deleteContactOnServer(contact);
2433			}
2434		}
2435	}
2436
2437	public void createContact(Contact contact) {
2438		boolean autoGrant = getPreferences().getBoolean("grant_new_contacts", true);
2439		if (autoGrant) {
2440			contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2441			contact.setOption(Contact.Options.ASKING);
2442		}
2443		pushContactToServer(contact);
2444	}
2445
2446	public void onOtrSessionEstablished(Conversation conversation) {
2447		final Account account = conversation.getAccount();
2448		final Session otrSession = conversation.getOtrSession();
2449		Log.d(Config.LOGTAG,
2450				account.getJid().toBareJid() + " otr session established with "
2451						+ conversation.getJid() + "/"
2452						+ otrSession.getSessionID().getUserID());
2453		conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2454
2455			@Override
2456			public void onMessageFound(Message message) {
2457				SessionID id = otrSession.getSessionID();
2458				try {
2459					message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2460				} catch (InvalidJidException e) {
2461					return;
2462				}
2463				if (message.needsUploading()) {
2464					mJingleConnectionManager.createNewConnection(message);
2465				} else {
2466					MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2467					if (outPacket != null) {
2468						mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2469						message.setStatus(Message.STATUS_SEND);
2470						databaseBackend.updateMessage(message);
2471						sendMessagePacket(account, outPacket);
2472					}
2473				}
2474				updateConversationUi();
2475			}
2476		});
2477	}
2478
2479	public boolean renewSymmetricKey(Conversation conversation) {
2480		Account account = conversation.getAccount();
2481		byte[] symmetricKey = new byte[32];
2482		this.mRandom.nextBytes(symmetricKey);
2483		Session otrSession = conversation.getOtrSession();
2484		if (otrSession != null) {
2485			MessagePacket packet = new MessagePacket();
2486			packet.setType(MessagePacket.TYPE_CHAT);
2487			packet.setFrom(account.getJid());
2488			MessageGenerator.addMessageHints(packet);
2489			packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2490					+ otrSession.getSessionID().getUserID());
2491			try {
2492				packet.setBody(otrSession
2493						.transformSending(CryptoHelper.FILETRANSFER
2494								+ CryptoHelper.bytesToHex(symmetricKey))[0]);
2495				sendMessagePacket(account, packet);
2496				conversation.setSymmetricKey(symmetricKey);
2497				return true;
2498			} catch (OtrException e) {
2499				return false;
2500			}
2501		}
2502		return false;
2503	}
2504
2505	public void pushContactToServer(final Contact contact) {
2506		contact.resetOption(Contact.Options.DIRTY_DELETE);
2507		contact.setOption(Contact.Options.DIRTY_PUSH);
2508		final Account account = contact.getAccount();
2509		if (account.getStatus() == Account.State.ONLINE) {
2510			final boolean ask = contact.getOption(Contact.Options.ASKING);
2511			final boolean sendUpdates = contact
2512					.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2513					&& contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2514			final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2515			iq.query(Xmlns.ROSTER).addChild(contact.asElement());
2516			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2517			if (sendUpdates) {
2518				sendPresencePacket(account,
2519						mPresenceGenerator.sendPresenceUpdatesTo(contact));
2520			}
2521			if (ask) {
2522				sendPresencePacket(account,
2523						mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2524			}
2525		}
2526	}
2527
2528	public void publishAvatar(Account account, Uri image, UiCallback<Avatar> callback) {
2529		final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2530		final int size = Config.AVATAR_SIZE;
2531		final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2532		if (avatar != null) {
2533			avatar.height = size;
2534			avatar.width = size;
2535			if (format.equals(Bitmap.CompressFormat.WEBP)) {
2536				avatar.type = "image/webp";
2537			} else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2538				avatar.type = "image/jpeg";
2539			} else if (format.equals(Bitmap.CompressFormat.PNG)) {
2540				avatar.type = "image/png";
2541			}
2542			if (!getFileBackend().save(avatar)) {
2543				callback.error(R.string.error_saving_avatar, avatar);
2544				return;
2545			}
2546			publishAvatar(account, avatar, callback);
2547		} else {
2548			callback.error(R.string.error_publish_avatar_converting, null);
2549		}
2550	}
2551
2552	public void publishAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2553		final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2554		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2555
2556			@Override
2557			public void onIqPacketReceived(Account account, IqPacket result) {
2558				if (result.getType() == IqPacket.TYPE.RESULT) {
2559					final IqPacket packet = XmppConnectionService.this.mIqGenerator
2560							.publishAvatarMetadata(avatar);
2561					sendIqPacket(account, packet, new OnIqPacketReceived() {
2562						@Override
2563						public void onIqPacketReceived(Account account, IqPacket result) {
2564							if (result.getType() == IqPacket.TYPE.RESULT) {
2565								if (account.setAvatar(avatar.getFilename())) {
2566									getAvatarService().clear(account);
2567									databaseBackend.updateAccount(account);
2568								}
2569								if (callback != null) {
2570									callback.success(avatar);
2571								} else {
2572									Log.d(Config.LOGTAG,account.getJid().toBareJid()+": published avatar");
2573								}
2574							} else {
2575								if (callback != null) {
2576									callback.error(
2577											R.string.error_publish_avatar_server_reject,
2578											avatar);
2579								}
2580							}
2581						}
2582					});
2583				} else {
2584					if (callback != null) {
2585						callback.error(
2586								R.string.error_publish_avatar_server_reject,
2587								avatar);
2588					}
2589				}
2590			}
2591		});
2592	}
2593
2594	public void republishAvatarIfNeeded(Account account) {
2595		if (account.getAxolotlService().isPepBroken()) {
2596			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": skipping republication of avatar because pep is broken");
2597			return;
2598		}
2599		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2600		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2601
2602			private Avatar parseAvatar(IqPacket packet) {
2603				Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2604				if (pubsub != null) {
2605					Element items = pubsub.findChild("items");
2606					if (items != null) {
2607						return Avatar.parseMetadata(items);
2608					}
2609				}
2610				return null;
2611			}
2612
2613			private boolean errorIsItemNotFound(IqPacket packet) {
2614				Element error = packet.findChild("error");
2615				return packet.getType() == IqPacket.TYPE.ERROR
2616						&& error != null
2617						&& error.hasChild("item-not-found");
2618			}
2619
2620			@Override
2621			public void onIqPacketReceived(Account account, IqPacket packet) {
2622				if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2623					Avatar serverAvatar = parseAvatar(packet);
2624					if (serverAvatar == null && account.getAvatar() != null) {
2625						Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2626						if (avatar != null) {
2627							Log.d(Config.LOGTAG,account.getJid().toBareJid()+": avatar on server was null. republishing");
2628							publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2629						} else {
2630							Log.e(Config.LOGTAG, account.getJid().toBareJid()+": error rereading avatar");
2631						}
2632					}
2633				}
2634			}
2635		});
2636	}
2637
2638	public void fetchAvatar(Account account, Avatar avatar) {
2639		fetchAvatar(account, avatar, null);
2640	}
2641
2642	public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2643		final String KEY = generateFetchKey(account, avatar);
2644		synchronized (this.mInProgressAvatarFetches) {
2645			if (!this.mInProgressAvatarFetches.contains(KEY)) {
2646				switch (avatar.origin) {
2647					case PEP:
2648						this.mInProgressAvatarFetches.add(KEY);
2649						fetchAvatarPep(account, avatar, callback);
2650						break;
2651					case VCARD:
2652						this.mInProgressAvatarFetches.add(KEY);
2653						fetchAvatarVcard(account, avatar, callback);
2654						break;
2655				}
2656			}
2657		}
2658	}
2659
2660	private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2661		IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2662		sendIqPacket(account, packet, new OnIqPacketReceived() {
2663
2664			@Override
2665			public void onIqPacketReceived(Account account, IqPacket result) {
2666				synchronized (mInProgressAvatarFetches) {
2667					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2668				}
2669				final String ERROR = account.getJid().toBareJid()
2670						+ ": fetching avatar for " + avatar.owner + " failed ";
2671				if (result.getType() == IqPacket.TYPE.RESULT) {
2672					avatar.image = mIqParser.avatarData(result);
2673					if (avatar.image != null) {
2674						if (getFileBackend().save(avatar)) {
2675							if (account.getJid().toBareJid().equals(avatar.owner)) {
2676								if (account.setAvatar(avatar.getFilename())) {
2677									databaseBackend.updateAccount(account);
2678								}
2679								getAvatarService().clear(account);
2680								updateConversationUi();
2681								updateAccountUi();
2682							} else {
2683								Contact contact = account.getRoster()
2684										.getContact(avatar.owner);
2685								contact.setAvatar(avatar);
2686								getAvatarService().clear(contact);
2687								updateConversationUi();
2688								updateRosterUi();
2689							}
2690							if (callback != null) {
2691								callback.success(avatar);
2692							}
2693							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2694									+ ": successfully fetched pep avatar for " + avatar.owner);
2695							return;
2696						}
2697					} else {
2698
2699						Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2700					}
2701				} else {
2702					Element error = result.findChild("error");
2703					if (error == null) {
2704						Log.d(Config.LOGTAG, ERROR + "(server error)");
2705					} else {
2706						Log.d(Config.LOGTAG, ERROR + error.toString());
2707					}
2708				}
2709				if (callback != null) {
2710					callback.error(0, null);
2711				}
2712
2713			}
2714		});
2715	}
2716
2717	private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2718		IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2719		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2720			@Override
2721			public void onIqPacketReceived(Account account, IqPacket packet) {
2722				synchronized (mInProgressAvatarFetches) {
2723					mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2724				}
2725				if (packet.getType() == IqPacket.TYPE.RESULT) {
2726					Element vCard = packet.findChild("vCard", "vcard-temp");
2727					Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2728					String image = photo != null ? photo.findChildContent("BINVAL") : null;
2729					if (image != null) {
2730						avatar.image = image;
2731						if (getFileBackend().save(avatar)) {
2732							Log.d(Config.LOGTAG, account.getJid().toBareJid()
2733									+ ": successfully fetched vCard avatar for " + avatar.owner);
2734							if (avatar.owner.isBareJid()) {
2735								Contact contact = account.getRoster()
2736										.getContact(avatar.owner);
2737								contact.setAvatar(avatar);
2738								getAvatarService().clear(contact);
2739								updateConversationUi();
2740								updateRosterUi();
2741							} else {
2742								Conversation conversation = find(account, avatar.owner.toBareJid());
2743								if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
2744									MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
2745									if (user != null) {
2746										if (user.setAvatar(avatar)) {
2747											getAvatarService().clear(user);
2748											updateConversationUi();
2749											updateMucRosterUi();
2750										}
2751									}
2752								}
2753							}
2754						}
2755					}
2756				}
2757			}
2758		});
2759	}
2760
2761	public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2762		IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2763		this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2764
2765			@Override
2766			public void onIqPacketReceived(Account account, IqPacket packet) {
2767				if (packet.getType() == IqPacket.TYPE.RESULT) {
2768					Element pubsub = packet.findChild("pubsub","http://jabber.org/protocol/pubsub");
2769					if (pubsub != null) {
2770						Element items = pubsub.findChild("items");
2771						if (items != null) {
2772							Avatar avatar = Avatar.parseMetadata(items);
2773							if (avatar != null) {
2774								avatar.owner = account.getJid().toBareJid();
2775								if (fileBackend.isAvatarCached(avatar)) {
2776									if (account.setAvatar(avatar.getFilename())) {
2777										databaseBackend.updateAccount(account);
2778									}
2779									getAvatarService().clear(account);
2780									callback.success(avatar);
2781								} else {
2782									fetchAvatarPep(account, avatar, callback);
2783								}
2784								return;
2785							}
2786						}
2787					}
2788				}
2789				callback.error(0, null);
2790			}
2791		});
2792	}
2793
2794	public void deleteContactOnServer(Contact contact) {
2795		contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2796		contact.resetOption(Contact.Options.DIRTY_PUSH);
2797		contact.setOption(Contact.Options.DIRTY_DELETE);
2798		Account account = contact.getAccount();
2799		if (account.getStatus() == Account.State.ONLINE) {
2800			IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2801			Element item = iq.query(Xmlns.ROSTER).addChild("item");
2802			item.setAttribute("jid", contact.getJid().toString());
2803			item.setAttribute("subscription", "remove");
2804			account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2805		}
2806	}
2807
2808	public void updateConversation(Conversation conversation) {
2809		this.databaseBackend.updateConversation(conversation);
2810	}
2811
2812	private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2813		synchronized (account) {
2814			XmppConnection connection = account.getXmppConnection();
2815			if (connection == null) {
2816				connection = createConnection(account);
2817				account.setXmppConnection(connection);
2818			} else {
2819				connection.interrupt();
2820			}
2821			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2822				if (!force) {
2823					disconnect(account, false);
2824				}
2825				Thread thread = new Thread(connection);
2826				connection.setInteractive(interactive);
2827				connection.prepareNewConnection();
2828				thread.start();
2829				scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2830			} else {
2831				disconnect(account, force);
2832				account.getRoster().clearPresences();
2833				connection.resetEverything();
2834				account.getAxolotlService().resetBrokenness();
2835			}
2836		}
2837	}
2838
2839	public void reconnectAccountInBackground(final Account account) {
2840		new Thread(new Runnable() {
2841			@Override
2842			public void run() {
2843				reconnectAccount(account, false, true);
2844			}
2845		}).start();
2846	}
2847
2848	public void invite(Conversation conversation, Jid contact) {
2849		Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
2850		MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2851		sendMessagePacket(conversation.getAccount(), packet);
2852	}
2853
2854	public void directInvite(Conversation conversation, Jid jid) {
2855		MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2856		sendMessagePacket(conversation.getAccount(), packet);
2857	}
2858
2859	public void resetSendingToWaiting(Account account) {
2860		for (Conversation conversation : getConversations()) {
2861			if (conversation.getAccount() == account) {
2862				conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2863
2864					@Override
2865					public void onMessageFound(Message message) {
2866						markMessage(message, Message.STATUS_WAITING);
2867					}
2868				});
2869			}
2870		}
2871	}
2872
2873	public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2874		if (uuid == null) {
2875			return null;
2876		}
2877		for (Conversation conversation : getConversations()) {
2878			if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2879				final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
2880				if (message != null) {
2881					markMessage(message, status);
2882				}
2883				return message;
2884			}
2885		}
2886		return null;
2887	}
2888
2889	public boolean markMessage(Conversation conversation, String uuid, int status) {
2890		if (uuid == null) {
2891			return false;
2892		} else {
2893			Message message = conversation.findSentMessageWithUuid(uuid);
2894			if (message != null) {
2895				markMessage(message, status);
2896				return true;
2897			} else {
2898				return false;
2899			}
2900		}
2901	}
2902
2903	public void markMessage(Message message, int status) {
2904		if (status == Message.STATUS_SEND_FAILED
2905				&& (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2906				.getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2907			return;
2908		}
2909		message.setStatus(status);
2910		databaseBackend.updateMessage(message);
2911		updateConversationUi();
2912	}
2913
2914	public SharedPreferences getPreferences() {
2915		return PreferenceManager
2916				.getDefaultSharedPreferences(getApplicationContext());
2917	}
2918
2919	public boolean confirmMessages() {
2920		return getPreferences().getBoolean("confirm_messages", true);
2921	}
2922
2923	public boolean allowMessageCorrection() {
2924		return getPreferences().getBoolean("allow_message_correction", true);
2925	}
2926
2927	public boolean sendChatStates() {
2928		return getPreferences().getBoolean("chat_states", false);
2929	}
2930
2931	public boolean saveEncryptedMessages() {
2932		return !getPreferences().getBoolean("dont_save_encrypted", false);
2933	}
2934
2935	private boolean respectAutojoin() {
2936		return getPreferences().getBoolean("autojoin", true);
2937	}
2938
2939	public boolean indicateReceived() {
2940		return getPreferences().getBoolean("indicate_received", false);
2941	}
2942
2943	public boolean useTorToConnect() {
2944		return Config.FORCE_ORBOT || getPreferences().getBoolean("use_tor", false);
2945	}
2946
2947	public boolean showExtendedConnectionOptions() {
2948		return getPreferences().getBoolean("show_connection_options", false);
2949	}
2950
2951	public boolean broadcastLastActivity() {
2952		return getPreferences().getBoolean("last_activity", false);
2953	}
2954
2955	public int unreadCount() {
2956		int count = 0;
2957		for (Conversation conversation : getConversations()) {
2958			count += conversation.unreadCount();
2959		}
2960		return count;
2961	}
2962
2963
2964	public void showErrorToastInUi(int resId) {
2965		if (mOnShowErrorToast != null) {
2966			mOnShowErrorToast.onShowErrorToast(resId);
2967		}
2968	}
2969
2970	public void updateConversationUi() {
2971		if (mOnConversationUpdate != null) {
2972			mOnConversationUpdate.onConversationUpdate();
2973		}
2974	}
2975
2976	public void updateAccountUi() {
2977		if (mOnAccountUpdate != null) {
2978			mOnAccountUpdate.onAccountUpdate();
2979		}
2980	}
2981
2982	public void updateRosterUi() {
2983		if (mOnRosterUpdate != null) {
2984			mOnRosterUpdate.onRosterUpdate();
2985		}
2986	}
2987
2988	public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
2989		if (mOnCaptchaRequested != null) {
2990			DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
2991			Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
2992					(int) (captcha.getHeight() * metrics.scaledDensity), false);
2993
2994			mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
2995			return true;
2996		}
2997		return false;
2998	}
2999
3000	public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3001		if (mOnUpdateBlocklist != null) {
3002			mOnUpdateBlocklist.OnUpdateBlocklist(status);
3003		}
3004	}
3005
3006	public void updateMucRosterUi() {
3007		if (mOnMucRosterUpdate != null) {
3008			mOnMucRosterUpdate.onMucRosterUpdate();
3009		}
3010	}
3011
3012	public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3013		if (mOnKeyStatusUpdated != null) {
3014			mOnKeyStatusUpdated.onKeyStatusUpdated(report);
3015		}
3016	}
3017
3018	public Account findAccountByJid(final Jid accountJid) {
3019		for (Account account : this.accounts) {
3020			if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
3021				return account;
3022			}
3023		}
3024		return null;
3025	}
3026
3027	public Conversation findConversationByUuid(String uuid) {
3028		for (Conversation conversation : getConversations()) {
3029			if (conversation.getUuid().equals(uuid)) {
3030				return conversation;
3031			}
3032		}
3033		return null;
3034	}
3035
3036	public boolean markRead(final Conversation conversation) {
3037		return markRead(conversation,true);
3038	}
3039
3040	public boolean markRead(final Conversation conversation, boolean clear) {
3041		if (clear) {
3042			mNotificationService.clear(conversation);
3043		}
3044		final List<Message> readMessages = conversation.markRead();
3045		if (readMessages.size() > 0) {
3046			Runnable runnable = new Runnable() {
3047				@Override
3048				public void run() {
3049					for (Message message : readMessages) {
3050						databaseBackend.updateMessage(message);
3051					}
3052				}
3053			};
3054			mDatabaseExecutor.execute(runnable);
3055			updateUnreadCountBadge();
3056			return true;
3057		} else {
3058			return false;
3059		}
3060	}
3061
3062	public synchronized void updateUnreadCountBadge() {
3063		int count = unreadCount();
3064		if (unreadCount != count) {
3065			Log.d(Config.LOGTAG, "update unread count to " + count);
3066			if (count > 0) {
3067				ShortcutBadger.applyCount(getApplicationContext(), count);
3068			} else {
3069				ShortcutBadger.removeCount(getApplicationContext());
3070			}
3071			unreadCount = count;
3072		}
3073	}
3074
3075	public void sendReadMarker(final Conversation conversation) {
3076		final Message markable = conversation.getLatestMarkableMessage();
3077		if (this.markRead(conversation)) {
3078			updateConversationUi();
3079		}
3080		if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
3081			Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
3082			Account account = conversation.getAccount();
3083			final Jid to = markable.getCounterpart();
3084			MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
3085			this.sendMessagePacket(conversation.getAccount(), packet);
3086		}
3087	}
3088
3089	public SecureRandom getRNG() {
3090		return this.mRandom;
3091	}
3092
3093	public MemorizingTrustManager getMemorizingTrustManager() {
3094		return this.mMemorizingTrustManager;
3095	}
3096
3097	public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
3098		this.mMemorizingTrustManager = trustManager;
3099	}
3100
3101	public void updateMemorizingTrustmanager() {
3102		final MemorizingTrustManager tm;
3103		final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
3104		if (dontTrustSystemCAs) {
3105			tm = new MemorizingTrustManager(getApplicationContext(), null);
3106		} else {
3107			tm = new MemorizingTrustManager(getApplicationContext());
3108		}
3109		setMemorizingTrustManager(tm);
3110	}
3111
3112	public PowerManager getPowerManager() {
3113		return this.pm;
3114	}
3115
3116	public LruCache<String, Bitmap> getBitmapCache() {
3117		return this.mBitmapCache;
3118	}
3119
3120	public void syncRosterToDisk(final Account account) {
3121		Runnable runnable = new Runnable() {
3122
3123			@Override
3124			public void run() {
3125				databaseBackend.writeRoster(account.getRoster());
3126			}
3127		};
3128		mDatabaseExecutor.execute(runnable);
3129
3130	}
3131
3132	public List<String> getKnownHosts() {
3133		final List<String> hosts = new ArrayList<>();
3134		for (final Account account : getAccounts()) {
3135			if (!hosts.contains(account.getServer().toString())) {
3136				hosts.add(account.getServer().toString());
3137			}
3138			for (final Contact contact : account.getRoster().getContacts()) {
3139				if (contact.showInRoster()) {
3140					final String server = contact.getServer().toString();
3141					if (server != null && !hosts.contains(server)) {
3142						hosts.add(server);
3143					}
3144				}
3145			}
3146		}
3147		if(Config.DOMAIN_LOCK != null && !hosts.contains(Config.DOMAIN_LOCK)) {
3148			hosts.add(Config.DOMAIN_LOCK);
3149		}
3150		if(Config.MAGIC_CREATE_DOMAIN != null && !hosts.contains(Config.MAGIC_CREATE_DOMAIN)) {
3151			hosts.add(Config.MAGIC_CREATE_DOMAIN);
3152		}
3153		return hosts;
3154	}
3155
3156	public List<String> getKnownConferenceHosts() {
3157		final ArrayList<String> mucServers = new ArrayList<>();
3158		for (final Account account : accounts) {
3159			if (account.getXmppConnection() != null) {
3160				final String server = account.getXmppConnection().getMucServer();
3161				if (server != null && !mucServers.contains(server)) {
3162					mucServers.add(server);
3163				}
3164			}
3165		}
3166		return mucServers;
3167	}
3168
3169	public void sendMessagePacket(Account account, MessagePacket packet) {
3170		XmppConnection connection = account.getXmppConnection();
3171		if (connection != null) {
3172			connection.sendMessagePacket(packet);
3173		}
3174	}
3175
3176	public void sendPresencePacket(Account account, PresencePacket packet) {
3177		XmppConnection connection = account.getXmppConnection();
3178		if (connection != null) {
3179			connection.sendPresencePacket(packet);
3180		}
3181	}
3182
3183	public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3184		final XmppConnection connection = account.getXmppConnection();
3185		if (connection != null) {
3186			IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3187			connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener);
3188		}
3189	}
3190
3191	public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3192		final XmppConnection connection = account.getXmppConnection();
3193		if (connection != null) {
3194			connection.sendIqPacket(packet, callback);
3195		}
3196	}
3197
3198	public void sendPresence(final Account account) {
3199		sendPresence(account, checkListeners() && broadcastLastActivity());
3200	}
3201
3202	private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3203		PresencePacket packet;
3204		if (manuallyChangePresence()) {
3205			packet =  mPresenceGenerator.selfPresence(account, account.getPresenceStatus());
3206			String message = account.getPresenceStatusMessage();
3207			if (message != null && !message.isEmpty()) {
3208				packet.addChild(new Element("status").setContent(message));
3209			}
3210		} else {
3211			packet = mPresenceGenerator.selfPresence(account, getTargetPresence());
3212		}
3213		if (mLastActivity > 0 && includeIdleTimestamp) {
3214			long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3215			packet.addChild("idle","urn:xmpp:idle:1").setAttribute("since", AbstractGenerator.getTimestamp(since));
3216		}
3217		sendPresencePacket(account, packet);
3218	}
3219
3220	private void deactivateGracePeriod() {
3221		for(Account account : getAccounts()) {
3222			account.deactivateGracePeriod();
3223		}
3224	}
3225
3226	public void refreshAllPresences() {
3227		boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3228		for (Account account : getAccounts()) {
3229			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3230				sendPresence(account, includeIdleTimestamp);
3231			}
3232		}
3233	}
3234
3235	private void refreshAllGcmTokens() {
3236		for(Account account : getAccounts()) {
3237			if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3238				mPushManagementService.registerPushTokenOnServer(account);
3239			}
3240		}
3241	}
3242
3243	public void sendOfflinePresence(final Account account) {
3244		sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3245	}
3246
3247	public MessageGenerator getMessageGenerator() {
3248		return this.mMessageGenerator;
3249	}
3250
3251	public PresenceGenerator getPresenceGenerator() {
3252		return this.mPresenceGenerator;
3253	}
3254
3255	public IqGenerator getIqGenerator() {
3256		return this.mIqGenerator;
3257	}
3258
3259	public IqParser getIqParser() {
3260		return this.mIqParser;
3261	}
3262
3263	public JingleConnectionManager getJingleConnectionManager() {
3264		return this.mJingleConnectionManager;
3265	}
3266
3267	public MessageArchiveService getMessageArchiveService() {
3268		return this.mMessageArchiveService;
3269	}
3270
3271	public List<Contact> findContacts(Jid jid) {
3272		ArrayList<Contact> contacts = new ArrayList<>();
3273		for (Account account : getAccounts()) {
3274			if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3275				Contact contact = account.getRoster().getContactFromRoster(jid);
3276				if (contact != null) {
3277					contacts.add(contact);
3278				}
3279			}
3280		}
3281		return contacts;
3282	}
3283
3284	public Conversation findFirstMuc(Jid jid) {
3285		for(Conversation conversation : getConversations()) {
3286			if (conversation.getJid().toBareJid().equals(jid.toBareJid())
3287					&& conversation.getMode() == Conversation.MODE_MULTI) {
3288				return conversation;
3289			}
3290		}
3291		return null;
3292	}
3293
3294	public NotificationService getNotificationService() {
3295		return this.mNotificationService;
3296	}
3297
3298	public HttpConnectionManager getHttpConnectionManager() {
3299		return this.mHttpConnectionManager;
3300	}
3301
3302	public void resendFailedMessages(final Message message) {
3303		final Collection<Message> messages = new ArrayList<>();
3304		Message current = message;
3305		while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3306			messages.add(current);
3307			if (current.mergeable(current.next())) {
3308				current = current.next();
3309			} else {
3310				break;
3311			}
3312		}
3313		for (final Message msg : messages) {
3314			msg.setTime(System.currentTimeMillis());
3315			markMessage(msg, Message.STATUS_WAITING);
3316			this.resendMessage(msg, false);
3317		}
3318	}
3319
3320	public void clearConversationHistory(final Conversation conversation) {
3321		conversation.clearMessages();
3322		conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3323		conversation.setLastClearHistory(System.currentTimeMillis());
3324		Runnable runnable = new Runnable() {
3325			@Override
3326			public void run() {
3327				databaseBackend.deleteMessagesInConversation(conversation);
3328			}
3329		};
3330		mDatabaseExecutor.execute(runnable);
3331	}
3332
3333	public void sendBlockRequest(final Blockable blockable) {
3334		if (blockable != null && blockable.getBlockedJid() != null) {
3335			final Jid jid = blockable.getBlockedJid();
3336			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
3337
3338				@Override
3339				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3340					if (packet.getType() == IqPacket.TYPE.RESULT) {
3341						account.getBlocklist().add(jid);
3342						updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3343					}
3344				}
3345			});
3346		}
3347	}
3348
3349	public void sendUnblockRequest(final Blockable blockable) {
3350		if (blockable != null && blockable.getJid() != null) {
3351			final Jid jid = blockable.getBlockedJid();
3352			this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3353				@Override
3354				public void onIqPacketReceived(final Account account, final IqPacket packet) {
3355					if (packet.getType() == IqPacket.TYPE.RESULT) {
3356						account.getBlocklist().remove(jid);
3357						updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3358					}
3359				}
3360			});
3361		}
3362	}
3363
3364	public void publishDisplayName(Account account) {
3365		String displayName = account.getDisplayName();
3366		if (displayName != null && !displayName.isEmpty()) {
3367			IqPacket publish = mIqGenerator.publishNick(displayName);
3368			sendIqPacket(account, publish, new OnIqPacketReceived() {
3369				@Override
3370				public void onIqPacketReceived(Account account, IqPacket packet) {
3371					if (packet.getType() == IqPacket.TYPE.ERROR) {
3372						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not publish nick");
3373					}
3374				}
3375			});
3376		}
3377	}
3378
3379	public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
3380		ServiceDiscoveryResult result = discoCache.get(key);
3381		if (result != null) {
3382			return result;
3383		} else {
3384			result = databaseBackend.findDiscoveryResult(key.first, key.second);
3385			if (result != null) {
3386				discoCache.put(key, result);
3387			}
3388			return result;
3389		}
3390	}
3391
3392	public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3393		final Pair<String,String> key = new Pair<>(presence.getHash(), presence.getVer());
3394		ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3395		if (disco != null) {
3396			presence.setServiceDiscoveryResult(disco);
3397		} else {
3398			if (!account.inProgressDiscoFetches.contains(key)) {
3399				account.inProgressDiscoFetches.add(key);
3400				IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3401				request.setTo(jid);
3402				request.query("http://jabber.org/protocol/disco#info");
3403				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": making disco request for "+key.second+" to "+jid);
3404				sendIqPacket(account, request, new OnIqPacketReceived() {
3405					@Override
3406					public void onIqPacketReceived(Account account, IqPacket discoPacket) {
3407						if (discoPacket.getType() == IqPacket.TYPE.RESULT) {
3408							ServiceDiscoveryResult disco = new ServiceDiscoveryResult(discoPacket);
3409							if (presence.getVer().equals(disco.getVer())) {
3410								databaseBackend.insertDiscoveryResult(disco);
3411								injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco);
3412							} else {
3413								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco.getVer());
3414							}
3415						}
3416						account.inProgressDiscoFetches.remove(key);
3417					}
3418				});
3419			}
3420		}
3421	}
3422
3423	private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3424		for(Contact contact : roster.getContacts()) {
3425			for(Presence presence : contact.getPresences().getPresences().values()) {
3426				if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3427					presence.setServiceDiscoveryResult(disco);
3428				}
3429			}
3430		}
3431	}
3432
3433	public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3434		IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3435		request.addChild("prefs","urn:xmpp:mam:0");
3436		sendIqPacket(account, request, new OnIqPacketReceived() {
3437			@Override
3438			public void onIqPacketReceived(Account account, IqPacket packet) {
3439				Element prefs = packet.findChild("prefs","urn:xmpp:mam:0");
3440				if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3441					callback.onPreferencesFetched(prefs);
3442				} else {
3443					callback.onPreferencesFetchFailed();
3444				}
3445			}
3446		});
3447	}
3448
3449	public PushManagementService getPushManagementService() {
3450		return mPushManagementService;
3451	}
3452
3453	public Account getPendingAccount() {
3454		Account pending = null;
3455		for(Account account : getAccounts()) {
3456			if (account.isOptionSet(Account.OPTION_REGISTER)) {
3457				pending = account;
3458			} else {
3459				return null;
3460			}
3461		}
3462		return pending;
3463	}
3464
3465	public void changeStatus(Account account, Presence.Status status, String statusMessage, boolean send) {
3466		if (!statusMessage.isEmpty()) {
3467			databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3468		}
3469		changeStatusReal(account, status, statusMessage, send);
3470	}
3471
3472	private void changeStatusReal(Account account, Presence.Status status, String statusMessage, boolean send) {
3473		account.setPresenceStatus(status);
3474		account.setPresenceStatusMessage(statusMessage);
3475		databaseBackend.updateAccount(account);
3476		if (!account.isOptionSet(Account.OPTION_DISABLED) && send) {
3477			sendPresence(account);
3478		}
3479	}
3480
3481	public void changeStatus(Presence.Status status, String statusMessage) {
3482		if (!statusMessage.isEmpty()) {
3483			databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3484		}
3485		for(Account account : getAccounts()) {
3486			changeStatusReal(account, status, statusMessage, true);
3487		}
3488	}
3489
3490	public List<PresenceTemplate> getPresenceTemplates(Account account) {
3491		List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3492		for(PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3493			if (!templates.contains(template)) {
3494				templates.add(0, template);
3495			}
3496		}
3497		return templates;
3498	}
3499
3500	public void saveConversationAsBookmark(Conversation conversation, String name) {
3501		Account account = conversation.getAccount();
3502		Bookmark bookmark = new Bookmark(account, conversation.getJid().toBareJid());
3503		if (!conversation.getJid().isBareJid()) {
3504			bookmark.setNick(conversation.getJid().getResourcepart());
3505		}
3506		if (name != null && !name.trim().isEmpty()) {
3507			bookmark.setBookmarkName(name.trim());
3508		}
3509		bookmark.setAutojoin(getPreferences().getBoolean("autojoin",true));
3510		account.getBookmarks().add(bookmark);
3511		pushBookmarks(account);
3512		conversation.setBookmark(bookmark);
3513	}
3514
3515	public interface OnMamPreferencesFetched {
3516		void onPreferencesFetched(Element prefs);
3517		void onPreferencesFetchFailed();
3518	}
3519
3520	public void pushMamPreferences(Account account, Element prefs) {
3521		IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3522		set.addChild(prefs);
3523		sendIqPacket(account, set, null);
3524	}
3525
3526	public interface OnAccountCreated {
3527		void onAccountCreated(Account account);
3528
3529		void informUser(int r);
3530	}
3531
3532	public interface OnMoreMessagesLoaded {
3533		void onMoreMessagesLoaded(int count, Conversation conversation);
3534
3535		void informUser(int r);
3536	}
3537
3538	public interface OnAccountPasswordChanged {
3539		void onPasswordChangeSucceeded();
3540
3541		void onPasswordChangeFailed();
3542	}
3543
3544	public interface OnAffiliationChanged {
3545		void onAffiliationChangedSuccessful(Jid jid);
3546
3547		void onAffiliationChangeFailed(Jid jid, int resId);
3548	}
3549
3550	public interface OnRoleChanged {
3551		void onRoleChangedSuccessful(String nick);
3552
3553		void onRoleChangeFailed(String nick, int resid);
3554	}
3555
3556	public interface OnConversationUpdate {
3557		void onConversationUpdate();
3558	}
3559
3560	public interface OnAccountUpdate {
3561		void onAccountUpdate();
3562	}
3563
3564	public interface OnCaptchaRequested {
3565		void onCaptchaRequested(Account account,
3566								String id,
3567								Data data,
3568								Bitmap captcha);
3569	}
3570
3571	public interface OnRosterUpdate {
3572		void onRosterUpdate();
3573	}
3574
3575	public interface OnMucRosterUpdate {
3576		void onMucRosterUpdate();
3577	}
3578
3579	public interface OnConferenceConfigurationFetched {
3580		void onConferenceConfigurationFetched(Conversation conversation);
3581
3582		void onFetchFailed(Conversation conversation, Element error);
3583	}
3584
3585	public interface OnConferenceJoined {
3586		void onConferenceJoined(Conversation conversation);
3587	}
3588
3589	public interface OnConferenceOptionsPushed {
3590		void onPushSucceeded();
3591
3592		void onPushFailed();
3593	}
3594
3595	public interface OnShowErrorToast {
3596		void onShowErrorToast(int resId);
3597	}
3598
3599	public class XmppConnectionBinder extends Binder {
3600		public XmppConnectionService getService() {
3601			return XmppConnectionService.this;
3602		}
3603	}
3604}