EditAccountActivity.java

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