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 eu.siacs.conversations.xmpp.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.ofEscaped(binding.accountJid.getText().toString(), getUserModeDomain(), null);
 205                } else {
 206                    jid = Jid.ofEscaped(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().getEscapedLocal();
 581        } else {
 582            unmodified = this.mAccount.getJid().asBareJid().toEscapedString();
 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 (mPendingFingerprintVerificationUri != null) {
 788                processFingerprintVerification(mPendingFingerprintVerificationUri, false);
 789                mPendingFingerprintVerificationUri = null;
 790            }
 791            updateAccountInformation(init);
 792        }
 793
 794
 795        if (Config.MAGIC_CREATE_DOMAIN == null && this.xmppConnectionService.getAccounts().size() == 0) {
 796            this.binding.cancelButton.setEnabled(false);
 797        }
 798        if (mUsernameMode) {
 799            this.binding.accountJidLayout.setHint(getString(R.string.username_hint));
 800            this.binding.accountJid.setHint(R.string.username_hint);
 801        } else {
 802            final KnownHostsAdapter mKnownHostsAdapter = new KnownHostsAdapter(this,
 803                    R.layout.simple_list_item,
 804                    xmppConnectionService.getKnownHosts());
 805            this.binding.accountJid.setAdapter(mKnownHostsAdapter);
 806        }
 807
 808        if (pendingUri != null) {
 809            processFingerprintVerification(pendingUri, false);
 810            pendingUri = null;
 811        }
 812        updatePortLayout();
 813        updateSaveButton();
 814        invalidateOptionsMenu();
 815    }
 816
 817    private String getUserModeDomain() {
 818        if (mAccount != null && mAccount.getJid().getDomain() != null) {
 819            return mAccount.getJid().getDomain();
 820        } else {
 821            return Config.DOMAIN_LOCK;
 822        }
 823    }
 824
 825    @Override
 826    public boolean onOptionsItemSelected(final MenuItem item) {
 827        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
 828            return false;
 829        }
 830        switch (item.getItemId()) {
 831            case android.R.id.home:
 832                deleteAccountAndReturnIfNecessary();
 833                break;
 834            case R.id.action_show_block_list:
 835                final Intent showBlocklistIntent = new Intent(this, BlocklistActivity.class);
 836                showBlocklistIntent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toString());
 837                startActivity(showBlocklistIntent);
 838                break;
 839            case R.id.action_server_info_show_more:
 840                changeMoreTableVisibility(!item.isChecked());
 841                break;
 842            case R.id.action_share_barcode:
 843                shareBarcode();
 844                break;
 845            case R.id.action_share_http:
 846                shareLink(true);
 847                break;
 848            case R.id.action_share_uri:
 849                shareLink(false);
 850                break;
 851            case R.id.action_change_password_on_server:
 852                gotoChangePassword(null);
 853                break;
 854            case R.id.action_mam_prefs:
 855                editMamPrefs();
 856                break;
 857            case R.id.action_renew_certificate:
 858                renewCertificate();
 859                break;
 860            case R.id.action_change_presence:
 861                changePresence();
 862                break;
 863        }
 864        return super.onOptionsItemSelected(item);
 865    }
 866
 867    private boolean inNeedOfSaslAccept() {
 868        return mAccount != null && mAccount.getLastErrorStatus() == Account.State.DOWNGRADE_ATTACK && mAccount.getKeyAsInt(Account.PINNED_MECHANISM_KEY, -1) >= 0 && !accountInfoEdited();
 869    }
 870
 871    private void shareBarcode() {
 872        Intent intent = new Intent(Intent.ACTION_SEND);
 873        intent.putExtra(Intent.EXTRA_STREAM, BarcodeProvider.getUriForAccount(this, mAccount));
 874        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 875        intent.setType("image/png");
 876        startActivity(Intent.createChooser(intent, getText(R.string.share_with)));
 877    }
 878
 879    private void changeMoreTableVisibility(boolean visible) {
 880        binding.serverInfoMore.setVisibility(visible ? View.VISIBLE : View.GONE);
 881    }
 882
 883    private void gotoChangePassword(String newPassword) {
 884        final Intent changePasswordIntent = new Intent(this, ChangePasswordActivity.class);
 885        changePasswordIntent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toString());
 886        if (newPassword != null) {
 887            changePasswordIntent.putExtra("password", newPassword);
 888        }
 889        startActivity(changePasswordIntent);
 890    }
 891
 892    private void renewCertificate() {
 893        KeyChain.choosePrivateKeyAlias(this, this, null, null, null, -1, null);
 894    }
 895
 896    private void changePresence() {
 897        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
 898        boolean manualStatus = sharedPreferences.getBoolean(SettingsActivity.MANUALLY_CHANGE_PRESENCE, getResources().getBoolean(R.bool.manually_change_presence));
 899        AlertDialog.Builder builder = new AlertDialog.Builder(this);
 900        final DialogPresenceBinding binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.dialog_presence, null, false);
 901        String current = mAccount.getPresenceStatusMessage();
 902        if (current != null && !current.trim().isEmpty()) {
 903            binding.statusMessage.append(current);
 904        }
 905        setAvailabilityRadioButton(mAccount.getPresenceStatus(), binding);
 906        binding.show.setVisibility(manualStatus ? View.VISIBLE : View.GONE);
 907        List<PresenceTemplate> templates = xmppConnectionService.getPresenceTemplates(mAccount);
 908        PresenceTemplateAdapter presenceTemplateAdapter = new PresenceTemplateAdapter(this, R.layout.simple_list_item, templates);
 909        binding.statusMessage.setAdapter(presenceTemplateAdapter);
 910        binding.statusMessage.setOnItemClickListener((parent, view, position, id) -> {
 911            PresenceTemplate template = (PresenceTemplate) parent.getItemAtPosition(position);
 912            setAvailabilityRadioButton(template.getStatus(), binding);
 913        });
 914        builder.setTitle(R.string.edit_status_message_title);
 915        builder.setView(binding.getRoot());
 916        builder.setNegativeButton(R.string.cancel, null);
 917        builder.setPositiveButton(R.string.confirm, (dialog, which) -> {
 918            PresenceTemplate template = new PresenceTemplate(getAvailabilityRadioButton(binding), binding.statusMessage.getText().toString().trim());
 919            if (mAccount.getPgpId() != 0 && hasPgp()) {
 920                generateSignature(null, template);
 921            } else {
 922                xmppConnectionService.changeStatus(mAccount, template, null);
 923            }
 924        });
 925        builder.create().show();
 926    }
 927
 928    private void generateSignature(Intent intent, PresenceTemplate template) {
 929        xmppConnectionService.getPgpEngine().generateSignature(intent, mAccount, template.getStatusMessage(), new UiCallback<String>() {
 930            @Override
 931            public void success(String signature) {
 932                xmppConnectionService.changeStatus(mAccount, template, signature);
 933            }
 934
 935            @Override
 936            public void error(int errorCode, String object) {
 937
 938            }
 939
 940            @Override
 941            public void userInputRequired(PendingIntent pi, String object) {
 942                mPendingPresenceTemplate.push(template);
 943                try {
 944                    startIntentSenderForResult(pi.getIntentSender(), REQUEST_CHANGE_STATUS, null, 0, 0, 0);
 945                } catch (final IntentSender.SendIntentException ignored) {
 946                }
 947            }
 948        });
 949    }
 950
 951    @Override
 952    public void alias(String alias) {
 953        if (alias != null) {
 954            xmppConnectionService.updateKeyInAccount(mAccount, alias);
 955        }
 956    }
 957
 958    private void updateAccountInformation(boolean init) {
 959        if (init) {
 960            this.binding.accountJid.getEditableText().clear();
 961            if (mUsernameMode) {
 962                this.binding.accountJid.getEditableText().append(this.mAccount.getJid().getEscapedLocal());
 963            } else {
 964                this.binding.accountJid.getEditableText().append(this.mAccount.getJid().asBareJid().toEscapedString());
 965            }
 966            this.binding.accountPassword.getEditableText().clear();
 967            this.binding.accountPassword.getEditableText().append(this.mAccount.getPassword());
 968            this.binding.hostname.setText("");
 969            this.binding.hostname.getEditableText().append(this.mAccount.getHostname());
 970            this.binding.port.setText("");
 971            this.binding.port.getEditableText().append(String.valueOf(this.mAccount.getPort()));
 972            this.binding.namePort.setVisibility(mShowOptions ? View.VISIBLE : View.GONE);
 973
 974        }
 975
 976        final boolean editable = !mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY) && !mAccount.isOptionSet(Account.OPTION_FIXED_USERNAME) && QuickConversationsService.isConversations();
 977        this.binding.accountJid.setEnabled(editable);
 978        this.binding.accountJid.setFocusable(editable);
 979        this.binding.accountJid.setFocusableInTouchMode(editable);
 980        this.binding.accountJid.setCursorVisible(editable);
 981
 982
 983        final String displayName = mAccount.getDisplayName();
 984        updateDisplayName(displayName);
 985
 986
 987        final boolean tooglePassword = mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE) || !mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
 988        final boolean editPassword = !mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE) || (!mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY) && QuickConversationsService.isConversations()) || mAccount.getLastErrorStatus() == Account.State.UNAUTHORIZED;
 989
 990        this.binding.accountPasswordLayout.setPasswordVisibilityToggleEnabled(tooglePassword);
 991
 992        this.binding.accountPassword.setFocusable(editPassword);
 993        this.binding.accountPassword.setFocusableInTouchMode(editPassword);
 994        this.binding.accountPassword.setCursorVisible(editPassword);
 995        this.binding.accountPassword.setEnabled(editPassword);
 996
 997        if (!mInitMode) {
 998            this.binding.avater.setVisibility(View.VISIBLE);
 999            AvatarWorkerTask.loadAvatar(mAccount, binding.avater, R.dimen.avatar_on_details_screen_size);
1000        } else {
1001            this.binding.avater.setVisibility(View.GONE);
1002        }
1003        this.binding.accountRegisterNew.setChecked(this.mAccount.isOptionSet(Account.OPTION_REGISTER));
1004        if (this.mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE)) {
1005            if (this.mAccount.isOptionSet(Account.OPTION_REGISTER)) {
1006                ActionBar actionBar = getSupportActionBar();
1007                if (actionBar != null) {
1008                    actionBar.setTitle(R.string.create_account);
1009                }
1010            }
1011            this.binding.accountRegisterNew.setVisibility(View.GONE);
1012        } else if (this.mAccount.isOptionSet(Account.OPTION_REGISTER) && mForceRegister == null) {
1013            this.binding.accountRegisterNew.setVisibility(View.VISIBLE);
1014        } else {
1015            this.binding.accountRegisterNew.setVisibility(View.GONE);
1016        }
1017        if (this.mAccount.isOnlineAndConnected() && !this.mFetchingAvatar) {
1018            Features features = this.mAccount.getXmppConnection().getFeatures();
1019            this.binding.stats.setVisibility(View.VISIBLE);
1020            boolean showBatteryWarning = !xmppConnectionService.getPushManagementService().available(mAccount) && isOptimizingBattery();
1021            boolean showDataSaverWarning = isAffectedByDataSaver();
1022            showOsOptimizationWarning(showBatteryWarning, showDataSaverWarning);
1023            this.binding.sessionEst.setText(UIHelper.readableTimeDifferenceFull(this, this.mAccount.getXmppConnection()
1024                    .getLastSessionEstablished()));
1025            if (features.rosterVersioning()) {
1026                this.binding.serverInfoRosterVersion.setText(R.string.server_info_available);
1027            } else {
1028                this.binding.serverInfoRosterVersion.setText(R.string.server_info_unavailable);
1029            }
1030            if (features.carbons()) {
1031                this.binding.serverInfoCarbons.setText(R.string.server_info_available);
1032            } else {
1033                this.binding.serverInfoCarbons.setText(R.string.server_info_unavailable);
1034            }
1035            if (features.mam()) {
1036                this.binding.serverInfoMam.setText(R.string.server_info_available);
1037            } else {
1038                this.binding.serverInfoMam.setText(R.string.server_info_unavailable);
1039            }
1040            if (features.csi()) {
1041                this.binding.serverInfoCsi.setText(R.string.server_info_available);
1042            } else {
1043                this.binding.serverInfoCsi.setText(R.string.server_info_unavailable);
1044            }
1045            if (features.blocking()) {
1046                this.binding.serverInfoBlocking.setText(R.string.server_info_available);
1047            } else {
1048                this.binding.serverInfoBlocking.setText(R.string.server_info_unavailable);
1049            }
1050            if (features.sm()) {
1051                this.binding.serverInfoSm.setText(R.string.server_info_available);
1052            } else {
1053                this.binding.serverInfoSm.setText(R.string.server_info_unavailable);
1054            }
1055            if (features.externalServiceDiscovery()) {
1056                this.binding.serverInfoExternalService.setText(R.string.server_info_available);
1057            } else {
1058                this.binding.serverInfoExternalService.setText(R.string.server_info_unavailable);
1059            }
1060            if (features.pep()) {
1061                AxolotlService axolotlService = this.mAccount.getAxolotlService();
1062                if (axolotlService != null && axolotlService.isPepBroken()) {
1063                    this.binding.serverInfoPep.setText(R.string.server_info_broken);
1064                } else if (features.pepPublishOptions() || features.pepOmemoWhitelisted()) {
1065                    this.binding.serverInfoPep.setText(R.string.server_info_available);
1066                } else {
1067                    this.binding.serverInfoPep.setText(R.string.server_info_partial);
1068                }
1069            } else {
1070                this.binding.serverInfoPep.setText(R.string.server_info_unavailable);
1071            }
1072            if (features.httpUpload(0)) {
1073                final long maxFileSize = features.getMaxHttpUploadSize();
1074                if (maxFileSize > 0) {
1075                    this.binding.serverInfoHttpUpload.setText(UIHelper.filesizeToString(maxFileSize));
1076                } else {
1077                    this.binding.serverInfoHttpUpload.setText(R.string.server_info_available);
1078                }
1079            } else if (features.p1S3FileTransfer()) {
1080                this.binding.serverInfoHttpUploadDescription.setText(R.string.p1_s3_filetransfer);
1081                this.binding.serverInfoHttpUpload.setText(R.string.server_info_available);
1082            } else {
1083                this.binding.serverInfoHttpUpload.setText(R.string.server_info_unavailable);
1084            }
1085
1086            this.binding.pushRow.setVisibility(xmppConnectionService.getPushManagementService().isStub() ? View.GONE : View.VISIBLE);
1087
1088            if (xmppConnectionService.getPushManagementService().available(mAccount)) {
1089                this.binding.serverInfoPush.setText(R.string.server_info_available);
1090            } else {
1091                this.binding.serverInfoPush.setText(R.string.server_info_unavailable);
1092            }
1093            final long pgpKeyId = this.mAccount.getPgpId();
1094            if (pgpKeyId != 0 && Config.supportOpenPgp()) {
1095                OnClickListener openPgp = view -> launchOpenKeyChain(pgpKeyId);
1096                OnClickListener delete = view -> showDeletePgpDialog();
1097                this.binding.pgpFingerprintBox.setVisibility(View.VISIBLE);
1098                this.binding.pgpFingerprint.setText(OpenPgpUtils.convertKeyIdToHex(pgpKeyId));
1099                this.binding.pgpFingerprint.setOnClickListener(openPgp);
1100                if ("pgp".equals(messageFingerprint)) {
1101                    this.binding.pgpFingerprintDesc.setTextAppearance(this, R.style.TextAppearance_Conversations_Caption_Highlight);
1102                }
1103                this.binding.pgpFingerprintDesc.setOnClickListener(openPgp);
1104                this.binding.actionDeletePgp.setOnClickListener(delete);
1105            } else {
1106                this.binding.pgpFingerprintBox.setVisibility(View.GONE);
1107            }
1108            final String ownAxolotlFingerprint = this.mAccount.getAxolotlService().getOwnFingerprint();
1109            if (ownAxolotlFingerprint != null && Config.supportOmemo()) {
1110                this.binding.axolotlFingerprintBox.setVisibility(View.VISIBLE);
1111                if (ownAxolotlFingerprint.equals(messageFingerprint)) {
1112                    this.binding.ownFingerprintDesc.setTextAppearance(this, R.style.TextAppearance_Conversations_Caption_Highlight);
1113                    this.binding.ownFingerprintDesc.setText(R.string.omemo_fingerprint_selected_message);
1114                } else {
1115                    this.binding.ownFingerprintDesc.setTextAppearance(this, R.style.TextAppearance_Conversations_Caption);
1116                    this.binding.ownFingerprintDesc.setText(R.string.omemo_fingerprint);
1117                }
1118                this.binding.axolotlFingerprint.setText(CryptoHelper.prettifyFingerprint(ownAxolotlFingerprint.substring(2)));
1119                this.binding.actionCopyAxolotlToClipboard.setVisibility(View.VISIBLE);
1120                this.binding.actionCopyAxolotlToClipboard.setOnClickListener(v -> copyOmemoFingerprint(ownAxolotlFingerprint));
1121            } else {
1122                this.binding.axolotlFingerprintBox.setVisibility(View.GONE);
1123            }
1124            boolean hasKeys = false;
1125            binding.otherDeviceKeys.removeAllViews();
1126            for (XmppAxolotlSession session : mAccount.getAxolotlService().findOwnSessions()) {
1127                if (!session.getTrust().isCompromised()) {
1128                    boolean highlight = session.getFingerprint().equals(messageFingerprint);
1129                    addFingerprintRow(binding.otherDeviceKeys, session, highlight);
1130                    hasKeys = true;
1131                }
1132            }
1133            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
1134                this.binding.otherDeviceKeysCard.setVisibility(View.VISIBLE);
1135                Set<Integer> otherDevices = mAccount.getAxolotlService().getOwnDeviceIds();
1136                if (otherDevices == null || otherDevices.isEmpty()) {
1137                    binding.clearDevices.setVisibility(View.GONE);
1138                } else {
1139                    binding.clearDevices.setVisibility(View.VISIBLE);
1140                }
1141            } else {
1142                this.binding.otherDeviceKeysCard.setVisibility(View.GONE);
1143            }
1144        } else {
1145            final TextInputLayout errorLayout;
1146            if (this.mAccount.errorStatus()) {
1147                if (this.mAccount.getStatus() == Account.State.UNAUTHORIZED || this.mAccount.getStatus() == Account.State.DOWNGRADE_ATTACK) {
1148                    errorLayout = this.binding.accountPasswordLayout;
1149                } else if (mShowOptions
1150                        && this.mAccount.getStatus() == Account.State.SERVER_NOT_FOUND
1151                        && this.binding.hostname.getText().length() > 0) {
1152                    errorLayout = this.binding.hostnameLayout;
1153                } else {
1154                    errorLayout = this.binding.accountJidLayout;
1155                }
1156                errorLayout.setError(getString(this.mAccount.getStatus().getReadableId()));
1157                if (init || !accountInfoEdited()) {
1158                    errorLayout.requestFocus();
1159                }
1160            } else {
1161                errorLayout = null;
1162            }
1163            removeErrorsOnAllBut(errorLayout);
1164            this.binding.stats.setVisibility(View.GONE);
1165            this.binding.otherDeviceKeysCard.setVisibility(View.GONE);
1166        }
1167    }
1168
1169    private void updateDisplayName(String displayName) {
1170        if (TextUtils.isEmpty(displayName)) {
1171            this.binding.yourName.setText(R.string.no_name_set_instructions);
1172            this.binding.yourName.setTextAppearance(this, R.style.TextAppearance_Conversations_Body1_Tertiary);
1173        } else {
1174            this.binding.yourName.setText(displayName);
1175            this.binding.yourName.setTextAppearance(this, R.style.TextAppearance_Conversations_Body1);
1176        }
1177    }
1178
1179    private void removeErrorsOnAllBut(TextInputLayout exception) {
1180        if (this.binding.accountJidLayout != exception) {
1181            this.binding.accountJidLayout.setErrorEnabled(false);
1182            this.binding.accountJidLayout.setError(null);
1183        }
1184        if (this.binding.accountPasswordLayout != exception) {
1185            this.binding.accountPasswordLayout.setErrorEnabled(false);
1186            this.binding.accountPasswordLayout.setError(null);
1187        }
1188        if (this.binding.hostnameLayout != exception) {
1189            this.binding.hostnameLayout.setErrorEnabled(false);
1190            this.binding.hostnameLayout.setError(null);
1191        }
1192        if (this.binding.portLayout != exception) {
1193            this.binding.portLayout.setErrorEnabled(false);
1194            this.binding.portLayout.setError(null);
1195        }
1196    }
1197
1198    private void showDeletePgpDialog() {
1199        AlertDialog.Builder builder = new AlertDialog.Builder(this);
1200        builder.setTitle(R.string.unpublish_pgp);
1201        builder.setMessage(R.string.unpublish_pgp_message);
1202        builder.setNegativeButton(R.string.cancel, null);
1203        builder.setPositiveButton(R.string.confirm, (dialogInterface, i) -> {
1204            mAccount.setPgpSignId(0);
1205            mAccount.unsetPgpSignature();
1206            xmppConnectionService.databaseBackend.updateAccount(mAccount);
1207            xmppConnectionService.sendPresence(mAccount);
1208            refreshUiReal();
1209        });
1210        builder.create().show();
1211    }
1212
1213    private void showOsOptimizationWarning(boolean showBatteryWarning, boolean showDataSaverWarning) {
1214        this.binding.osOptimization.setVisibility(showBatteryWarning || showDataSaverWarning ? View.VISIBLE : View.GONE);
1215        if (showDataSaverWarning && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
1216            this.binding.osOptimizationHeadline.setText(R.string.data_saver_enabled);
1217            this.binding.osOptimizationBody.setText(R.string.data_saver_enabled_explained);
1218            this.binding.osOptimizationDisable.setText(R.string.allow);
1219            this.binding.osOptimizationDisable.setOnClickListener(v -> {
1220                Intent intent = new Intent(Settings.ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS);
1221                Uri uri = Uri.parse("package:" + getPackageName());
1222                intent.setData(uri);
1223                try {
1224                    startActivityForResult(intent, REQUEST_DATA_SAVER);
1225                } catch (ActivityNotFoundException e) {
1226                    Toast.makeText(EditAccountActivity.this, R.string.device_does_not_support_data_saver, Toast.LENGTH_SHORT).show();
1227                }
1228            });
1229        } else if (showBatteryWarning && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
1230            this.binding.osOptimizationDisable.setText(R.string.disable);
1231            this.binding.osOptimizationHeadline.setText(R.string.battery_optimizations_enabled);
1232            this.binding.osOptimizationBody.setText(R.string.battery_optimizations_enabled_explained);
1233            this.binding.osOptimizationDisable.setOnClickListener(v -> {
1234                Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1235                Uri uri = Uri.parse("package:" + getPackageName());
1236                intent.setData(uri);
1237                try {
1238                    startActivityForResult(intent, REQUEST_BATTERY_OP);
1239                } catch (ActivityNotFoundException e) {
1240                    Toast.makeText(EditAccountActivity.this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
1241                }
1242            });
1243        }
1244    }
1245
1246    public void showWipePepDialog() {
1247        Builder builder = new Builder(this);
1248        builder.setTitle(getString(R.string.clear_other_devices));
1249        builder.setIconAttribute(android.R.attr.alertDialogIcon);
1250        builder.setMessage(getString(R.string.clear_other_devices_desc));
1251        builder.setNegativeButton(getString(R.string.cancel), null);
1252        builder.setPositiveButton(getString(R.string.accept),
1253                (dialog, which) -> mAccount.getAxolotlService().wipeOtherPepDevices());
1254        builder.create().show();
1255    }
1256
1257    private void editMamPrefs() {
1258        this.mFetchingMamPrefsToast = Toast.makeText(this, R.string.fetching_mam_prefs, Toast.LENGTH_LONG);
1259        this.mFetchingMamPrefsToast.show();
1260        xmppConnectionService.fetchMamPreferences(mAccount, this);
1261    }
1262
1263    @Override
1264    public void onKeyStatusUpdated(AxolotlService.FetchStatus report) {
1265        refreshUi();
1266    }
1267
1268    @Override
1269    public void onCaptchaRequested(final Account account, final String id, final Data data, final Bitmap captcha) {
1270        runOnUiThread(() -> {
1271            if (mCaptchaDialog != null && mCaptchaDialog.isShowing()) {
1272                mCaptchaDialog.dismiss();
1273            }
1274            final Builder builder = new Builder(EditAccountActivity.this);
1275            final View view = getLayoutInflater().inflate(R.layout.captcha, null);
1276            final ImageView imageView = view.findViewById(R.id.captcha);
1277            final EditText input = view.findViewById(R.id.input);
1278            imageView.setImageBitmap(captcha);
1279
1280            builder.setTitle(getString(R.string.captcha_required));
1281            builder.setView(view);
1282
1283            builder.setPositiveButton(getString(R.string.ok),
1284                    (dialog, which) -> {
1285                        String rc = input.getText().toString();
1286                        data.put("username", account.getUsername());
1287                        data.put("password", account.getPassword());
1288                        data.put("ocr", rc);
1289                        data.submit();
1290
1291                        if (xmppConnectionServiceBound) {
1292                            xmppConnectionService.sendCreateAccountWithCaptchaPacket(account, id, data);
1293                        }
1294                    });
1295            builder.setNegativeButton(getString(R.string.cancel), (dialog, which) -> {
1296                if (xmppConnectionService != null) {
1297                    xmppConnectionService.sendCreateAccountWithCaptchaPacket(account, null, null);
1298                }
1299            });
1300
1301            builder.setOnCancelListener(dialog -> {
1302                if (xmppConnectionService != null) {
1303                    xmppConnectionService.sendCreateAccountWithCaptchaPacket(account, null, null);
1304                }
1305            });
1306            mCaptchaDialog = builder.create();
1307            mCaptchaDialog.show();
1308            input.requestFocus();
1309        });
1310    }
1311
1312    public void onShowErrorToast(final int resId) {
1313        runOnUiThread(() -> Toast.makeText(EditAccountActivity.this, resId, Toast.LENGTH_SHORT).show());
1314    }
1315
1316    @Override
1317    public void onPreferencesFetched(final Element prefs) {
1318        runOnUiThread(() -> {
1319            if (mFetchingMamPrefsToast != null) {
1320                mFetchingMamPrefsToast.cancel();
1321            }
1322            Builder builder = new Builder(EditAccountActivity.this);
1323            builder.setTitle(R.string.server_side_mam_prefs);
1324            String defaultAttr = prefs.getAttribute("default");
1325            final List<String> defaults = Arrays.asList("never", "roster", "always");
1326            final AtomicInteger choice = new AtomicInteger(Math.max(0, defaults.indexOf(defaultAttr)));
1327            builder.setSingleChoiceItems(R.array.mam_prefs, choice.get(), (dialog, which) -> choice.set(which));
1328            builder.setNegativeButton(R.string.cancel, null);
1329            builder.setPositiveButton(R.string.ok, (dialog, which) -> {
1330                prefs.setAttribute("default", defaults.get(choice.get()));
1331                xmppConnectionService.pushMamPreferences(mAccount, prefs);
1332            });
1333            builder.create().show();
1334        });
1335    }
1336
1337    @Override
1338    public void onPreferencesFetchFailed() {
1339        runOnUiThread(() -> {
1340            if (mFetchingMamPrefsToast != null) {
1341                mFetchingMamPrefsToast.cancel();
1342            }
1343            Toast.makeText(EditAccountActivity.this, R.string.unable_to_fetch_mam_prefs, Toast.LENGTH_LONG).show();
1344        });
1345    }
1346
1347    @Override
1348    public void OnUpdateBlocklist(Status status) {
1349        refreshUi();
1350    }
1351}