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