EditAccountActivity.java

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