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