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