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