EditAccountActivity.java

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