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