EditAccountActivity.java

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