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