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