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