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