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