EditAccountActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.app.PendingIntent;
   4import android.content.ActivityNotFoundException;
   5import android.content.DialogInterface;
   6import android.content.Intent;
   7import android.content.SharedPreferences;
   8import android.databinding.DataBindingUtil;
   9import android.graphics.Bitmap;
  10import android.net.Uri;
  11import android.os.Bundle;
  12import android.os.Handler;
  13import android.preference.PreferenceManager;
  14import android.provider.Settings;
  15import android.security.KeyChain;
  16import android.security.KeyChainAliasCallback;
  17import android.support.design.widget.TextInputLayout;
  18import android.support.v4.content.ContextCompat;
  19import android.support.v7.app.ActionBar;
  20import android.support.v7.app.AlertDialog;
  21import android.support.v7.app.AlertDialog.Builder;
  22import android.text.Editable;
  23import android.text.TextWatcher;
  24import android.util.Log;
  25import android.view.Menu;
  26import android.view.MenuItem;
  27import android.view.View;
  28import android.view.View.OnClickListener;
  29import android.widget.AdapterView;
  30import android.widget.AutoCompleteTextView;
  31import android.widget.Button;
  32import android.widget.CheckBox;
  33import android.widget.CompoundButton;
  34import android.widget.CompoundButton.OnCheckedChangeListener;
  35import android.widget.EditText;
  36import android.widget.ImageButton;
  37import android.widget.ImageView;
  38import android.widget.LinearLayout;
  39import android.widget.RelativeLayout;
  40import android.widget.TableLayout;
  41import android.widget.TableRow;
  42import android.widget.TextView;
  43import android.widget.Toast;
  44
  45import org.openintents.openpgp.util.OpenPgpUtils;
  46
  47import java.net.URL;
  48import java.util.Arrays;
  49import java.util.List;
  50import java.util.Set;
  51import java.util.concurrent.atomic.AtomicInteger;
  52
  53import eu.siacs.conversations.Config;
  54import eu.siacs.conversations.R;
  55import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  56import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession;
  57import eu.siacs.conversations.databinding.ActivityEditAccountBinding;
  58import eu.siacs.conversations.databinding.DialogPresenceBinding;
  59import eu.siacs.conversations.entities.Account;
  60import eu.siacs.conversations.entities.PresenceTemplate;
  61import eu.siacs.conversations.services.BarcodeProvider;
  62import eu.siacs.conversations.services.XmppConnectionService;
  63import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
  64import eu.siacs.conversations.services.XmppConnectionService.OnCaptchaRequested;
  65import eu.siacs.conversations.ui.adapter.KnownHostsAdapter;
  66import eu.siacs.conversations.ui.adapter.PresenceTemplateAdapter;
  67import eu.siacs.conversations.ui.widget.DisabledActionModeCallback;
  68import eu.siacs.conversations.utils.CryptoHelper;
  69import eu.siacs.conversations.utils.UIHelper;
  70import eu.siacs.conversations.utils.XmppUri;
  71import eu.siacs.conversations.xml.Element;
  72import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
  73import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  74import eu.siacs.conversations.xmpp.XmppConnection;
  75import eu.siacs.conversations.xmpp.XmppConnection.Features;
  76import eu.siacs.conversations.xmpp.forms.Data;
  77import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  78import eu.siacs.conversations.xmpp.jid.Jid;
  79import eu.siacs.conversations.xmpp.pep.Avatar;
  80
  81public class EditAccountActivity extends OmemoActivity implements OnAccountUpdate, OnUpdateBlocklist,
  82		OnKeyStatusUpdated, OnCaptchaRequested, KeyChainAliasCallback, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnMamPreferencesFetched {
  83
  84	private static final int REQUEST_DATA_SAVER = 0xf244;
  85	private TextInputLayout mAccountJidLayout;
  86	private EditText mPassword;
  87	private TextInputLayout mPasswordLayout;
  88	private CheckBox mRegisterNew;
  89	private Button mCancelButton;
  90	private Button mSaveButton;
  91	private Button mDisableOsOptimizationsButton;
  92	private TextView getmDisableOsOptimizationsBody;
  93	private TableLayout mMoreTable;
  94
  95	private TextView mServerInfoSm;
  96	private TextView mServerInfoRosterVersion;
  97	private TextView mServerInfoCarbons;
  98	private TextView mServerInfoMam;
  99	private TextView mServerInfoCSI;
 100	private TextView mServerInfoBlocking;
 101	private TextView mServerInfoPep;
 102	private TextView mServerInfoHttpUpload;
 103	private TextView mServerInfoPush;
 104	private TextView mSessionEst;
 105	private TextView mAxolotlFingerprint;
 106	private TextView mPgpFingerprint;
 107	private TextView mOwnFingerprintDesc;
 108	private TextView getmPgpFingerprintDesc;
 109	private ImageView mAvatar;
 110	private RelativeLayout mAxolotlFingerprintBox;
 111	private RelativeLayout mPgpFingerprintBox;
 112	private ImageButton mAxolotlFingerprintToClipboardButton;
 113	private ImageButton mPgpDeleteFingerprintButton;
 114	private LinearLayout keys;
 115	private LinearLayout mNamePort;
 116	private EditText mHostname;
 117	private TextInputLayout mHostnameLayout;
 118	private EditText mPort;
 119	private TextInputLayout mPortLayout;
 120	private AlertDialog mCaptchaDialog = null;
 121
 122	private Jid jidToEdit;
 123	private boolean mInitMode = false;
 124	private boolean mUsernameMode = Config.DOMAIN_LOCK != null;
 125	private boolean mShowOptions = false;
 126	private Account mAccount;
 127	private String messageFingerprint;
 128
 129	private boolean mFetchingAvatar = false;
 130
 131	private final OnClickListener mSaveButtonClickListener = new OnClickListener() {
 132
 133		@Override
 134		public void onClick(final View v) {
 135			final String password = mPassword.getText().toString();
 136			final boolean wasDisabled = mAccount != null && mAccount.getStatus() == Account.State.DISABLED;
 137
 138			if (!mInitMode && passwordChangedInMagicCreateMode()) {
 139				gotoChangePassword(password);
 140				return;
 141			}
 142			if (mInitMode && mAccount != null) {
 143				mAccount.setOption(Account.OPTION_DISABLED, false);
 144			}
 145			if (mAccount != null && mAccount.getStatus() == Account.State.DISABLED && !accountInfoEdited()) {
 146				mAccount.setOption(Account.OPTION_DISABLED, false);
 147				if (!xmppConnectionService.updateAccount(mAccount)) {
 148					Toast.makeText(EditAccountActivity.this, R.string.unable_to_update_account, Toast.LENGTH_SHORT).show();
 149				}
 150				return;
 151			}
 152			final boolean registerNewAccount = mRegisterNew.isChecked() && !Config.DISALLOW_REGISTRATION_IN_UI;
 153			if (mUsernameMode && binding.accountJid.getText().toString().contains("@")) {
 154				mAccountJidLayout.setError(getString(R.string.invalid_username));
 155				removeErrorsOnAllBut(mAccountJidLayout);
 156				binding.accountJid.requestFocus();
 157				return;
 158			}
 159
 160			XmppConnection connection = mAccount == null ? null : mAccount.getXmppConnection();
 161			boolean openRegistrationUrl = registerNewAccount && mAccount != null && mAccount.getStatus() == Account.State.REGISTRATION_WEB;
 162			boolean openPaymentUrl = mAccount != null && mAccount.getStatus() == Account.State.PAYMENT_REQUIRED;
 163			final boolean redirectionWorthyStatus = openPaymentUrl || openRegistrationUrl;
 164			URL url = connection != null && redirectionWorthyStatus ? connection.getRedirectionUrl() : null;
 165			if (url != null && redirectionWorthyStatus && !wasDisabled) {
 166				try {
 167					startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url.toString())));
 168					return;
 169				} catch (ActivityNotFoundException e) {
 170					Toast.makeText(EditAccountActivity.this, R.string.application_found_to_open_website, Toast.LENGTH_SHORT);
 171					return;
 172				}
 173			}
 174
 175			final Jid jid;
 176			try {
 177				if (mUsernameMode) {
 178					jid = Jid.fromParts(binding.accountJid.getText().toString(), getUserModeDomain(), null);
 179				} else {
 180					jid = Jid.fromString(binding.accountJid.getText().toString());
 181				}
 182			} catch (final InvalidJidException e) {
 183				if (mUsernameMode) {
 184					mAccountJidLayout.setError(getString(R.string.invalid_username));
 185				} else {
 186					mAccountJidLayout.setError(getString(R.string.invalid_jid));
 187				}
 188				binding.accountJid.requestFocus();
 189				removeErrorsOnAllBut(mAccountJidLayout);
 190				return;
 191			}
 192			String hostname = null;
 193			int numericPort = 5222;
 194			if (mShowOptions) {
 195				hostname = mHostname.getText().toString().replaceAll("\\s", "");
 196				final String port = mPort.getText().toString().replaceAll("\\s", "");
 197				if (hostname.contains(" ")) {
 198					mHostnameLayout.setError(getString(R.string.not_valid_hostname));
 199					mHostname.requestFocus();
 200					removeErrorsOnAllBut(mHostnameLayout);
 201					return;
 202				}
 203				try {
 204					numericPort = Integer.parseInt(port);
 205					if (numericPort < 0 || numericPort > 65535) {
 206						mPortLayout.setError(getString(R.string.not_a_valid_port));
 207						removeErrorsOnAllBut(mPortLayout);
 208						mPort.requestFocus();
 209						return;
 210					}
 211
 212				} catch (NumberFormatException e) {
 213					mPortLayout.setError(getString(R.string.not_a_valid_port));
 214					removeErrorsOnAllBut(mPortLayout);
 215					mPort.requestFocus();
 216					return;
 217				}
 218			}
 219
 220			if (jid.isDomainJid()) {
 221				if (mUsernameMode) {
 222					mAccountJidLayout.setError(getString(R.string.invalid_username));
 223				} else {
 224					mAccountJidLayout.setError(getString(R.string.invalid_jid));
 225				}
 226				removeErrorsOnAllBut(mAccountJidLayout);
 227				binding.accountJid.requestFocus();
 228				return;
 229			}
 230			if (mAccount != null) {
 231				if (mInitMode && mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE)) {
 232					mAccount.setOption(Account.OPTION_MAGIC_CREATE, mAccount.getPassword().contains(password));
 233				}
 234				mAccount.setJid(jid);
 235				mAccount.setPort(numericPort);
 236				mAccount.setHostname(hostname);
 237				mAccountJidLayout.setError(null);
 238				mAccount.setPassword(password);
 239				mAccount.setOption(Account.OPTION_REGISTER, registerNewAccount);
 240				if (!xmppConnectionService.updateAccount(mAccount)) {
 241					Toast.makeText(EditAccountActivity.this, R.string.unable_to_update_account, Toast.LENGTH_SHORT).show();
 242					return;
 243				}
 244			} else {
 245				if (xmppConnectionService.findAccountByJid(jid) != null) {
 246					mAccountJidLayout.setError(getString(R.string.account_already_exists));
 247					removeErrorsOnAllBut(mAccountJidLayout);
 248					binding.accountJid.requestFocus();
 249					return;
 250				}
 251				mAccount = new Account(jid.toBareJid(), password);
 252				mAccount.setPort(numericPort);
 253				mAccount.setHostname(hostname);
 254				mAccount.setOption(Account.OPTION_USETLS, true);
 255				mAccount.setOption(Account.OPTION_USECOMPRESSION, true);
 256				mAccount.setOption(Account.OPTION_REGISTER, registerNewAccount);
 257				xmppConnectionService.createAccount(mAccount);
 258			}
 259			mHostnameLayout.setError(null);
 260			mPortLayout.setError(null);
 261			if (mAccount.isEnabled()
 262					&& !registerNewAccount
 263					&& !mInitMode) {
 264				finish();
 265			} else {
 266				updateSaveButton();
 267				updateAccountInformation(true);
 268			}
 269
 270		}
 271	};
 272	private final OnClickListener mCancelButtonClickListener = new OnClickListener() {
 273
 274		@Override
 275		public void onClick(final View v) {
 276			deleteAccountAndReturnIfNecessary();
 277			finish();
 278		}
 279	};
 280	private Toast mFetchingMamPrefsToast;
 281	private TableRow mPushRow;
 282	private String mSavedInstanceAccount;
 283	private boolean mSavedInstanceInit = false;
 284	private Button mClearDevicesButton;
 285	private XmppUri pendingUri = null;
 286	private boolean mUseTor;
 287	private ActivityEditAccountBinding binding;
 288
 289	public void refreshUiReal() {
 290		invalidateOptionsMenu();
 291		if (mAccount != null
 292				&& mAccount.getStatus() != Account.State.ONLINE
 293				&& mFetchingAvatar) {
 294			startActivity(new Intent(getApplicationContext(),
 295					ManageAccountActivity.class));
 296			finish();
 297		} else if (mInitMode && mAccount != null && mAccount.getStatus() == Account.State.ONLINE) {
 298			if (!mFetchingAvatar) {
 299				mFetchingAvatar = true;
 300				xmppConnectionService.checkForAvatar(mAccount, mAvatarFetchCallback);
 301			}
 302		}
 303		if (mAccount != null) {
 304			updateAccountInformation(false);
 305		}
 306		updateSaveButton();
 307	}
 308
 309	@Override
 310	public boolean onNavigateUp() {
 311		deleteAccountAndReturnIfNecessary();
 312		return super.onNavigateUp();
 313	}
 314
 315	@Override
 316	public void onBackPressed() {
 317		deleteAccountAndReturnIfNecessary();
 318		super.onBackPressed();
 319	}
 320
 321	private void deleteAccountAndReturnIfNecessary() {
 322		if (mInitMode && mAccount != null && !mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY)) {
 323			xmppConnectionService.deleteAccount(mAccount);
 324		}
 325
 326		if (xmppConnectionService.getAccounts().size() == 0) {
 327			Intent intent = new Intent(EditAccountActivity.this, WelcomeActivity.class);
 328			WelcomeActivity.addInviteUri(intent, getIntent());
 329			startActivity(intent);
 330		}
 331	}
 332
 333	@Override
 334	public void onAccountUpdate() {
 335		refreshUi();
 336	}
 337
 338	private final UiCallback<Avatar> mAvatarFetchCallback = new UiCallback<Avatar>() {
 339
 340		@Override
 341		public void userInputRequried(final PendingIntent pi, final Avatar avatar) {
 342			finishInitialSetup(avatar);
 343		}
 344
 345		@Override
 346		public void success(final Avatar avatar) {
 347			finishInitialSetup(avatar);
 348		}
 349
 350		@Override
 351		public void error(final int errorCode, final Avatar avatar) {
 352			finishInitialSetup(avatar);
 353		}
 354	};
 355	private final TextWatcher mTextWatcher = new TextWatcher() {
 356
 357		@Override
 358		public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {
 359			updateSaveButton();
 360		}
 361
 362		@Override
 363		public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {
 364		}
 365
 366		@Override
 367		public void afterTextChanged(final Editable s) {
 368
 369		}
 370	};
 371
 372	private View.OnFocusChangeListener mEditTextFocusListener = new View.OnFocusChangeListener() {
 373		@Override
 374		public void onFocusChange(View view, boolean b) {
 375			EditText et = (EditText) view;
 376			if (b) {
 377				int resId = mUsernameMode ? R.string.username : R.string.account_settings_example_jabber_id;
 378				if (view.getId() == R.id.hostname) {
 379					resId = mUseTor ? R.string.hostname_or_onion : R.string.hostname_example;
 380				}
 381				final int res = resId;
 382				new Handler().postDelayed(() -> et.setHint(res), 200);
 383			} else {
 384				et.setHint(null);
 385			}
 386		}
 387	};
 388
 389
 390	private final OnClickListener mAvatarClickListener = new OnClickListener() {
 391		@Override
 392		public void onClick(final View view) {
 393			if (mAccount != null) {
 394				final Intent intent = new Intent(getApplicationContext(), PublishProfilePictureActivity.class);
 395				intent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toBareJid().toString());
 396				startActivity(intent);
 397			}
 398		}
 399	};
 400
 401	protected void finishInitialSetup(final Avatar avatar) {
 402		runOnUiThread(() -> {
 403			hideKeyboard();
 404			final Intent intent;
 405			final XmppConnection connection = mAccount.getXmppConnection();
 406			final boolean wasFirstAccount = xmppConnectionService != null && xmppConnectionService.getAccounts().size() == 1;
 407			if (avatar != null || (connection != null && !connection.getFeatures().pep())) {
 408				intent = new Intent(getApplicationContext(), StartConversationActivity.class);
 409				if (wasFirstAccount) {
 410					intent.putExtra("init", true);
 411				}
 412			} else {
 413				intent = new Intent(getApplicationContext(), PublishProfilePictureActivity.class);
 414				intent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toBareJid().toString());
 415				intent.putExtra("setup", true);
 416			}
 417			if (wasFirstAccount) {
 418				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
 419			}
 420			WelcomeActivity.addInviteUri(intent, getIntent());
 421			startActivity(intent);
 422			finish();
 423		});
 424	}
 425
 426	@Override
 427	public void onActivityResult(int requestCode, int resultCode, Intent data) {
 428		super.onActivityResult(requestCode, resultCode, data);
 429		if (requestCode == REQUEST_BATTERY_OP || requestCode == REQUEST_DATA_SAVER) {
 430			updateAccountInformation(mAccount == null);
 431		}
 432	}
 433
 434	@Override
 435	protected void processFingerprintVerification(XmppUri uri) {
 436		processFingerprintVerification(uri, true);
 437	}
 438
 439
 440	protected void processFingerprintVerification(XmppUri uri, boolean showWarningToast) {
 441		if (mAccount != null && mAccount.getJid().toBareJid().equals(uri.getJid()) && uri.hasFingerprints()) {
 442			if (xmppConnectionService.verifyFingerprints(mAccount, uri.getFingerprints())) {
 443				Toast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show();
 444			}
 445		} else if (showWarningToast) {
 446			Toast.makeText(this, R.string.invalid_barcode, Toast.LENGTH_SHORT).show();
 447		}
 448	}
 449
 450	protected void updateSaveButton() {
 451		boolean accountInfoEdited = accountInfoEdited();
 452
 453		if (!mInitMode && passwordChangedInMagicCreateMode()) {
 454			this.mSaveButton.setText(R.string.change_password);
 455			this.mSaveButton.setEnabled(true);
 456		} else if (accountInfoEdited && !mInitMode) {
 457			this.mSaveButton.setText(R.string.save);
 458			this.mSaveButton.setEnabled(true);
 459		} else if (mAccount != null
 460				&& (mAccount.getStatus() == Account.State.CONNECTING || mAccount.getStatus() == Account.State.REGISTRATION_SUCCESSFUL || mFetchingAvatar)) {
 461			this.mSaveButton.setEnabled(false);
 462			this.mSaveButton.setText(R.string.account_status_connecting);
 463		} else if (mAccount != null && mAccount.getStatus() == Account.State.DISABLED && !mInitMode) {
 464			this.mSaveButton.setEnabled(true);
 465			this.mSaveButton.setText(R.string.enable);
 466		} else {
 467			this.mSaveButton.setEnabled(true);
 468			if (!mInitMode) {
 469				if (mAccount != null && mAccount.isOnlineAndConnected()) {
 470					this.mSaveButton.setText(R.string.save);
 471					if (!accountInfoEdited) {
 472						this.mSaveButton.setEnabled(false);
 473					}
 474				} else {
 475					XmppConnection connection = mAccount == null ? null : mAccount.getXmppConnection();
 476					URL url = connection != null && mAccount.getStatus() == Account.State.PAYMENT_REQUIRED ? connection.getRedirectionUrl() : null;
 477					if (url != null) {
 478						this.mSaveButton.setText(R.string.open_website);
 479					} else {
 480						this.mSaveButton.setText(R.string.connect);
 481					}
 482				}
 483			} else {
 484				XmppConnection connection = mAccount == null ? null : mAccount.getXmppConnection();
 485				URL url = connection != null && mAccount.getStatus() == Account.State.REGISTRATION_WEB ? connection.getRedirectionUrl() : null;
 486				if (url != null && mRegisterNew.isChecked()) {
 487					this.mSaveButton.setText(R.string.open_website);
 488				} else {
 489					this.mSaveButton.setText(R.string.next);
 490				}
 491			}
 492		}
 493	}
 494
 495	protected boolean accountInfoEdited() {
 496		if (this.mAccount == null) {
 497			return false;
 498		}
 499		return jidEdited() ||
 500				!this.mAccount.getPassword().equals(this.mPassword.getText().toString()) ||
 501				!this.mAccount.getHostname().equals(this.mHostname.getText().toString()) ||
 502				!String.valueOf(this.mAccount.getPort()).equals(this.mPort.getText().toString());
 503	}
 504
 505	protected boolean jidEdited() {
 506		final String unmodified;
 507		if (mUsernameMode) {
 508			unmodified = this.mAccount.getJid().getLocalpart();
 509		} else {
 510			unmodified = this.mAccount.getJid().toBareJid().toString();
 511		}
 512		return !unmodified.equals(this.binding.accountJid.getText().toString());
 513	}
 514
 515	protected boolean passwordChangedInMagicCreateMode() {
 516		return mAccount != null
 517				&& mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE)
 518				&& !this.mAccount.getPassword().equals(this.mPassword.getText().toString())
 519				&& !this.jidEdited()
 520				&& mAccount.isOnlineAndConnected();
 521	}
 522
 523	@Override
 524	protected String getShareableUri(boolean http) {
 525		if (mAccount != null) {
 526			return http ? mAccount.getShareableLink() : mAccount.getShareableUri();
 527		} else {
 528			return null;
 529		}
 530	}
 531
 532	@Override
 533	protected void onCreate(final Bundle savedInstanceState) {
 534		super.onCreate(savedInstanceState);
 535		if (savedInstanceState != null) {
 536			this.mSavedInstanceAccount = savedInstanceState.getString("account");
 537			this.mSavedInstanceInit = savedInstanceState.getBoolean("initMode", false);
 538		}
 539		this.binding = DataBindingUtil.setContentView(this, R.layout.activity_edit_account);
 540		binding.accountJid.addTextChangedListener(this.mTextWatcher);
 541		binding.accountJid.setOnFocusChangeListener(this.mEditTextFocusListener);
 542		this.mAccountJidLayout = (TextInputLayout) findViewById(R.id.account_jid_layout);
 543		this.mPassword = (EditText) findViewById(R.id.account_password);
 544		this.mPassword.addTextChangedListener(this.mTextWatcher);
 545		this.mPasswordLayout = (TextInputLayout) findViewById(R.id.account_password_layout);
 546		this.mAvatar = (ImageView) findViewById(R.id.avater);
 547		this.mAvatar.setOnClickListener(this.mAvatarClickListener);
 548		this.mRegisterNew = (CheckBox) findViewById(R.id.account_register_new);
 549		this.mDisableOsOptimizationsButton = (Button) findViewById(R.id.os_optimization_disable);
 550		this.getmDisableOsOptimizationsBody = (TextView) findViewById(R.id.os_optimization_body);
 551		this.mSessionEst = (TextView) findViewById(R.id.session_est);
 552		this.mServerInfoRosterVersion = (TextView) findViewById(R.id.server_info_roster_version);
 553		this.mServerInfoCarbons = (TextView) findViewById(R.id.server_info_carbons);
 554		this.mServerInfoMam = (TextView) findViewById(R.id.server_info_mam);
 555		this.mServerInfoCSI = (TextView) findViewById(R.id.server_info_csi);
 556		this.mServerInfoBlocking = (TextView) findViewById(R.id.server_info_blocking);
 557		this.mServerInfoSm = (TextView) findViewById(R.id.server_info_sm);
 558		this.mServerInfoPep = (TextView) findViewById(R.id.server_info_pep);
 559		this.mServerInfoHttpUpload = (TextView) findViewById(R.id.server_info_http_upload);
 560		this.mPushRow = (TableRow) findViewById(R.id.push_row);
 561		this.mServerInfoPush = (TextView) findViewById(R.id.server_info_push);
 562		this.mPgpFingerprintBox = (RelativeLayout) findViewById(R.id.pgp_fingerprint_box);
 563		this.mPgpFingerprint = (TextView) findViewById(R.id.pgp_fingerprint);
 564		this.getmPgpFingerprintDesc = (TextView) findViewById(R.id.pgp_fingerprint_desc);
 565		this.mPgpDeleteFingerprintButton = (ImageButton) findViewById(R.id.action_delete_pgp);
 566		this.mAxolotlFingerprint = (TextView) findViewById(R.id.axolotl_fingerprint);
 567		this.mAxolotlFingerprintBox = (RelativeLayout) findViewById(R.id.axolotl_fingerprint_box);
 568		this.mAxolotlFingerprintToClipboardButton = (ImageButton) findViewById(R.id.action_copy_axolotl_to_clipboard);
 569		this.mOwnFingerprintDesc = (TextView) findViewById(R.id.own_fingerprint_desc);
 570		this.keys = (LinearLayout) findViewById(R.id.other_device_keys);
 571		this.mNamePort = (LinearLayout) findViewById(R.id.name_port);
 572		this.mHostname = (EditText) findViewById(R.id.hostname);
 573		this.mHostname.addTextChangedListener(mTextWatcher);
 574		this.mHostname.setOnFocusChangeListener(mEditTextFocusListener);
 575		this.mHostnameLayout = (TextInputLayout) findViewById(R.id.hostname_layout);
 576		this.mClearDevicesButton = (Button) findViewById(R.id.clear_devices);
 577		this.mClearDevicesButton.setOnClickListener(new OnClickListener() {
 578			@Override
 579			public void onClick(View v) {
 580				showWipePepDialog();
 581			}
 582		});
 583		this.mPort = (EditText) findViewById(R.id.port);
 584		this.mPort.setText("5222");
 585		this.mPort.addTextChangedListener(mTextWatcher);
 586		this.mPortLayout = (TextInputLayout) findViewById(R.id.port_layout);
 587		this.mSaveButton = (Button) findViewById(R.id.save_button);
 588		this.mCancelButton = (Button) findViewById(R.id.cancel_button);
 589		this.mSaveButton.setOnClickListener(this.mSaveButtonClickListener);
 590		this.mCancelButton.setOnClickListener(this.mCancelButtonClickListener);
 591		this.mMoreTable = (TableLayout) findViewById(R.id.server_info_more);
 592		if (savedInstanceState != null && savedInstanceState.getBoolean("showMoreTable")) {
 593			changeMoreTableVisibility(true);
 594		}
 595		final OnCheckedChangeListener OnCheckedShowConfirmPassword = new OnCheckedChangeListener() {
 596			@Override
 597			public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
 598				updateSaveButton();
 599			}
 600		};
 601		this.mRegisterNew.setOnCheckedChangeListener(OnCheckedShowConfirmPassword);
 602		if (Config.DISALLOW_REGISTRATION_IN_UI) {
 603			this.mRegisterNew.setVisibility(View.GONE);
 604		}
 605	}
 606
 607	@Override
 608	public boolean onCreateOptionsMenu(final Menu menu) {
 609		super.onCreateOptionsMenu(menu);
 610		getMenuInflater().inflate(R.menu.editaccount, menu);
 611		final MenuItem showBlocklist = menu.findItem(R.id.action_show_block_list);
 612		final MenuItem showMoreInfo = menu.findItem(R.id.action_server_info_show_more);
 613		final MenuItem changePassword = menu.findItem(R.id.action_change_password_on_server);
 614		final MenuItem renewCertificate = menu.findItem(R.id.action_renew_certificate);
 615		final MenuItem mamPrefs = menu.findItem(R.id.action_mam_prefs);
 616		final MenuItem changePresence = menu.findItem(R.id.action_change_presence);
 617		final MenuItem share = menu.findItem(R.id.action_share);
 618		renewCertificate.setVisible(mAccount != null && mAccount.getPrivateKeyAlias() != null);
 619
 620		share.setVisible(mAccount != null && !mInitMode);
 621
 622		if (mAccount != null && mAccount.isOnlineAndConnected()) {
 623			if (!mAccount.getXmppConnection().getFeatures().blocking()) {
 624				showBlocklist.setVisible(false);
 625			}
 626
 627			if (!mAccount.getXmppConnection().getFeatures().register()) {
 628				changePassword.setVisible(false);
 629			}
 630			mamPrefs.setVisible(mAccount.getXmppConnection().getFeatures().mam());
 631			changePresence.setVisible(true);
 632		} else {
 633			showBlocklist.setVisible(false);
 634			showMoreInfo.setVisible(false);
 635			changePassword.setVisible(false);
 636			mamPrefs.setVisible(false);
 637			changePresence.setVisible(false);
 638		}
 639		return super.onCreateOptionsMenu(menu);
 640	}
 641
 642	@Override
 643	public boolean onPrepareOptionsMenu(Menu menu) {
 644		final MenuItem showMoreInfo = menu.findItem(R.id.action_server_info_show_more);
 645		if (showMoreInfo.isVisible()) {
 646			showMoreInfo.setChecked(mMoreTable.getVisibility() == View.VISIBLE);
 647		}
 648		return super.onPrepareOptionsMenu(menu);
 649	}
 650
 651	@Override
 652	protected void onStart() {
 653		super.onStart();
 654		final int theme = findTheme();
 655		if (this.mTheme != theme) {
 656			recreate();
 657		} else if (getIntent() != null) {
 658			try {
 659				this.jidToEdit = Jid.fromString(getIntent().getStringExtra("jid"));
 660			} catch (final InvalidJidException | NullPointerException ignored) {
 661				this.jidToEdit = null;
 662			}
 663			if (jidToEdit != null && getIntent().getData() != null) {
 664				final XmppUri uri = new XmppUri(getIntent().getData());
 665				if (xmppConnectionServiceBound) {
 666					processFingerprintVerification(uri, false);
 667				} else {
 668					this.pendingUri = uri;
 669				}
 670			}
 671			boolean init = getIntent().getBooleanExtra("init", false);
 672			this.mInitMode = init || this.jidToEdit == null;
 673			this.messageFingerprint = getIntent().getStringExtra("fingerprint");
 674			if (!mInitMode) {
 675				this.mRegisterNew.setVisibility(View.GONE);
 676				if (getSupportActionBar() != null) {
 677					getSupportActionBar().setTitle(getString(R.string.account_details));
 678				}
 679			} else {
 680				this.mAvatar.setVisibility(View.GONE);
 681				ActionBar ab = getSupportActionBar();
 682				if (ab != null) {
 683					if (init && Config.MAGIC_CREATE_DOMAIN == null) {
 684						ab.setDisplayShowHomeEnabled(false);
 685						ab.setDisplayHomeAsUpEnabled(false);
 686					}
 687					ab.setTitle(R.string.action_add_account);
 688				}
 689			}
 690		}
 691		SharedPreferences preferences = getPreferences();
 692		mUseTor = Config.FORCE_ORBOT || preferences.getBoolean("use_tor", false);
 693		this.mShowOptions = mUseTor || preferences.getBoolean("show_connection_options", false);
 694		this.mNamePort.setVisibility(mShowOptions ? View.VISIBLE : View.GONE);
 695	}
 696
 697	@Override
 698	public void onNewIntent(Intent intent) {
 699		if (intent != null && intent.getData() != null) {
 700			final XmppUri uri = new XmppUri(intent.getData());
 701			if (xmppConnectionServiceBound) {
 702				processFingerprintVerification(uri, false);
 703			} else {
 704				this.pendingUri = uri;
 705			}
 706		}
 707	}
 708
 709	@Override
 710	public void onSaveInstanceState(final Bundle savedInstanceState) {
 711		if (mAccount != null) {
 712			savedInstanceState.putString("account", mAccount.getJid().toBareJid().toString());
 713			savedInstanceState.putBoolean("initMode", mInitMode);
 714			savedInstanceState.putBoolean("showMoreTable", mMoreTable.getVisibility() == View.VISIBLE);
 715		}
 716		super.onSaveInstanceState(savedInstanceState);
 717	}
 718
 719	protected void onBackendConnected() {
 720		boolean init = true;
 721		if (mSavedInstanceAccount != null) {
 722			try {
 723				this.mAccount = xmppConnectionService.findAccountByJid(Jid.fromString(mSavedInstanceAccount));
 724				this.mInitMode = mSavedInstanceInit;
 725				init = false;
 726			} catch (InvalidJidException e) {
 727				this.mAccount = null;
 728			}
 729
 730		} else if (this.jidToEdit != null) {
 731			this.mAccount = xmppConnectionService.findAccountByJid(jidToEdit);
 732		}
 733
 734		if (mAccount != null) {
 735			this.mInitMode |= this.mAccount.isOptionSet(Account.OPTION_REGISTER);
 736			this.mUsernameMode |= mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE) && mAccount.isOptionSet(Account.OPTION_REGISTER);
 737			if (this.mAccount.getPrivateKeyAlias() != null) {
 738				this.mPassword.setHint(R.string.authenticate_with_certificate);
 739				if (this.mInitMode) {
 740					this.mPassword.requestFocus();
 741				}
 742			}
 743			if (mPendingFingerprintVerificationUri != null) {
 744				processFingerprintVerification(mPendingFingerprintVerificationUri, false);
 745				mPendingFingerprintVerificationUri = null;
 746			}
 747			updateAccountInformation(init);
 748		}
 749
 750
 751		if (Config.MAGIC_CREATE_DOMAIN == null && this.xmppConnectionService.getAccounts().size() == 0) {
 752			this.mCancelButton.setEnabled(false);
 753		}
 754		if (mUsernameMode) {
 755			this.binding.accountJid.setHint(R.string.username_hint);
 756		} else {
 757			final KnownHostsAdapter mKnownHostsAdapter = new KnownHostsAdapter(this,
 758					R.layout.simple_list_item,
 759					xmppConnectionService.getKnownHosts());
 760			this.binding.accountJid.setAdapter(mKnownHostsAdapter);
 761		}
 762
 763		if (pendingUri != null) {
 764			processFingerprintVerification(pendingUri, false);
 765			pendingUri = null;
 766		}
 767
 768		updateSaveButton();
 769		invalidateOptionsMenu();
 770	}
 771
 772	private String getUserModeDomain() {
 773		if (mAccount != null) {
 774			return mAccount.getJid().getDomainpart();
 775		} else {
 776			return Config.DOMAIN_LOCK;
 777		}
 778	}
 779
 780	@Override
 781	public boolean onOptionsItemSelected(final MenuItem item) {
 782		switch (item.getItemId()) {
 783			case R.id.action_show_block_list:
 784				final Intent showBlocklistIntent = new Intent(this, BlocklistActivity.class);
 785				showBlocklistIntent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toString());
 786				startActivity(showBlocklistIntent);
 787				break;
 788			case R.id.action_server_info_show_more:
 789				changeMoreTableVisibility(!item.isChecked());
 790				break;
 791			case R.id.action_share_barcode:
 792				shareBarcode();
 793				break;
 794			case R.id.action_share_http:
 795				shareLink(true);
 796				break;
 797			case R.id.action_share_uri:
 798				shareLink(false);
 799				break;
 800			case R.id.action_change_password_on_server:
 801				gotoChangePassword(null);
 802				break;
 803			case R.id.action_mam_prefs:
 804				editMamPrefs();
 805				break;
 806			case R.id.action_renew_certificate:
 807				renewCertificate();
 808				break;
 809			case R.id.action_change_presence:
 810				changePresence();
 811				break;
 812		}
 813		return super.onOptionsItemSelected(item);
 814	}
 815
 816	private void shareBarcode() {
 817		Intent intent = new Intent(Intent.ACTION_SEND);
 818		intent.putExtra(Intent.EXTRA_STREAM, BarcodeProvider.getUriForAccount(this, mAccount));
 819		intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 820		intent.setType("image/png");
 821		startActivity(Intent.createChooser(intent, getText(R.string.share_with)));
 822	}
 823
 824	private void changeMoreTableVisibility(boolean visible) {
 825		mMoreTable.setVisibility(visible ? View.VISIBLE : View.GONE);
 826	}
 827
 828	private void gotoChangePassword(String newPassword) {
 829		final Intent changePasswordIntent = new Intent(this, ChangePasswordActivity.class);
 830		changePasswordIntent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toString());
 831		if (newPassword != null) {
 832			changePasswordIntent.putExtra("password", newPassword);
 833		}
 834		startActivity(changePasswordIntent);
 835	}
 836
 837	private void renewCertificate() {
 838		KeyChain.choosePrivateKeyAlias(this, this, null, null, null, -1, null);
 839	}
 840
 841	private void changePresence() {
 842		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
 843		boolean manualStatus = sharedPreferences.getBoolean(SettingsActivity.MANUALLY_CHANGE_PRESENCE, getResources().getBoolean(R.bool.manually_change_presence));
 844		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 845		final DialogPresenceBinding binding = DataBindingUtil.inflate(getLayoutInflater(),R.layout.dialog_presence,null,false);
 846		binding.show.setVisibility(manualStatus ? View.VISIBLE : View.GONE);
 847		List<PresenceTemplate> templates = xmppConnectionService.getPresenceTemplates(mAccount);
 848		PresenceTemplateAdapter presenceTemplateAdapter = new PresenceTemplateAdapter(this,R.layout.simple_list_item,templates);
 849		binding.statusMessage.setAdapter(presenceTemplateAdapter);
 850		binding.statusMessage.setOnItemClickListener((parent, view, position, id) -> {
 851			PresenceTemplate template = (PresenceTemplate) parent.getItemAtPosition(position);
 852			Log.d(Config.LOGTAG,"selected: "+template.getStatusMessage());
 853		});
 854		builder.setTitle(R.string.change_presence);
 855		builder.setView(binding.getRoot());
 856		builder.setNegativeButton(R.string.cancel,null);
 857		builder.setPositiveButton(R.string.confirm,null);
 858		builder.create().show();
 859	}
 860
 861	@Override
 862	public void alias(String alias) {
 863		if (alias != null) {
 864			xmppConnectionService.updateKeyInAccount(mAccount, alias);
 865		}
 866	}
 867
 868	private void updateAccountInformation(boolean init) {
 869		if (init) {
 870			this.binding.accountJid.getEditableText().clear();
 871			if (mUsernameMode) {
 872				this.binding.accountJid.getEditableText().append(this.mAccount.getJid().getLocalpart());
 873			} else {
 874				this.binding.accountJid.getEditableText().append(this.mAccount.getJid().toBareJid().toString());
 875			}
 876			this.mPassword.getEditableText().clear();
 877			this.mPassword.getEditableText().append(this.mAccount.getPassword());
 878			this.mHostname.setText("");
 879			this.mHostname.getEditableText().append(this.mAccount.getHostname());
 880			this.mPort.setText("");
 881			this.mPort.getEditableText().append(String.valueOf(this.mAccount.getPort()));
 882			this.mNamePort.setVisibility(mShowOptions ? View.VISIBLE : View.GONE);
 883
 884		}
 885
 886		final boolean editable = !mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
 887		this.binding.accountJid.setEnabled(editable);
 888		this.binding.accountJid.setFocusable(editable);
 889		this.binding.accountJid.setFocusableInTouchMode(editable);
 890		if (editable) {
 891			this.mPassword.setCustomSelectionActionModeCallback(null);
 892		} else {
 893			this.mPassword.setCustomSelectionActionModeCallback(new DisabledActionModeCallback());
 894		}
 895
 896		if (!mInitMode) {
 897			this.mAvatar.setVisibility(View.VISIBLE);
 898			this.mAvatar.setImageBitmap(avatarService().get(this.mAccount, getPixel(72)));
 899		} else {
 900			this.mAvatar.setVisibility(View.GONE);
 901		}
 902		if (this.mAccount.isOptionSet(Account.OPTION_REGISTER)) {
 903			this.mRegisterNew.setVisibility(View.VISIBLE);
 904			this.mRegisterNew.setChecked(true);
 905		} else {
 906			this.mRegisterNew.setVisibility(View.GONE);
 907			this.mRegisterNew.setChecked(false);
 908		}
 909		if (this.mAccount.isOnlineAndConnected() && !this.mFetchingAvatar) {
 910			Features features = this.mAccount.getXmppConnection().getFeatures();
 911			this.binding.stats.setVisibility(View.VISIBLE);
 912			boolean showBatteryWarning = !xmppConnectionService.getPushManagementService().available(mAccount) && isOptimizingBattery();
 913			boolean showDataSaverWarning = isAffectedByDataSaver();
 914			showOsOptimizationWarning(showBatteryWarning, showDataSaverWarning);
 915			this.mSessionEst.setText(UIHelper.readableTimeDifferenceFull(this, this.mAccount.getXmppConnection()
 916					.getLastSessionEstablished()));
 917			if (features.rosterVersioning()) {
 918				this.mServerInfoRosterVersion.setText(R.string.server_info_available);
 919			} else {
 920				this.mServerInfoRosterVersion.setText(R.string.server_info_unavailable);
 921			}
 922			if (features.carbons()) {
 923				this.mServerInfoCarbons.setText(R.string.server_info_available);
 924			} else {
 925				this.mServerInfoCarbons
 926						.setText(R.string.server_info_unavailable);
 927			}
 928			if (features.mam()) {
 929				this.mServerInfoMam.setText(R.string.server_info_available);
 930			} else {
 931				this.mServerInfoMam.setText(R.string.server_info_unavailable);
 932			}
 933			if (features.csi()) {
 934				this.mServerInfoCSI.setText(R.string.server_info_available);
 935			} else {
 936				this.mServerInfoCSI.setText(R.string.server_info_unavailable);
 937			}
 938			if (features.blocking()) {
 939				this.mServerInfoBlocking.setText(R.string.server_info_available);
 940			} else {
 941				this.mServerInfoBlocking.setText(R.string.server_info_unavailable);
 942			}
 943			if (features.sm()) {
 944				this.mServerInfoSm.setText(R.string.server_info_available);
 945			} else {
 946				this.mServerInfoSm.setText(R.string.server_info_unavailable);
 947			}
 948			if (features.pep()) {
 949				AxolotlService axolotlService = this.mAccount.getAxolotlService();
 950				if (axolotlService != null && axolotlService.isPepBroken()) {
 951					this.mServerInfoPep.setText(R.string.server_info_broken);
 952				} else if (features.pepPublishOptions() || features.pepOmemoWhitelisted()) {
 953					this.mServerInfoPep.setText(R.string.server_info_available);
 954				} else {
 955					this.mServerInfoPep.setText(R.string.server_info_partial);
 956				}
 957			} else {
 958				this.mServerInfoPep.setText(R.string.server_info_unavailable);
 959			}
 960			if (features.httpUpload(0)) {
 961				this.mServerInfoHttpUpload.setText(R.string.server_info_available);
 962			} else {
 963				this.mServerInfoHttpUpload.setText(R.string.server_info_unavailable);
 964			}
 965
 966			this.mPushRow.setVisibility(xmppConnectionService.getPushManagementService().isStub() ? View.GONE : View.VISIBLE);
 967
 968			if (xmppConnectionService.getPushManagementService().available(mAccount)) {
 969				this.mServerInfoPush.setText(R.string.server_info_available);
 970			} else {
 971				this.mServerInfoPush.setText(R.string.server_info_unavailable);
 972			}
 973			final long pgpKeyId = this.mAccount.getPgpId();
 974			if (pgpKeyId != 0 && Config.supportOpenPgp()) {
 975				OnClickListener openPgp = view -> launchOpenKeyChain(pgpKeyId);
 976				OnClickListener delete = view -> showDeletePgpDialog();
 977				this.mPgpFingerprintBox.setVisibility(View.VISIBLE);
 978				this.mPgpFingerprint.setText(OpenPgpUtils.convertKeyIdToHex(pgpKeyId));
 979				this.mPgpFingerprint.setOnClickListener(openPgp);
 980				if ("pgp".equals(messageFingerprint)) {
 981					this.getmPgpFingerprintDesc.setTextAppearance(this,R.style.TextAppearance_Conversations_Caption_Highlight);
 982				}
 983				this.getmPgpFingerprintDesc.setOnClickListener(openPgp);
 984				this.mPgpDeleteFingerprintButton.setOnClickListener(delete);
 985			} else {
 986				this.mPgpFingerprintBox.setVisibility(View.GONE);
 987			}
 988			final String ownAxolotlFingerprint = this.mAccount.getAxolotlService().getOwnFingerprint();
 989			if (ownAxolotlFingerprint != null && Config.supportOmemo()) {
 990				this.mAxolotlFingerprintBox.setVisibility(View.VISIBLE);
 991				if (ownAxolotlFingerprint.equals(messageFingerprint)) {
 992					this.mOwnFingerprintDesc.setTextAppearance(this,R.style.TextAppearance_Conversations_Caption_Highlight);
 993					this.mOwnFingerprintDesc.setText(R.string.omemo_fingerprint_selected_message);
 994				} else {
 995					this.mOwnFingerprintDesc.setTextAppearance(this,R.style.TextAppearance_Conversations_Caption);
 996					this.mOwnFingerprintDesc.setText(R.string.omemo_fingerprint);
 997				}
 998				this.mAxolotlFingerprint.setText(CryptoHelper.prettifyFingerprint(ownAxolotlFingerprint.substring(2)));
 999				this.mAxolotlFingerprintToClipboardButton.setVisibility(View.VISIBLE);
1000				this.mAxolotlFingerprintToClipboardButton.setOnClickListener(v -> copyOmemoFingerprint(ownAxolotlFingerprint));
1001			} else {
1002				this.mAxolotlFingerprintBox.setVisibility(View.GONE);
1003			}
1004			boolean hasKeys = false;
1005			keys.removeAllViews();
1006			for (XmppAxolotlSession session : mAccount.getAxolotlService().findOwnSessions()) {
1007				if (!session.getTrust().isCompromised()) {
1008					boolean highlight = session.getFingerprint().equals(messageFingerprint);
1009					addFingerprintRow(keys, session, highlight);
1010					hasKeys = true;
1011				}
1012			}
1013			if (hasKeys && Config.supportOmemo()) {
1014				this.binding.otherDeviceKeysCard.setVisibility(View.VISIBLE);
1015				Set<Integer> otherDevices = mAccount.getAxolotlService().getOwnDeviceIds();
1016				if (otherDevices == null || otherDevices.isEmpty()) {
1017					mClearDevicesButton.setVisibility(View.GONE);
1018				} else {
1019					mClearDevicesButton.setVisibility(View.VISIBLE);
1020				}
1021			} else {
1022				this.binding.otherDeviceKeysCard.setVisibility(View.GONE);
1023			}
1024		} else {
1025			final TextInputLayout errorLayout;
1026			if (this.mAccount.errorStatus()) {
1027				if (this.mAccount.getStatus() == Account.State.UNAUTHORIZED) {
1028					errorLayout = this.mPasswordLayout;
1029				} else if (mShowOptions
1030						&& this.mAccount.getStatus() == Account.State.SERVER_NOT_FOUND
1031						&& this.mHostname.getText().length() > 0) {
1032					errorLayout = this.mHostnameLayout;
1033				} else {
1034					errorLayout = this.mAccountJidLayout;
1035				}
1036				errorLayout.setError(getString(this.mAccount.getStatus().getReadableId()));
1037				if (init || !accountInfoEdited()) {
1038					errorLayout.requestFocus();
1039				}
1040			} else {
1041				errorLayout = null;
1042			}
1043			removeErrorsOnAllBut(errorLayout);
1044			this.binding.stats.setVisibility(View.GONE);
1045			this.binding.otherDeviceKeysCard.setVisibility(View.GONE);
1046		}
1047	}
1048
1049	private void removeErrorsOnAllBut(TextInputLayout exception) {
1050		if (this.mAccountJidLayout != exception) {
1051			this.mAccountJidLayout.setErrorEnabled(false);
1052			this.mAccountJidLayout.setError(null);
1053		}
1054		if (this.mPasswordLayout != exception) {
1055			this.mPasswordLayout.setErrorEnabled(false);
1056			this.mPasswordLayout.setError(null);
1057		}
1058		if (this.mHostnameLayout != exception) {
1059			this.mHostnameLayout.setErrorEnabled(false);
1060			this.mHostnameLayout.setError(null);
1061		}
1062		if (this.mPortLayout != exception) {
1063			this.mPortLayout.setErrorEnabled(false);
1064			this.mPortLayout.setError(null);
1065		}
1066	}
1067
1068	private void showDeletePgpDialog() {
1069		AlertDialog.Builder builder = new AlertDialog.Builder(this);
1070		builder.setTitle(R.string.unpublish_pgp);
1071		builder.setMessage(R.string.unpublish_pgp_message);
1072		builder.setNegativeButton(R.string.cancel, null);
1073		builder.setPositiveButton(R.string.confirm, (dialogInterface, i) -> {
1074			mAccount.setPgpSignId(0);
1075			mAccount.unsetPgpSignature();
1076			xmppConnectionService.databaseBackend.updateAccount(mAccount);
1077			xmppConnectionService.sendPresence(mAccount);
1078			refreshUiReal();
1079		});
1080		builder.create().show();
1081	}
1082
1083	private void showOsOptimizationWarning(boolean showBatteryWarning, boolean showDataSaverWarning) {
1084		this.binding.osOptimization.setVisibility(showBatteryWarning || showDataSaverWarning ? View.VISIBLE : View.GONE);
1085		if (showDataSaverWarning) {
1086			this.binding.osOptimizationHeadline.setText(R.string.data_saver_enabled);
1087			this.getmDisableOsOptimizationsBody.setText(R.string.data_saver_enabled_explained);
1088			this.mDisableOsOptimizationsButton.setText(R.string.allow);
1089			this.mDisableOsOptimizationsButton.setOnClickListener(v -> {
1090				Intent intent = new Intent(Settings.ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS);
1091				Uri uri = Uri.parse("package:" + getPackageName());
1092				intent.setData(uri);
1093				try {
1094					startActivityForResult(intent, REQUEST_DATA_SAVER);
1095				} catch (ActivityNotFoundException e) {
1096					Toast.makeText(EditAccountActivity.this, R.string.device_does_not_support_data_saver, Toast.LENGTH_SHORT).show();
1097				}
1098			});
1099		} else if (showBatteryWarning) {
1100			this.mDisableOsOptimizationsButton.setText(R.string.disable);
1101			this.binding.osOptimizationHeadline.setText(R.string.battery_optimizations_enabled);
1102			this.getmDisableOsOptimizationsBody.setText(R.string.battery_optimizations_enabled_explained);
1103			this.mDisableOsOptimizationsButton.setOnClickListener(v -> {
1104				Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1105				Uri uri = Uri.parse("package:" + getPackageName());
1106				intent.setData(uri);
1107				try {
1108					startActivityForResult(intent, REQUEST_BATTERY_OP);
1109				} catch (ActivityNotFoundException e) {
1110					Toast.makeText(EditAccountActivity.this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
1111				}
1112			});
1113		}
1114	}
1115
1116	public void showWipePepDialog() {
1117		Builder builder = new Builder(this);
1118		builder.setTitle(getString(R.string.clear_other_devices));
1119		builder.setIconAttribute(android.R.attr.alertDialogIcon);
1120		builder.setMessage(getString(R.string.clear_other_devices_desc));
1121		builder.setNegativeButton(getString(R.string.cancel), null);
1122		builder.setPositiveButton(getString(R.string.accept),
1123				(dialog, which) -> mAccount.getAxolotlService().wipeOtherPepDevices());
1124		builder.create().show();
1125	}
1126
1127	private void editMamPrefs() {
1128		this.mFetchingMamPrefsToast = Toast.makeText(this, R.string.fetching_mam_prefs, Toast.LENGTH_LONG);
1129		this.mFetchingMamPrefsToast.show();
1130		xmppConnectionService.fetchMamPreferences(mAccount, this);
1131	}
1132
1133	@Override
1134	public void onKeyStatusUpdated(AxolotlService.FetchStatus report) {
1135		refreshUi();
1136	}
1137
1138	@Override
1139	public void onCaptchaRequested(final Account account, final String id, final Data data, final Bitmap captcha) {
1140		runOnUiThread(() -> {
1141			if (mCaptchaDialog != null && mCaptchaDialog.isShowing()) {
1142				mCaptchaDialog.dismiss();
1143			}
1144			final Builder builder = new Builder(EditAccountActivity.this);
1145			final View view = getLayoutInflater().inflate(R.layout.captcha, null);
1146			final ImageView imageView = view.findViewById(R.id.captcha);
1147			final EditText input = view.findViewById(R.id.input);
1148			imageView.setImageBitmap(captcha);
1149
1150			builder.setTitle(getString(R.string.captcha_required));
1151			builder.setView(view);
1152
1153			builder.setPositiveButton(getString(R.string.ok),
1154					(dialog, which) -> {
1155						String rc = input.getText().toString();
1156						data.put("username", account.getUsername());
1157						data.put("password", account.getPassword());
1158						data.put("ocr", rc);
1159						data.submit();
1160
1161						if (xmppConnectionServiceBound) {
1162							xmppConnectionService.sendCreateAccountWithCaptchaPacket(account, id, data);
1163						}
1164					});
1165			builder.setNegativeButton(getString(R.string.cancel), (dialog, which) -> {
1166				if (xmppConnectionService != null) {
1167					xmppConnectionService.sendCreateAccountWithCaptchaPacket(account, null, null);
1168				}
1169			});
1170
1171			builder.setOnCancelListener(dialog -> {
1172				if (xmppConnectionService != null) {
1173					xmppConnectionService.sendCreateAccountWithCaptchaPacket(account, null, null);
1174				}
1175			});
1176			mCaptchaDialog = builder.create();
1177			mCaptchaDialog.show();
1178			input.requestFocus();
1179		});
1180	}
1181
1182	public void onShowErrorToast(final int resId) {
1183		runOnUiThread(() -> Toast.makeText(EditAccountActivity.this, resId, Toast.LENGTH_SHORT).show());
1184	}
1185
1186	@Override
1187	public void onPreferencesFetched(final Element prefs) {
1188		runOnUiThread(() -> {
1189			if (mFetchingMamPrefsToast != null) {
1190				mFetchingMamPrefsToast.cancel();
1191			}
1192			Builder builder = new Builder(EditAccountActivity.this);
1193			builder.setTitle(R.string.server_side_mam_prefs);
1194			String defaultAttr = prefs.getAttribute("default");
1195			final List<String> defaults = Arrays.asList("never", "roster", "always");
1196			final AtomicInteger choice = new AtomicInteger(Math.max(0, defaults.indexOf(defaultAttr)));
1197			builder.setSingleChoiceItems(R.array.mam_prefs, choice.get(), (dialog, which) -> choice.set(which));
1198			builder.setNegativeButton(R.string.cancel, null);
1199			builder.setPositiveButton(R.string.ok, (dialog, which) -> {
1200				prefs.setAttribute("default", defaults.get(choice.get()));
1201				xmppConnectionService.pushMamPreferences(mAccount, prefs);
1202			});
1203			builder.create().show();
1204		});
1205	}
1206
1207	@Override
1208	public void onPreferencesFetchFailed() {
1209		runOnUiThread(() -> {
1210			if (mFetchingMamPrefsToast != null) {
1211				mFetchingMamPrefsToast.cancel();
1212			}
1213			Toast.makeText(EditAccountActivity.this, R.string.unable_to_fetch_mam_prefs, Toast.LENGTH_LONG).show();
1214		});
1215	}
1216
1217	@Override
1218	public void OnUpdateBlocklist(Status status) {
1219		refreshUi();
1220	}
1221}