EditAccountActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.app.Activity;
   4import android.app.KeyguardManager;
   5import android.app.PendingIntent;
   6import android.content.ActivityNotFoundException;
   7import android.content.Context;
   8import android.content.Intent;
   9import android.content.IntentSender;
  10import android.content.SharedPreferences;
  11import android.graphics.Bitmap;
  12import android.graphics.drawable.ColorDrawable;
  13import android.net.Uri;
  14import android.os.Build;
  15import android.os.Bundle;
  16import android.os.Handler;
  17import android.preference.PreferenceManager;
  18import android.provider.Settings;
  19import android.security.KeyChain;
  20import android.security.KeyChainAliasCallback;
  21import android.text.Editable;
  22import android.text.TextUtils;
  23import android.text.TextWatcher;
  24import android.util.Log;
  25import android.view.Menu;
  26import android.view.MenuItem;
  27import android.view.View;
  28import android.view.View.OnClickListener;
  29import android.widget.CheckBox;
  30import android.widget.CompoundButton.OnCheckedChangeListener;
  31import android.widget.EditText;
  32import android.widget.ImageView;
  33import android.widget.TextView;
  34import android.widget.Toast;
  35import androidx.annotation.NonNull;
  36import androidx.appcompat.app.ActionBar;
  37import androidx.appcompat.app.AlertDialog;
  38import androidx.databinding.DataBindingUtil;
  39import androidx.lifecycle.Lifecycle;
  40import com.google.android.material.color.MaterialColors;
  41import com.google.android.material.dialog.MaterialAlertDialogBuilder;
  42import com.google.android.material.textfield.TextInputLayout;
  43import com.google.common.base.CharMatcher;
  44import com.google.common.base.Strings;
  45
  46import com.rarepebble.colorpicker.ColorPickerView;
  47
  48import org.openintents.openpgp.util.OpenPgpUtils;
  49
  50import java.text.DateFormat;
  51import java.util.Arrays;
  52import java.util.Calendar;
  53import java.util.Date;
  54import java.util.List;
  55import java.util.Set;
  56import java.util.concurrent.atomic.AtomicInteger;
  57
  58import eu.siacs.conversations.AppSettings;
  59import eu.siacs.conversations.Config;
  60import eu.siacs.conversations.R;
  61import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  62import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  63import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession;
  64import eu.siacs.conversations.databinding.ActivityEditAccountBinding;
  65import eu.siacs.conversations.databinding.DialogPresenceBinding;
  66import eu.siacs.conversations.entities.Account;
  67import eu.siacs.conversations.entities.Presence;
  68import eu.siacs.conversations.entities.PresenceTemplate;
  69import eu.siacs.conversations.services.BarcodeProvider;
  70import eu.siacs.conversations.services.QuickConversationsService;
  71import eu.siacs.conversations.services.XmppConnectionService;
  72import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
  73import eu.siacs.conversations.services.XmppConnectionService.OnCaptchaRequested;
  74import eu.siacs.conversations.ui.TimePreference;
  75import eu.siacs.conversations.ui.adapter.KnownHostsAdapter;
  76import eu.siacs.conversations.ui.adapter.PresenceTemplateAdapter;
  77import eu.siacs.conversations.ui.util.AvatarWorkerTask;
  78import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
  79import eu.siacs.conversations.ui.util.PendingItem;
  80import eu.siacs.conversations.ui.util.SoftKeyboardUtils;
  81import eu.siacs.conversations.utils.Compatibility;
  82import eu.siacs.conversations.utils.CryptoHelper;
  83import eu.siacs.conversations.utils.Resolver;
  84import eu.siacs.conversations.utils.SignupUtils;
  85import eu.siacs.conversations.utils.TorServiceUtils;
  86import eu.siacs.conversations.utils.UIHelper;
  87import eu.siacs.conversations.utils.XmppUri;
  88import eu.siacs.conversations.xml.Element;
  89import eu.siacs.conversations.xmpp.Jid;
  90import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
  91import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  92import eu.siacs.conversations.xmpp.XmppConnection;
  93import eu.siacs.conversations.xmpp.XmppConnection.Features;
  94import eu.siacs.conversations.xmpp.forms.Data;
  95import eu.siacs.conversations.xmpp.pep.Avatar;
  96
  97import static eu.siacs.conversations.utils.PermissionUtils.allGranted;
  98import static eu.siacs.conversations.utils.PermissionUtils.writeGranted;
  99
 100import okhttp3.HttpUrl;
 101import okhttp3.HttpUrl;
 102import org.openintents.openpgp.util.OpenPgpUtils;
 103import org.openintents.openpgp.util.OpenPgpUtils;
 104
 105public class EditAccountActivity extends OmemoActivity
 106        implements OnAccountUpdate,
 107                OnUpdateBlocklist,
 108                OnKeyStatusUpdated,
 109                OnCaptchaRequested,
 110                KeyChainAliasCallback,
 111                XmppConnectionService.OnShowErrorToast,
 112                XmppConnectionService.OnMamPreferencesFetched {
 113
 114    public static final String EXTRA_OPENED_FROM_NOTIFICATION = "opened_from_notification";
 115    public static final String EXTRA_FORCE_REGISTER = "force_register";
 116
 117    private static final int REQUEST_IMPORT_BACKUP = 0x63fb;
 118    private static final int REQUEST_DATA_SAVER = 0xf244;
 119    private static final int REQUEST_CHANGE_STATUS = 0xee11;
 120    private static final int REQUEST_ORBOT = 0xff22;
 121    private static final int REQUEST_UNLOCK = 0xff23;
 122    private final PendingItem<PresenceTemplate> mPendingPresenceTemplate = new PendingItem<>();
 123    private AlertDialog mCaptchaDialog = null;
 124    private Jid jidToEdit;
 125    private boolean mInitMode = false;
 126    private Boolean mForceRegister = null;
 127    private boolean mUsernameMode = false;
 128    private boolean mShowOptions = false;
 129    private Account mAccount;
 130    private final OnClickListener mCancelButtonClickListener =
 131            v -> {
 132                deleteAccountAndReturnIfNecessary();
 133                finish();
 134            };
 135    private final UiCallback<Avatar> mAvatarFetchCallback =
 136            new UiCallback<Avatar>() {
 137
 138                @Override
 139                public void userInputRequired(final PendingIntent pi, final Avatar avatar) {
 140                    finishInitialSetup(avatar);
 141                }
 142
 143                @Override
 144                public void success(final Avatar avatar) {
 145                    finishInitialSetup(avatar);
 146                }
 147
 148                @Override
 149                public void error(final int errorCode, final Avatar avatar) {
 150                    finishInitialSetup(avatar);
 151                }
 152            };
 153    private final OnClickListener mAvatarClickListener =
 154            new OnClickListener() {
 155                @Override
 156                public void onClick(final View view) {
 157                    if (mAccount != null) {
 158                        final Intent intent =
 159                                new Intent(
 160                                        getApplicationContext(),
 161                                        PublishProfilePictureActivity.class);
 162                        intent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().asBareJid().toString());
 163                        startActivity(intent);
 164                    }
 165                }
 166            };
 167    private String messageFingerprint;
 168    private boolean mFetchingAvatar = false;
 169    private Toast mFetchingMamPrefsToast;
 170    private String mSavedInstanceAccount;
 171    private boolean mSavedInstanceInit = false;
 172    private XmppUri pendingUri = null;
 173    private boolean mUseTor;
 174    private ActivityEditAccountBinding binding;
 175    private final OnClickListener mSaveButtonClickListener =
 176            new OnClickListener() {
 177
 178                @Override
 179                public void onClick(final View v) {
 180                    final String password = binding.accountPassword.getText().toString();
 181                    final boolean wasDisabled =
 182                            mAccount != null && mAccount.getStatus() == Account.State.DISABLED;
 183                    final boolean accountInfoEdited = accountInfoEdited();
 184
 185                    ColorDrawable previewColor = (ColorDrawable) binding.colorPreview.getBackground();
 186                    if (previewColor != null && previewColor.getColor() != mAccount.getColor(isDark())) {
 187                        mAccount.setColor(previewColor.getColor());
 188                    }
 189
 190                    if (mInitMode && mAccount != null) {
 191                        mAccount.setOption(Account.OPTION_DISABLED, false);
 192                    }
 193                    if (mAccount != null
 194                            && Arrays.asList(Account.State.DISABLED, Account.State.LOGGED_OUT)
 195                                    .contains(mAccount.getStatus())
 196                            && !accountInfoEdited) {
 197                        mAccount.setOption(Account.OPTION_SOFT_DISABLED, false);
 198                        mAccount.setOption(Account.OPTION_DISABLED, false);
 199                        if (!xmppConnectionService.updateAccount(mAccount)) {
 200                            Toast.makeText(
 201                                            EditAccountActivity.this,
 202                                            R.string.unable_to_update_account,
 203                                            Toast.LENGTH_SHORT)
 204                                    .show();
 205                        }
 206                        return;
 207                    }
 208                    final boolean registerNewAccount;
 209                    if (mForceRegister != null) {
 210                        registerNewAccount = mForceRegister;
 211                    } else {
 212                        registerNewAccount =
 213                                binding.accountRegisterNew.isChecked()
 214                                        && !Config.DISALLOW_REGISTRATION_IN_UI;
 215                    }
 216                    if (mUsernameMode && binding.accountJid.getText().toString().contains("@")) {
 217                        binding.accountJidLayout.setError(getString(R.string.invalid_username));
 218                        removeErrorsOnAllBut(binding.accountJidLayout);
 219                        binding.accountJid.requestFocus();
 220                        return;
 221                    }
 222
 223                    XmppConnection connection =
 224                            mAccount == null ? null : mAccount.getXmppConnection();
 225                    final boolean startOrbot =
 226                            mAccount != null
 227                                    && mAccount.getStatus() == Account.State.TOR_NOT_AVAILABLE;
 228                    if (startOrbot) {
 229                        if (TorServiceUtils.isOrbotInstalled(EditAccountActivity.this)) {
 230                            TorServiceUtils.startOrbot(EditAccountActivity.this, REQUEST_ORBOT);
 231                        } else {
 232                            TorServiceUtils.downloadOrbot(EditAccountActivity.this, REQUEST_ORBOT);
 233                        }
 234                        return;
 235                    }
 236
 237                    if (inNeedOfSaslAccept()) {
 238                        mAccount.resetPinnedMechanism();
 239                        if (!xmppConnectionService.updateAccount(mAccount)) {
 240                            Toast.makeText(
 241                                            EditAccountActivity.this,
 242                                            R.string.unable_to_update_account,
 243                                            Toast.LENGTH_SHORT)
 244                                    .show();
 245                        }
 246                        return;
 247                    }
 248
 249                    final boolean openRegistrationUrl =
 250                            registerNewAccount
 251                                    && !accountInfoEdited
 252                                    && mAccount != null
 253                                    && mAccount.getStatus() == Account.State.REGISTRATION_WEB;
 254                    final boolean openPaymentUrl =
 255                            mAccount != null
 256                                    && mAccount.getStatus() == Account.State.PAYMENT_REQUIRED;
 257                    final boolean redirectionWorthyStatus = openPaymentUrl || openRegistrationUrl;
 258                    final HttpUrl url =
 259                            connection != null && redirectionWorthyStatus
 260                                    ? connection.getRedirectionUrl()
 261                                    : null;
 262                    if (url != null && !wasDisabled) {
 263                        try {
 264                            startActivity(
 265                                    new Intent(Intent.ACTION_VIEW, Uri.parse(url.toString())));
 266                            return;
 267                        } catch (ActivityNotFoundException e) {
 268                            Toast.makeText(
 269                                            EditAccountActivity.this,
 270                                            R.string.application_found_to_open_website,
 271                                            Toast.LENGTH_SHORT)
 272                                    .show();
 273                            return;
 274                        }
 275                    }
 276
 277                    final Jid jid;
 278                    try {
 279                        if (mUsernameMode) {
 280                            jid =
 281                                    Jid.of(
 282                                            binding.accountJid.getText().toString(),
 283                                            getUserModeDomain(),
 284                                            null);
 285                        } else {
 286                            jid = Jid.ofUserInput(binding.accountJid.getText().toString());
 287                            Resolver.checkDomain(jid);
 288                        }
 289                    } catch (final NullPointerException | IllegalArgumentException e) {
 290                        if (mUsernameMode) {
 291                            binding.accountJidLayout.setError(getString(R.string.invalid_username));
 292                        } else {
 293                            binding.accountJidLayout.setError(getString(R.string.invalid_jid));
 294                        }
 295                        binding.accountJid.requestFocus();
 296                        removeErrorsOnAllBut(binding.accountJidLayout);
 297                        return;
 298                    }
 299                    final String hostname;
 300                    int numericPort = 5222;
 301                    if (mShowOptions) {
 302                        hostname = CharMatcher.whitespace().removeFrom(binding.hostname.getText());
 303                        final String port =
 304                                CharMatcher.whitespace().removeFrom(binding.port.getText());
 305                        if (Resolver.invalidHostname(hostname)) {
 306                            binding.hostnameLayout.setError(getString(R.string.not_valid_hostname));
 307                            binding.hostname.requestFocus();
 308                            removeErrorsOnAllBut(binding.hostnameLayout);
 309                            return;
 310                        }
 311                        if (!hostname.isEmpty()) {
 312                            try {
 313                                numericPort = Integer.parseInt(port);
 314                                if (numericPort < 0 || numericPort > 65535) {
 315                                    binding.portLayout.setError(
 316                                            getString(R.string.not_a_valid_port));
 317                                    removeErrorsOnAllBut(binding.portLayout);
 318                                    binding.port.requestFocus();
 319                                    return;
 320                                }
 321
 322                            } catch (NumberFormatException e) {
 323                                binding.portLayout.setError(getString(R.string.not_a_valid_port));
 324                                removeErrorsOnAllBut(binding.portLayout);
 325                                binding.port.requestFocus();
 326                                return;
 327                            }
 328                        }
 329                    } else {
 330                        hostname = null;
 331                    }
 332
 333                    if (jid.getLocal() == null) {
 334                        if (mUsernameMode) {
 335                            binding.accountJidLayout.setError(getString(R.string.invalid_username));
 336                        } else {
 337                            binding.accountJidLayout.setError(getString(R.string.invalid_jid));
 338                        }
 339                        removeErrorsOnAllBut(binding.accountJidLayout);
 340                        binding.accountJid.requestFocus();
 341                        return;
 342                    }
 343                    if (mAccount != null) {
 344                        if (mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE)) {
 345                            mAccount.setOption(
 346                                    Account.OPTION_MAGIC_CREATE,
 347                                    mAccount.getPassword().contains(password));
 348                        }
 349                        mAccount.setJid(jid);
 350                        mAccount.setPort(numericPort);
 351                        mAccount.setHostname(hostname);
 352                        binding.accountJidLayout.setError(null);
 353                        mAccount.setPassword(password);
 354                        mAccount.setOption(Account.OPTION_REGISTER, registerNewAccount);
 355                        if (!xmppConnectionService.updateAccount(mAccount)) {
 356                            Toast.makeText(
 357                                            EditAccountActivity.this,
 358                                            R.string.unable_to_update_account,
 359                                            Toast.LENGTH_SHORT)
 360                                    .show();
 361                            return;
 362                        }
 363                    } else {
 364                        if (xmppConnectionService.findAccountByJid(jid) != null) {
 365                            binding.accountJidLayout.setError(
 366                                    getString(R.string.account_already_exists));
 367                            removeErrorsOnAllBut(binding.accountJidLayout);
 368                            binding.accountJid.requestFocus();
 369                            return;
 370                        }
 371                        mAccount = new Account(jid.asBareJid(), password);
 372                        mAccount.setPort(numericPort);
 373                        mAccount.setHostname(hostname);
 374                        mAccount.setOption(Account.OPTION_REGISTER, registerNewAccount);
 375                        xmppConnectionService.createAccount(mAccount);
 376                    }
 377                    binding.hostnameLayout.setError(null);
 378                    binding.portLayout.setError(null);
 379                    if (mAccount.isOnion()) {
 380                        Toast.makeText(
 381                                        EditAccountActivity.this,
 382                                        R.string.audio_video_disabled_tor,
 383                                        Toast.LENGTH_LONG)
 384                                .show();
 385                    }
 386                    if (mAccount.isEnabled() && !registerNewAccount && !mInitMode) {
 387                        finish();
 388                    } else {
 389                        updateSaveButton();
 390                        updateAccountInformation(true);
 391                    }
 392                }
 393            };
 394    private final TextWatcher mTextWatcher =
 395            new TextWatcher() {
 396
 397                @Override
 398                public void onTextChanged(
 399                        final CharSequence s, final int start, final int before, final int count) {
 400                    updatePortLayout();
 401                    updateSaveButton();
 402                }
 403
 404                @Override
 405                public void beforeTextChanged(
 406                        final CharSequence s, final int start, final int count, final int after) {}
 407
 408                @Override
 409                public void afterTextChanged(final Editable s) {}
 410            };
 411    private final View.OnFocusChangeListener mEditTextFocusListener =
 412            new View.OnFocusChangeListener() {
 413                @Override
 414                public void onFocusChange(View view, boolean b) {
 415                    EditText et = (EditText) view;
 416                    if (b) {
 417                        int resId =
 418                                mUsernameMode
 419                                        ? R.string.username
 420                                        : R.string.account_settings_example_jabber_id;
 421                        if (view.getId() == R.id.hostname) {
 422                            resId =
 423                                    mUseTor
 424                                            ? R.string.hostname_or_onion
 425                                            : R.string.hostname_example;
 426                        }
 427                        final int res = resId;
 428                        new Handler().postDelayed(() -> et.setHint(res), 200);
 429                    } else {
 430                        et.setHint(null);
 431                    }
 432                }
 433            };
 434
 435    private static void setAvailabilityRadioButton(
 436            Presence.Status status, DialogPresenceBinding binding) {
 437        if (status == null) {
 438            binding.online.setChecked(true);
 439            return;
 440        }
 441        switch (status) {
 442            case DND:
 443                binding.dnd.setChecked(true);
 444                break;
 445            case XA:
 446                binding.xa.setChecked(true);
 447                break;
 448            case AWAY:
 449                binding.away.setChecked(true);
 450                break;
 451            default:
 452                binding.online.setChecked(true);
 453        }
 454    }
 455
 456    private static Presence.Status getAvailabilityRadioButton(DialogPresenceBinding binding) {
 457        if (binding.dnd.isChecked()) {
 458            return Presence.Status.DND;
 459        } else if (binding.xa.isChecked()) {
 460            return Presence.Status.XA;
 461        } else if (binding.away.isChecked()) {
 462            return Presence.Status.AWAY;
 463        } else {
 464            return Presence.Status.ONLINE;
 465        }
 466    }
 467
 468    public void refreshUiReal() {
 469        invalidateOptionsMenu();
 470        if (mAccount != null && mAccount.getStatus() != Account.State.ONLINE && mFetchingAvatar) {
 471            Intent intent = new Intent(this, StartConversationActivity.class);
 472            StartConversationActivity.addInviteUri(intent, getIntent());
 473            startActivity(intent);
 474            finish();
 475        } else if (mInitMode && mAccount != null && mAccount.getStatus() == Account.State.ONLINE) {
 476            if (!mFetchingAvatar) {
 477                mFetchingAvatar = true;
 478                xmppConnectionService.checkForAvatar(mAccount, mAvatarFetchCallback);
 479            }
 480        }
 481        if (mAccount != null) {
 482            updateAccountInformation(false);
 483        }
 484        updateSaveButton();
 485    }
 486
 487    @Override
 488    public boolean onNavigateUp() {
 489        deleteAccountAndReturnIfNecessary();
 490        return super.onNavigateUp();
 491    }
 492
 493    @Override
 494    public void onBackPressed() {
 495        deleteAccountAndReturnIfNecessary();
 496        super.onBackPressed();
 497    }
 498
 499    private void deleteAccountAndReturnIfNecessary() {
 500        if (mInitMode
 501                && mAccount != null
 502                && !mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY)) {
 503            xmppConnectionService.deleteAccount(mAccount);
 504        }
 505
 506        final boolean magicCreate =
 507                mAccount != null
 508                        && mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE)
 509                        && !mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
 510        final Jid jid = mAccount == null ? null : mAccount.getJid();
 511
 512        if (SignupUtils.isSupportTokenRegistry()
 513                && jid != null
 514                && magicCreate
 515                && !jid.getDomain().equals(Config.MAGIC_CREATE_DOMAIN)) {
 516            final Jid preset;
 517            if (mAccount.isOptionSet(Account.OPTION_FIXED_USERNAME)) {
 518                preset = jid.asBareJid();
 519            } else {
 520                preset = jid.getDomain();
 521            }
 522            final Intent intent =
 523                    SignupUtils.getTokenRegistrationIntent(
 524                            this, preset, mAccount.getKey(Account.KEY_PRE_AUTH_REGISTRATION_TOKEN));
 525            StartConversationActivity.addInviteUri(intent, getIntent());
 526            startActivity(intent);
 527            return;
 528        }
 529
 530        final List<Account> accounts =
 531                xmppConnectionService == null ? null : xmppConnectionService.getAccounts();
 532        if (accounts != null && accounts.size() == 0 && Config.MAGIC_CREATE_DOMAIN != null) {
 533            Intent intent =
 534                    SignupUtils.getSignUpIntent(this, mForceRegister != null && mForceRegister);
 535            StartConversationActivity.addInviteUri(intent, getIntent());
 536            startActivity(intent);
 537        }
 538    }
 539
 540    @Override
 541    public void onAccountUpdate() {
 542        refreshUi();
 543    }
 544
 545    protected void finishInitialSetup(final Avatar avatar) {
 546        runOnUiThread(
 547                () -> {
 548                    SoftKeyboardUtils.hideSoftKeyboard(EditAccountActivity.this);
 549                    final Intent intent;
 550                    final XmppConnection connection = mAccount.getXmppConnection();
 551                    final boolean wasFirstAccount =
 552                            xmppConnectionService != null
 553                                    && xmppConnectionService.getAccounts().size() == 1;
 554                    if (avatar != null || (connection != null && !connection.getFeatures().pep())) {
 555                        intent =
 556                                new Intent(
 557                                        getApplicationContext(), StartConversationActivity.class);
 558                        intent.putExtra("init", true);
 559                        intent.putExtra(
 560                                EXTRA_ACCOUNT, mAccount.getJid().asBareJid().toString());
 561                    } else {
 562                        intent =
 563                                new Intent(
 564                                        getApplicationContext(),
 565                                        PublishProfilePictureActivity.class);
 566                        intent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().asBareJid().toString());
 567                        intent.putExtra("setup", true);
 568                    }
 569                    if (wasFirstAccount) {
 570                        intent.setFlags(
 571                                Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
 572                    }
 573                    StartConversationActivity.addInviteUri(intent, getIntent());
 574                    startActivity(intent);
 575                    finish();
 576                });
 577    }
 578
 579    @Override
 580    public void onActivityResult(int requestCode, int resultCode, Intent data) {
 581        // TODO check for Camera / Scan permission
 582        super.onActivityResult(requestCode, resultCode, data);
 583        if (requestCode == REQUEST_BATTERY_OP || requestCode == REQUEST_DATA_SAVER) {
 584            updateAccountInformation(mAccount == null);
 585        }
 586        if (requestCode == REQUEST_BATTERY_OP) {
 587            // the result code is always 0 even when battery permission were granted
 588            XmppConnectionService.toggleForegroundService(xmppConnectionService);
 589        }
 590        if (requestCode == REQUEST_CHANGE_STATUS) {
 591            PresenceTemplate template = mPendingPresenceTemplate.pop();
 592            if (template != null && resultCode == Activity.RESULT_OK) {
 593                generateSignature(data, template);
 594            } else {
 595                Log.d(Config.LOGTAG, "pgp result not ok");
 596            }
 597        }
 598        if (requestCode == REQUEST_UNLOCK) {
 599            if (resultCode == RESULT_OK) {
 600                openChangePassword(true);
 601            }
 602        }
 603    }
 604
 605    @Override
 606    protected void processFingerprintVerification(XmppUri uri) {
 607        processFingerprintVerification(uri, true);
 608    }
 609
 610    protected void processFingerprintVerification(XmppUri uri, boolean showWarningToast) {
 611        if (mAccount != null
 612                && mAccount.getJid().asBareJid().equals(uri.getJid())
 613                && uri.hasFingerprints()) {
 614            if (xmppConnectionService.verifyFingerprints(mAccount, uri.getFingerprints())) {
 615                Toast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show();
 616                updateAccountInformation(false);
 617            }
 618        } else if (showWarningToast) {
 619            Toast.makeText(this, R.string.invalid_barcode, Toast.LENGTH_SHORT).show();
 620        }
 621    }
 622
 623    private void updatePortLayout() {
 624        final String hostname = this.binding.hostname.getText().toString();
 625        if (TextUtils.isEmpty(hostname)) {
 626            this.binding.portLayout.setEnabled(false);
 627            this.binding.portLayout.setError(null);
 628        } else {
 629            this.binding.portLayout.setEnabled(true);
 630        }
 631    }
 632
 633    protected void updateSaveButton() {
 634        boolean accountInfoEdited = accountInfoEdited();
 635
 636        if (accountInfoEdited && !mInitMode) {
 637            this.binding.saveButton.setText(R.string.save);
 638            this.binding.saveButton.setEnabled(true);
 639        } else if (mAccount != null
 640                && (mAccount.getStatus() == Account.State.CONNECTING
 641                        || mAccount.getStatus() == Account.State.REGISTRATION_SUCCESSFUL
 642                        || mFetchingAvatar)) {
 643            this.binding.saveButton.setEnabled(false);
 644            this.binding.saveButton.setText(R.string.account_status_connecting);
 645        } else if (mAccount != null
 646                && mAccount.getStatus() == Account.State.DISABLED
 647                && !mInitMode) {
 648            this.binding.saveButton.setEnabled(true);
 649            this.binding.saveButton.setText(R.string.enable);
 650        } else if (torNeedsInstall(mAccount)) {
 651            this.binding.saveButton.setEnabled(true);
 652            this.binding.saveButton.setText(R.string.install_orbot);
 653        } else if (torNeedsStart(mAccount)) {
 654            this.binding.saveButton.setEnabled(true);
 655            this.binding.saveButton.setText(R.string.start_orbot);
 656        } else {
 657            this.binding.saveButton.setEnabled(true);
 658            if (!mInitMode) {
 659                if (mAccount != null && mAccount.isOnlineAndConnected()) {
 660                    this.binding.saveButton.setText(R.string.save);
 661                    if (!accountInfoEdited) {
 662                        this.binding.saveButton.setEnabled(false);
 663                    }
 664                } else {
 665                    XmppConnection connection =
 666                            mAccount == null ? null : mAccount.getXmppConnection();
 667                    HttpUrl url =
 668                            connection != null
 669                                            && mAccount.getStatus()
 670                                                    == Account.State.PAYMENT_REQUIRED
 671                                    ? connection.getRedirectionUrl()
 672                                    : null;
 673                    if (url != null) {
 674                        this.binding.saveButton.setText(R.string.open_website);
 675                    } else if (inNeedOfSaslAccept()) {
 676                        this.binding.saveButton.setText(R.string.accept);
 677                    } else {
 678                        this.binding.saveButton.setText(R.string.connect);
 679                    }
 680                }
 681            } else {
 682                XmppConnection connection = mAccount == null ? null : mAccount.getXmppConnection();
 683                HttpUrl url =
 684                        connection != null && mAccount.getStatus() == Account.State.REGISTRATION_WEB
 685                                ? connection.getRedirectionUrl()
 686                                : null;
 687                if (url != null
 688                        && this.binding.accountRegisterNew.isChecked()
 689                        && !accountInfoEdited) {
 690                    this.binding.saveButton.setText(R.string.open_website);
 691                } else {
 692                    this.binding.saveButton.setText(R.string.next);
 693                }
 694            }
 695        }
 696    }
 697
 698    private boolean torNeedsInstall(final Account account) {
 699        return account != null
 700                && account.getStatus() == Account.State.TOR_NOT_AVAILABLE
 701                && !TorServiceUtils.isOrbotInstalled(this);
 702    }
 703
 704    private boolean torNeedsStart(final Account account) {
 705        return account != null && account.getStatus() == Account.State.TOR_NOT_AVAILABLE;
 706    }
 707
 708    protected boolean accountInfoEdited() {
 709        if (this.mAccount == null) {
 710            return false;
 711        }
 712        ColorDrawable previewColor = (ColorDrawable) binding.colorPreview.getBackground();
 713        return jidEdited()
 714                || !this.mAccount
 715                        .getPassword()
 716                        .equals(this.binding.accountPassword.getText().toString())
 717                || !this.mAccount.getHostname().equals(this.binding.hostname.getText().toString())
 718                || this.mAccount.getColor(isDark()) != (previewColor == null ? 0 : previewColor.getColor())
 719                || !String.valueOf(this.mAccount.getPort())
 720                        .equals(this.binding.port.getText().toString());
 721    }
 722
 723    protected boolean jidEdited() {
 724        final String unmodified;
 725        if (mUsernameMode) {
 726            unmodified = this.mAccount.getJid().getLocal();
 727        } else {
 728            unmodified = this.mAccount.getJid().asBareJid().toString();
 729        }
 730        return !unmodified.equals(this.binding.accountJid.getText().toString());
 731    }
 732
 733    @Override
 734    protected String getShareableUri(boolean http) {
 735        if (mAccount != null) {
 736            return http ? mAccount.getShareableLink() : mAccount.getShareableUri();
 737        } else {
 738            return null;
 739        }
 740    }
 741
 742    @Override
 743    protected void onCreate(final Bundle savedInstanceState) {
 744        super.onCreate(savedInstanceState);
 745        if (savedInstanceState != null) {
 746            this.mSavedInstanceAccount = savedInstanceState.getString("account");
 747            this.mSavedInstanceInit = savedInstanceState.getBoolean("initMode", false);
 748        }
 749        this.binding = DataBindingUtil.setContentView(this, R.layout.activity_edit_account);
 750        Activities.setStatusAndNavigationBarColors(this, binding.getRoot());
 751        setSupportActionBar(binding.toolbar);
 752        binding.accountJid.addTextChangedListener(this.mTextWatcher);
 753        binding.accountJid.setOnFocusChangeListener(this.mEditTextFocusListener);
 754        this.binding.accountPassword.addTextChangedListener(this.mTextWatcher);
 755
 756        this.binding.avater.setOnClickListener(this.mAvatarClickListener);
 757        this.binding.hostname.addTextChangedListener(mTextWatcher);
 758        this.binding.hostname.setOnFocusChangeListener(mEditTextFocusListener);
 759        this.binding.clearDevices.setOnClickListener(v -> showWipePepDialog());
 760        this.binding.port.setText(String.valueOf(Resolver.XMPP_PORT_STARTTLS));
 761        this.binding.port.addTextChangedListener(mTextWatcher);
 762        this.binding.saveButton.setOnClickListener(this.mSaveButtonClickListener);
 763        this.binding.cancelButton.setOnClickListener(this.mCancelButtonClickListener);
 764        if (savedInstanceState != null && savedInstanceState.getBoolean("showMoreTable")) {
 765            changeMoreTableVisibility(true);
 766        }
 767        final OnCheckedChangeListener OnCheckedShowConfirmPassword =
 768                (buttonView, isChecked) -> updateSaveButton();
 769        this.binding.accountRegisterNew.setOnCheckedChangeListener(OnCheckedShowConfirmPassword);
 770        if (Config.DISALLOW_REGISTRATION_IN_UI) {
 771            this.binding.accountRegisterNew.setVisibility(View.GONE);
 772        }
 773        this.binding.actionEditYourName.setOnClickListener(this::onEditYourNameClicked);
 774        binding.accountColorBox.setOnClickListener((v) -> {
 775            showColorDialog();
 776        });
 777
 778        final var preferences = getPreferences();
 779        binding.quietHoursEnable.setOnClickListener((v) -> {
 780            preferences.edit().putBoolean("enable_quiet_hours:" + mAccount.getUuid(), binding.quietHoursEnable.isChecked()).apply();
 781            updateAccountInformation(false);
 782        });
 783        binding.quietHoursStartBox.setOnClickListener((v) -> {
 784            final var picker = new com.google.android.material.timepicker.MaterialTimePicker.Builder()
 785                .setTitleText("Quiet Hours Start")
 786                .setHour((int)(preferences.getLong("quiet_hours_start:" + mAccount.getUuid(), 1320) / 60))
 787                .setMinute((int)(preferences.getLong("quiet_hours_start:" + mAccount.getUuid(), 1320) % 60))
 788                .build();
 789            picker.addOnPositiveButtonClickListener((v2) -> {
 790                preferences.edit().putLong("quiet_hours_start:" + mAccount.getUuid(), (picker.getHour() * 60) + picker.getMinute()).apply();
 791                updateAccountInformation(false);
 792            });
 793            picker.show(getSupportFragmentManager(), "quiethoursstart");
 794        });
 795        binding.quietHoursEndBox.setOnClickListener((v) -> {
 796            final var picker = new com.google.android.material.timepicker.MaterialTimePicker.Builder()
 797                .setTitleText("Quiet Hours End")
 798                .setHour((int)(preferences.getLong("quiet_hours_end:" + mAccount.getUuid(), 1320) / 60))
 799                .setMinute((int)(preferences.getLong("quiet_hours_end:" + mAccount.getUuid(), 1320) % 60))
 800                .build();
 801            picker.addOnPositiveButtonClickListener((v2) -> {
 802                preferences.edit().putLong("quiet_hours_end:" + mAccount.getUuid(), (picker.getHour() * 60) + picker.getMinute()).apply();
 803                updateAccountInformation(false);
 804            });
 805            picker.show(getSupportFragmentManager(), "quiethoursend");
 806        });
 807        this.binding.scanButton.setOnClickListener((v) -> ScanActivity.scan(this));
 808    }
 809
 810    private void onEditYourNameClicked(View view) {
 811        quickEdit(
 812                mAccount.getDisplayName(),
 813                R.string.your_name,
 814                value -> {
 815                    final String displayName = value.trim();
 816                    updateDisplayName(displayName);
 817                    mAccount.setDisplayName(displayName);
 818                    xmppConnectionService.publishDisplayName(mAccount);
 819                    refreshAvatar();
 820                    return null;
 821                },
 822                true);
 823    }
 824
 825    private void refreshAvatar() {
 826        AvatarWorkerTask.loadAvatar(
 827                mAccount, binding.avater, R.dimen.avatar_on_details_screen_size);
 828    }
 829
 830    @Override
 831    public boolean onCreateOptionsMenu(final Menu menu) {
 832        super.onCreateOptionsMenu(menu);
 833        getMenuInflater().inflate(R.menu.editaccount, menu);
 834        final MenuItem showBlocklist = menu.findItem(R.id.action_show_block_list);
 835        final MenuItem showMoreInfo = menu.findItem(R.id.action_server_info_show_more);
 836        final MenuItem changePassword = menu.findItem(R.id.action_change_password_on_server);
 837        final MenuItem deleteAccount = menu.findItem(R.id.action_delete_account);
 838        final MenuItem renewCertificate = menu.findItem(R.id.action_renew_certificate);
 839        final MenuItem mamPrefs = menu.findItem(R.id.action_mam_prefs);
 840        final MenuItem changePresence = menu.findItem(R.id.action_change_presence);
 841        final MenuItem share = menu.findItem(R.id.action_share);
 842        final MenuItem importBackup = menu.findItem(R.id.action_import_backup);
 843        renewCertificate.setVisible(mAccount != null && mAccount.getPrivateKeyAlias() != null);
 844
 845        share.setVisible(mAccount != null && !mInitMode);
 846        importBackup.setVisible(mAccount == null || mInitMode);
 847
 848        if (mAccount != null && mAccount.isOnlineAndConnected()) {
 849            if (!mAccount.getXmppConnection().getFeatures().blocking()) {
 850                showBlocklist.setVisible(false);
 851            }
 852
 853            if (!mAccount.getXmppConnection().getFeatures().register()) {
 854                changePassword.setVisible(false);
 855                deleteAccount.setVisible(false);
 856            }
 857            mamPrefs.setVisible(mAccount.getXmppConnection().getFeatures().mam());
 858            changePresence.setVisible(!mInitMode);
 859        } else {
 860            showBlocklist.setVisible(false);
 861            showMoreInfo.setVisible(false);
 862            changePassword.setVisible(false);
 863            deleteAccount.setVisible(false);
 864            mamPrefs.setVisible(false);
 865            changePresence.setVisible(false);
 866        }
 867        return super.onCreateOptionsMenu(menu);
 868    }
 869
 870    @Override
 871    public boolean onPrepareOptionsMenu(Menu menu) {
 872        final MenuItem showMoreInfo = menu.findItem(R.id.action_server_info_show_more);
 873        if (showMoreInfo.isVisible()) {
 874            showMoreInfo.setChecked(binding.serverInfoMore.getVisibility() == View.VISIBLE);
 875        }
 876        return super.onPrepareOptionsMenu(menu);
 877    }
 878
 879    @Override
 880    public void onStart() {
 881        super.onStart();
 882        final Intent intent = getIntent();
 883        if (intent != null) {
 884            try {
 885                this.jidToEdit = Jid.of(intent.getStringExtra("jid"));
 886            } catch (final IllegalArgumentException | NullPointerException ignored) {
 887                this.jidToEdit = null;
 888            }
 889            final Uri data = intent.getData();
 890            final XmppUri xmppUri = data == null ? null : new XmppUri(data);
 891            final boolean scanned = intent.getBooleanExtra("scanned", false);
 892            if (jidToEdit != null && xmppUri != null && xmppUri.hasFingerprints()) {
 893                if (scanned) {
 894                    if (xmppConnectionServiceBound) {
 895                        processFingerprintVerification(xmppUri, false);
 896                    } else {
 897                        this.pendingUri = xmppUri;
 898                    }
 899                } else {
 900                    displayVerificationWarningDialog(xmppUri);
 901                }
 902            }
 903            boolean init = intent.getBooleanExtra("init", false);
 904            boolean openedFromNotification =
 905                    intent.getBooleanExtra(EXTRA_OPENED_FROM_NOTIFICATION, false);
 906            Log.d(Config.LOGTAG, "extras " + intent.getExtras());
 907            this.mForceRegister =
 908                    intent.hasExtra(EXTRA_FORCE_REGISTER)
 909                            ? intent.getBooleanExtra(EXTRA_FORCE_REGISTER, false)
 910                            : null;
 911            Log.d(Config.LOGTAG, "force register=" + mForceRegister);
 912            this.mInitMode = init || this.jidToEdit == null;
 913            this.messageFingerprint = intent.getStringExtra("fingerprint");
 914            if (!mInitMode) {
 915                this.binding.accountRegisterNew.setVisibility(View.GONE);
 916                setTitle(getString(R.string.account_details));
 917                configureActionBar(getSupportActionBar(), !openedFromNotification);
 918            } else {
 919                this.binding.avater.setVisibility(View.GONE);
 920                configureActionBar(
 921                        getSupportActionBar(), !(init && Config.MAGIC_CREATE_DOMAIN == null));
 922                if (mForceRegister != null) {
 923                    if (mForceRegister) {
 924                        setTitle(R.string.register_new_account);
 925                    } else {
 926                        setTitle(R.string.add_existing_account);
 927                    }
 928                } else {
 929                    setTitle(R.string.action_add_account);
 930                }
 931            }
 932        }
 933        SharedPreferences preferences = getPreferences();
 934        mUseTor = preferences.getBoolean("use_tor", getResources().getBoolean(R.bool.use_tor));
 935        this.mShowOptions = mUseTor || preferences.getBoolean("show_connection_options", getResources().getBoolean(R.bool.show_connection_options));
 936        this.binding.namePort.setVisibility(mShowOptions ? View.VISIBLE : View.GONE);
 937        if (mForceRegister != null) {
 938            this.binding.accountRegisterNew.setVisibility(View.GONE);
 939        }
 940        if (intent.getBooleanExtra("snikket", false)) {
 941            this.binding.accountJidLayout.setHint("Snikket Address");
 942        }
 943    }
 944
 945    private void displayVerificationWarningDialog(final XmppUri xmppUri) {
 946        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
 947        builder.setTitle(R.string.verify_omemo_keys);
 948        View view = getLayoutInflater().inflate(R.layout.dialog_verify_fingerprints, null);
 949        final CheckBox isTrustedSource = view.findViewById(R.id.trusted_source);
 950        TextView warning = view.findViewById(R.id.warning);
 951        warning.setText(R.string.verifying_omemo_keys_trusted_source_account);
 952        builder.setView(view);
 953        builder.setPositiveButton(
 954                R.string.continue_btn,
 955                (dialog, which) -> {
 956                    if (isTrustedSource.isChecked()) {
 957                        processFingerprintVerification(xmppUri, false);
 958                    } else {
 959                        finish();
 960                    }
 961                });
 962        builder.setNegativeButton(R.string.cancel, (dialog, which) -> finish());
 963        final var dialog = builder.create();
 964        dialog.setCanceledOnTouchOutside(false);
 965        dialog.setOnCancelListener(d -> finish());
 966        dialog.show();
 967    }
 968
 969    @Override
 970    public void onNewIntent(final Intent intent) {
 971        super.onNewIntent(intent);
 972        if (intent != null && intent.getData() != null) {
 973            final XmppUri uri = new XmppUri(intent.getData());
 974            if (xmppConnectionServiceBound) {
 975                processFingerprintVerification(uri, false);
 976            } else {
 977                this.pendingUri = uri;
 978            }
 979        }
 980    }
 981
 982    @Override
 983    public void onSaveInstanceState(@NonNull final Bundle savedInstanceState) {
 984        if (mAccount != null) {
 985            savedInstanceState.putString("account", mAccount.getJid().asBareJid().toString());
 986            savedInstanceState.putBoolean("initMode", mInitMode);
 987            savedInstanceState.putBoolean(
 988                    "showMoreTable", binding.serverInfoMore.getVisibility() == View.VISIBLE);
 989        }
 990        super.onSaveInstanceState(savedInstanceState);
 991    }
 992
 993    protected void onBackendConnected() {
 994        boolean init = true;
 995        if (mSavedInstanceAccount != null) {
 996            try {
 997                this.mAccount =
 998                        xmppConnectionService.findAccountByJid(Jid.of(mSavedInstanceAccount));
 999                this.mInitMode = mSavedInstanceInit;
1000                init = false;
1001            } catch (IllegalArgumentException e) {
1002                this.mAccount = null;
1003            }
1004
1005        } else if (this.jidToEdit != null) {
1006            this.mAccount = xmppConnectionService.findAccountByJid(jidToEdit);
1007        }
1008
1009        if (mAccount != null) {
1010            this.mInitMode |= this.mAccount.isOptionSet(Account.OPTION_REGISTER);
1011            this.mUsernameMode |=
1012                    mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE)
1013                            && mAccount.isOptionSet(Account.OPTION_REGISTER);
1014            if (mPendingFingerprintVerificationUri != null) {
1015                processFingerprintVerification(mPendingFingerprintVerificationUri, false);
1016                mPendingFingerprintVerificationUri = null;
1017            }
1018            updateAccountInformation(init);
1019        }
1020
1021        if (Config.MAGIC_CREATE_DOMAIN == null
1022                && this.xmppConnectionService.getAccounts().size() == 0) {
1023            this.binding.cancelButton.setEnabled(false);
1024        }
1025        if (mUsernameMode) {
1026            this.binding.accountJidLayout.setHint(getString(R.string.username_hint));
1027        } else {
1028            final KnownHostsAdapter mKnownHostsAdapter =
1029                    new KnownHostsAdapter(
1030                            this,
1031                            R.layout.item_autocomplete,
1032                            xmppConnectionService.getKnownHosts());
1033            this.binding.accountJid.setAdapter(mKnownHostsAdapter);
1034        }
1035
1036        if (pendingUri != null) {
1037            processFingerprintVerification(pendingUri, false);
1038            pendingUri = null;
1039        }
1040        updatePortLayout();
1041        updateSaveButton();
1042        invalidateOptionsMenu();
1043    }
1044
1045    private String getUserModeDomain() {
1046        if (mAccount != null && mAccount.getJid().getDomain() != null) {
1047            return mAccount.getServer();
1048        } else {
1049            return null;
1050        }
1051    }
1052
1053    @Override
1054    public boolean onOptionsItemSelected(final MenuItem item) {
1055        if (MenuDoubleTabUtil.shouldIgnoreTap()) {
1056            return false;
1057        }
1058        switch (item.getItemId()) {
1059            case android.R.id.home:
1060                deleteAccountAndReturnIfNecessary();
1061                break;
1062            case R.id.action_show_block_list:
1063                final Intent showBlocklistIntent = new Intent(this, BlocklistActivity.class);
1064                showBlocklistIntent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toString());
1065                startActivity(showBlocklistIntent);
1066                break;
1067            case R.id.action_server_info_show_more:
1068                changeMoreTableVisibility(!item.isChecked());
1069                break;
1070            case R.id.action_share_barcode:
1071                shareBarcode();
1072                break;
1073            case R.id.action_share_http:
1074                shareLink(true);
1075                break;
1076            case R.id.action_share_uri:
1077                shareLink(false);
1078                break;
1079            case R.id.action_change_password_on_server:
1080                gotoChangePassword();
1081                break;
1082            case R.id.action_delete_account:
1083                deleteAccount();
1084                break;
1085            case R.id.action_mam_prefs:
1086                editMamPrefs();
1087                break;
1088            case R.id.action_renew_certificate:
1089                renewCertificate();
1090                break;
1091            case R.id.action_change_presence:
1092                changePresence();
1093                break;
1094            case R.id.action_import_backup:
1095                if (hasStoragePermission(REQUEST_IMPORT_BACKUP)) {
1096                    startActivity(new Intent(this, ImportBackupActivity.class));
1097                }
1098                break;
1099        }
1100        return super.onOptionsItemSelected(item);
1101    }
1102
1103    private void deleteAccount() {
1104        this.deleteAccount(mAccount, () -> finish());
1105    }
1106
1107    private boolean inNeedOfSaslAccept() {
1108        return mAccount != null
1109                && mAccount.getLastErrorStatus() == Account.State.DOWNGRADE_ATTACK
1110                && mAccount.getPinnedMechanismPriority() >= 0
1111                && !accountInfoEdited();
1112    }
1113
1114    private void shareBarcode() {
1115        Intent intent = new Intent(Intent.ACTION_SEND);
1116        intent.putExtra(Intent.EXTRA_STREAM, BarcodeProvider.getUriForAccount(this, mAccount));
1117        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1118        intent.setType("image/png");
1119        startActivity(Intent.createChooser(intent, getText(R.string.share_with)));
1120    }
1121
1122    private void changeMoreTableVisibility(final boolean visible) {
1123        binding.serverInfoMore.setVisibility(visible ? View.VISIBLE : View.GONE);
1124        binding.serverInfoLoginMechanism.setVisibility(visible ? View.VISIBLE : View.GONE);
1125    }
1126
1127    private void gotoChangePassword() {
1128        KeyguardManager keyguardManager = (KeyguardManager) this.getSystemService(Context.KEYGUARD_SERVICE);
1129        Intent credentialsIntent = keyguardManager.createConfirmDeviceCredentialIntent("Unlock required", "Please unlock in order to change your password");
1130        if (credentialsIntent == null) {
1131            openChangePassword(false);
1132        } else {
1133            startActivityForResult(credentialsIntent, REQUEST_UNLOCK);
1134        }
1135    }
1136
1137    private void openChangePassword(boolean didUnlock) {
1138        final Intent changePasswordIntent = new Intent(this, ChangePasswordActivity.class);
1139        changePasswordIntent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toString());
1140        changePasswordIntent.putExtra("did_unlock", didUnlock);
1141        startActivity(changePasswordIntent);
1142    }
1143
1144    private void renewCertificate() {
1145        KeyChain.choosePrivateKeyAlias(this, this, null, null, null, -1, null);
1146    }
1147
1148    private void changePresence() {
1149        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1150        boolean manualStatus =
1151                sharedPreferences.getBoolean(
1152                        AppSettings.MANUALLY_CHANGE_PRESENCE,
1153                        getResources().getBoolean(R.bool.manually_change_presence));
1154        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
1155        final DialogPresenceBinding binding =
1156                DataBindingUtil.inflate(getLayoutInflater(), R.layout.dialog_presence, null, false);
1157        String current = mAccount.getPresenceStatusMessage();
1158        if (current != null && !current.trim().isEmpty()) {
1159            binding.statusMessage.append(current);
1160        }
1161        setAvailabilityRadioButton(mAccount.getPresenceStatus(), binding);
1162        binding.show.setVisibility(manualStatus ? View.VISIBLE : View.GONE);
1163        List<PresenceTemplate> templates = xmppConnectionService.getPresenceTemplates(mAccount);
1164        PresenceTemplateAdapter presenceTemplateAdapter =
1165                new PresenceTemplateAdapter(this, R.layout.item_autocomplete, templates);
1166        binding.statusMessage.setAdapter(presenceTemplateAdapter);
1167        binding.statusMessage.setOnItemClickListener(
1168                (parent, view, position, id) -> {
1169                    PresenceTemplate template =
1170                            (PresenceTemplate) parent.getItemAtPosition(position);
1171                    setAvailabilityRadioButton(template.getStatus(), binding);
1172                });
1173        builder.setTitle(R.string.edit_status_message_title);
1174        builder.setView(binding.getRoot());
1175        builder.setNegativeButton(R.string.cancel, null);
1176        builder.setPositiveButton(
1177                R.string.confirm,
1178                (dialog, which) -> {
1179                    PresenceTemplate template =
1180                            new PresenceTemplate(
1181                                    getAvailabilityRadioButton(binding),
1182                                    binding.statusMessage.getText().toString().trim());
1183                    if (mAccount.getPgpId() != 0 && hasPgp()) {
1184                        generateSignature(null, template);
1185                    } else {
1186                        xmppConnectionService.changeStatus(mAccount, template, null);
1187                    }
1188                });
1189        builder.create().show();
1190    }
1191
1192    private void generateSignature(Intent intent, PresenceTemplate template) {
1193        xmppConnectionService
1194                .getPgpEngine()
1195                .generateSignature(
1196                        intent,
1197                        mAccount,
1198                        template.getStatusMessage(),
1199                        new UiCallback<String>() {
1200                            @Override
1201                            public void success(String signature) {
1202                                xmppConnectionService.changeStatus(mAccount, template, signature);
1203                            }
1204
1205                            @Override
1206                            public void error(int errorCode, String object) {}
1207
1208                            @Override
1209                            public void userInputRequired(PendingIntent pi, String object) {
1210                                mPendingPresenceTemplate.push(template);
1211                                try {
1212                                    startIntentSenderForResult(
1213                                            pi.getIntentSender(),
1214                                            REQUEST_CHANGE_STATUS,
1215                                            null,
1216                                            0,
1217                                            0,
1218                                            0,
1219                                            Compatibility.pgpStartIntentSenderOptions());
1220                                } catch (final IntentSender.SendIntentException ignored) {
1221                                }
1222                            }
1223                        });
1224    }
1225
1226    @Override
1227    public void alias(String alias) {
1228        if (alias != null) {
1229            xmppConnectionService.updateKeyInAccount(mAccount, alias);
1230        }
1231    }
1232
1233    void showColorDialog() {
1234        AlertDialog.Builder builder = new AlertDialog.Builder(this);
1235        final ColorPickerView picker = new ColorPickerView(this);
1236
1237        if (mAccount != null) picker.setColor(mAccount.getColor(isDark()));
1238        picker.showAlpha(true);
1239        picker.showHex(true);
1240        picker.showPreview(true);
1241        builder
1242                .setTitle(null)
1243                .setView(picker)
1244                .setPositiveButton(R.string.ok, (dialog, which) -> {
1245                    final int color = picker.getColor();
1246                    binding.colorPreview.setBackgroundColor(color);
1247                    updateSaveButton();
1248                })
1249                .setNegativeButton(R.string.cancel, (dialog, which) -> {});
1250        builder.show();
1251    }
1252
1253    private void updateAccountInformation(boolean init) {
1254        if (init) {
1255            this.binding.accountJid.getEditableText().clear();
1256            if (mUsernameMode) {
1257                this.binding.accountJid.getEditableText().append(this.mAccount.getJid().getLocal());
1258            } else {
1259                this.binding
1260                        .accountJid
1261                        .getEditableText()
1262                        .append(this.mAccount.getJid().asBareJid().toString());
1263            }
1264            this.binding.accountPassword.getEditableText().clear();
1265            this.binding.accountPassword.getEditableText().append(this.mAccount.getPassword());
1266            this.binding.hostname.setText("");
1267            this.binding.hostname.getEditableText().append(this.mAccount.getHostname());
1268            this.binding.port.setText("");
1269            this.binding.port.getEditableText().append(String.valueOf(this.mAccount.getPort()));
1270            this.binding.namePort.setVisibility(mShowOptions ? View.VISIBLE : View.GONE);
1271        }
1272
1273        final var preferences = getPreferences();
1274        binding.quietHoursEnable.setChecked(preferences.getBoolean("enable_quiet_hours:" + mAccount.getUuid(), false));
1275
1276        if (binding.quietHoursEnable.isChecked()) {
1277            binding.quietHoursStartBox.setVisibility(View.VISIBLE);
1278            binding.quietHoursEndBox.setVisibility(View.VISIBLE);
1279        } else {
1280            binding.quietHoursStartBox.setVisibility(View.GONE);
1281            binding.quietHoursEndBox.setVisibility(View.GONE);
1282        }
1283
1284        final var startTime = preferences.getLong("quiet_hours_start:" + mAccount.getUuid(), 1320);
1285		final DateFormat dateFormat = android.text.format.DateFormat.getTimeFormat(this);
1286		final Date date = TimePreference.minutesToCalender(startTime).getTime();
1287        binding.quietHoursStart.setText(dateFormat.format(date.getTime()));
1288
1289        final var endTime = preferences.getLong("quiet_hours_end:" + mAccount.getUuid(), 480);
1290		final DateFormat dateFormatE = android.text.format.DateFormat.getTimeFormat(this);
1291		final Date dateE = TimePreference.minutesToCalender(endTime).getTime();
1292        binding.quietHoursEnd.setText(dateFormat.format(dateE.getTime()));
1293
1294        if (!mInitMode && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
1295            this.binding.accountPassword.setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_NO);
1296        }
1297
1298        final boolean editable =
1299                !mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY)
1300                        && !mAccount.isOptionSet(Account.OPTION_FIXED_USERNAME)
1301                        && QuickConversationsService.isConversations();
1302        this.binding.accountJid.setEnabled(editable);
1303        this.binding.accountJid.setFocusable(editable);
1304        this.binding.accountJid.setFocusableInTouchMode(editable);
1305        this.binding.accountJid.setCursorVisible(editable);
1306
1307        final String displayName = mAccount.getDisplayName();
1308        updateDisplayName(displayName);
1309
1310        if (xmppConnectionService != null && xmppConnectionService.getAccounts().size() > 1) {
1311            binding.accountColorBox.setVisibility(View.VISIBLE);
1312            binding.colorPreview.setBackgroundColor(mAccount.getColor(isDark()));
1313            binding.quietHoursBox.setVisibility(View.VISIBLE);
1314        } else {
1315            binding.accountColorBox.setVisibility(View.GONE);
1316            binding.quietHoursBox.setVisibility(View.GONE);
1317        }
1318
1319        final boolean togglePassword =
1320                mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE)
1321                        || !mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
1322        final boolean neverLoggedIn =
1323                !mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
1324        final boolean editPassword = mAccount.unauthorized() || neverLoggedIn;
1325
1326        this.binding.accountPasswordLayout.setPasswordVisibilityToggleEnabled(togglePassword);
1327
1328        this.binding.accountPassword.setFocusable(editPassword);
1329        this.binding.accountPassword.setFocusableInTouchMode(editPassword);
1330        this.binding.accountPassword.setCursorVisible(editPassword);
1331        this.binding.accountPassword.setEnabled(editPassword);
1332
1333        if (!mInitMode) {
1334            this.binding.avater.setVisibility(View.VISIBLE);
1335            AvatarWorkerTask.loadAvatar(
1336                    mAccount, binding.avater, R.dimen.avatar_on_details_screen_size);
1337        } else {
1338            this.binding.avater.setVisibility(View.GONE);
1339        }
1340        this.binding.accountRegisterNew.setChecked(
1341                this.mAccount.isOptionSet(Account.OPTION_REGISTER));
1342        if (this.mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE)) {
1343            if (this.mAccount.isOptionSet(Account.OPTION_REGISTER)) {
1344                ActionBar actionBar = getSupportActionBar();
1345                if (actionBar != null) {
1346                    actionBar.setTitle(R.string.create_account);
1347                }
1348            }
1349            this.binding.accountRegisterNew.setVisibility(View.GONE);
1350        } else if (this.mAccount.isOptionSet(Account.OPTION_REGISTER) && mForceRegister == null) {
1351            this.binding.accountRegisterNew.setVisibility(View.VISIBLE);
1352        } else {
1353            this.binding.accountRegisterNew.setVisibility(View.GONE);
1354        }
1355        if (this.mAccount.isOnlineAndConnected() && !this.mFetchingAvatar) {
1356            final Features features = this.mAccount.getXmppConnection().getFeatures();
1357            this.binding.stats.setVisibility(View.VISIBLE);
1358            boolean showBatteryWarning = isOptimizingBattery();
1359            boolean showDataSaverWarning = isAffectedByDataSaver();
1360            showOsOptimizationWarning(showBatteryWarning, showDataSaverWarning);
1361            this.binding.sessionEst.setText(
1362                    UIHelper.readableTimeDifferenceFull(
1363                            this, this.mAccount.getXmppConnection().getLastSessionEstablished()));
1364            if (features.rosterVersioning()) {
1365                this.binding.serverInfoRosterVersion.setText(R.string.server_info_available);
1366            } else {
1367                this.binding.serverInfoRosterVersion.setText(R.string.server_info_unavailable);
1368            }
1369            if (features.carbons()) {
1370                this.binding.serverInfoCarbons.setText(R.string.server_info_available);
1371            } else {
1372                this.binding.serverInfoCarbons.setText(R.string.server_info_unavailable);
1373            }
1374            if (features.mam()) {
1375                this.binding.serverInfoMam.setText(R.string.server_info_available);
1376            } else {
1377                this.binding.serverInfoMam.setText(R.string.server_info_unavailable);
1378            }
1379            if (features.csi()) {
1380                this.binding.serverInfoCsi.setText(R.string.server_info_available);
1381            } else {
1382                this.binding.serverInfoCsi.setText(R.string.server_info_unavailable);
1383            }
1384            if (features.blocking()) {
1385                this.binding.serverInfoBlocking.setText(R.string.server_info_available);
1386            } else {
1387                this.binding.serverInfoBlocking.setText(R.string.server_info_unavailable);
1388            }
1389            if (features.sm()) {
1390                this.binding.serverInfoSm.setText(R.string.server_info_available);
1391            } else {
1392                this.binding.serverInfoSm.setText(R.string.server_info_unavailable);
1393            }
1394            if (features.externalServiceDiscovery()) {
1395                this.binding.serverInfoExternalService.setText(R.string.server_info_available);
1396            } else {
1397                this.binding.serverInfoExternalService.setText(R.string.server_info_unavailable);
1398            }
1399            if (features.bind2()) {
1400                this.binding.serverInfoBind2.setText(R.string.server_info_available);
1401            } else {
1402                this.binding.serverInfoBind2.setText(R.string.server_info_unavailable);
1403            }
1404            if (features.sasl2()) {
1405                this.binding.serverInfoSasl2.setText(R.string.server_info_available);
1406            } else {
1407                this.binding.serverInfoSasl2.setText(R.string.server_info_unavailable);
1408            }
1409            this.binding.loginMechanism.setText(Strings.nullToEmpty(features.loginMechanism()));
1410            if (features.pep()) {
1411                AxolotlService axolotlService = this.mAccount.getAxolotlService();
1412                if (axolotlService != null && axolotlService.isPepBroken()) {
1413                    this.binding.serverInfoPep.setText(R.string.server_info_broken);
1414                } else if (features.pepPublishOptions() || features.pepOmemoWhitelisted()) {
1415                    this.binding.serverInfoPep.setText(R.string.server_info_available);
1416                } else {
1417                    this.binding.serverInfoPep.setText(R.string.server_info_partial);
1418                }
1419            } else {
1420                this.binding.serverInfoPep.setText(R.string.server_info_unavailable);
1421            }
1422            if (features.httpUpload(0)) {
1423                final long maxFileSize = features.getMaxHttpUploadSize();
1424                if (maxFileSize > 0) {
1425                    this.binding.serverInfoHttpUpload.setText(
1426                            UIHelper.filesizeToString(maxFileSize));
1427                } else {
1428                    this.binding.serverInfoHttpUpload.setText(R.string.server_info_available);
1429                }
1430            } else {
1431                this.binding.serverInfoHttpUpload.setText(R.string.server_info_unavailable);
1432            }
1433
1434            this.binding.pushRow.setVisibility(
1435                    xmppConnectionService.getPushManagementService().isStub()
1436                            ? View.GONE
1437                            : View.VISIBLE);
1438
1439            if (xmppConnectionService.getPushManagementService().available(mAccount)) {
1440                this.binding.serverInfoPush.setText(R.string.server_info_available);
1441            } else {
1442                this.binding.serverInfoPush.setText(R.string.server_info_unavailable);
1443            }
1444            final long pgpKeyId = this.mAccount.getPgpId();
1445            if (pgpKeyId != 0 && Config.supportOpenPgp()) {
1446                OnClickListener openPgp = view -> launchOpenKeyChain(pgpKeyId);
1447                OnClickListener delete = view -> showDeletePgpDialog();
1448                this.binding.pgpFingerprintBox.setVisibility(View.VISIBLE);
1449                this.binding.pgpFingerprint.setText(OpenPgpUtils.convertKeyIdToHex(pgpKeyId));
1450                this.binding.pgpFingerprint.setOnClickListener(openPgp);
1451                if ("pgp".equals(messageFingerprint)) {
1452                    this.binding.pgpFingerprintDesc.setTextColor(
1453                            MaterialColors.getColor(
1454                                    binding.pgpFingerprintDesc,
1455                                    com.google.android.material.R.attr.colorPrimaryVariant));
1456                }
1457                this.binding.pgpFingerprintDesc.setOnClickListener(openPgp);
1458                this.binding.actionDeletePgp.setOnClickListener(delete);
1459            } else {
1460                this.binding.pgpFingerprintBox.setVisibility(View.GONE);
1461            }
1462            final String ownAxolotlFingerprint =
1463                    this.mAccount.getAxolotlService().getOwnFingerprint();
1464            if (ownAxolotlFingerprint != null && Config.supportOmemo()) {
1465                this.binding.axolotlFingerprintBox.setVisibility(View.VISIBLE);
1466                if (ownAxolotlFingerprint.equals(messageFingerprint)) {
1467                    this.binding.ownFingerprintDesc.setTextColor(
1468                            MaterialColors.getColor(
1469                                    binding.ownFingerprintDesc,
1470                                    com.google.android.material.R.attr.colorPrimaryVariant));
1471                    this.binding.ownFingerprintDesc.setText(
1472                            R.string.omemo_fingerprint_selected_message);
1473                } else {
1474                    this.binding.ownFingerprintDesc.setTextColor(
1475                            MaterialColors.getColor(
1476                                    binding.ownFingerprintDesc,
1477                                    com.google.android.material.R.attr.colorOnSurface));
1478                    this.binding.ownFingerprintDesc.setText(R.string.omemo_fingerprint);
1479                }
1480                this.binding.axolotlFingerprint.setText(
1481                        CryptoHelper.prettifyFingerprint(ownAxolotlFingerprint.substring(2)));
1482                this.binding.showQrCodeButton.setVisibility(View.VISIBLE);
1483                this.binding.showQrCodeButton.setOnClickListener(v -> showQrCode());
1484            } else {
1485                this.binding.axolotlFingerprintBox.setVisibility(View.GONE);
1486            }
1487            boolean hasKeys = false;
1488            boolean showUnverifiedWarning = false;
1489            binding.otherDeviceKeys.removeAllViews();
1490            for (final XmppAxolotlSession session :
1491                    mAccount.getAxolotlService().findOwnSessions()) {
1492                final FingerprintStatus trust = session.getTrust();
1493                if (!trust.isCompromised()) {
1494                    boolean highlight = session.getFingerprint().equals(messageFingerprint);
1495                    addFingerprintRow(binding.otherDeviceKeys, session, highlight);
1496                    hasKeys = true;
1497                }
1498                if (trust.isUnverified()) {
1499                    showUnverifiedWarning = true;
1500                }
1501            }
1502            if (hasKeys
1503                    && Config.supportOmemo()) { // TODO: either the button should be visible if we
1504                // print an active device or the device list should
1505                // be fed with reactivated devices
1506                this.binding.otherDeviceKeysCard.setVisibility(View.VISIBLE);
1507                Set<Integer> otherDevices = mAccount.getAxolotlService().getOwnDeviceIds();
1508                if (otherDevices == null || otherDevices.isEmpty()) {
1509                    binding.clearDevices.setVisibility(View.GONE);
1510                } else {
1511                    binding.clearDevices.setVisibility(View.VISIBLE);
1512                }
1513                binding.unverifiedWarning.setVisibility(
1514                        showUnverifiedWarning ? View.VISIBLE : View.GONE);
1515                binding.scanButton.setVisibility(showUnverifiedWarning ? View.VISIBLE : View.GONE);
1516            } else {
1517                this.binding.otherDeviceKeysCard.setVisibility(View.GONE);
1518            }
1519            this.binding.verificationBox.setVisibility(View.VISIBLE);
1520            if (mAccount.getXmppConnection() != null && mAccount.getXmppConnection().resolverAuthenticated()) {
1521                if (mAccount.getXmppConnection().daneVerified()) {
1522                    this.binding.verificationMessage.setText("DNSSEC + DANE Verified");
1523                    this.binding.verificationIndicator.setImageResource(R.drawable.shield_verified);
1524                } else {
1525                    this.binding.verificationMessage.setText("DNSSEC Verified");
1526                    this.binding.verificationIndicator.setImageResource(R.drawable.shield);
1527                }
1528            } else {
1529                this.binding.verificationMessage.setText("Not DNSSEC Verified");
1530                this.binding.verificationIndicator.setImageResource(R.drawable.shield_question);
1531            }
1532        } else {
1533            final TextInputLayout errorLayout;
1534            final var status = this.mAccount.getStatus();
1535            if (status.isError()
1536                    || Arrays.asList(
1537                                    Account.State.NO_INTERNET,
1538                                    Account.State.MISSING_INTERNET_PERMISSION)
1539                            .contains(status)) {
1540                if (status == Account.State.UNAUTHORIZED
1541                        || status == Account.State.DOWNGRADE_ATTACK) {
1542                    errorLayout = this.binding.accountPasswordLayout;
1543                } else if (mShowOptions
1544                        && status == Account.State.SERVER_NOT_FOUND
1545                        && this.binding.hostname.getText().length() > 0) {
1546                    errorLayout = this.binding.hostnameLayout;
1547                } else {
1548                    errorLayout = this.binding.accountJidLayout;
1549                }
1550                errorLayout.setError(getString(this.mAccount.getStatus().getReadableId()));
1551                if (init || !accountInfoEdited()) {
1552                    errorLayout.requestFocus();
1553                }
1554            } else {
1555                errorLayout = null;
1556            }
1557            removeErrorsOnAllBut(errorLayout);
1558            this.binding.stats.setVisibility(View.GONE);
1559            this.binding.otherDeviceKeysCard.setVisibility(View.GONE);
1560            this.binding.verificationBox.setVisibility(View.GONE);
1561        }
1562    }
1563
1564    private void updateDisplayName(String displayName) {
1565        if (TextUtils.isEmpty(displayName)) {
1566            this.binding.yourName.setText(R.string.no_name_set_instructions);
1567            this.binding.yourName.setTextColor(
1568                    MaterialColors.getColor(
1569                            binding.yourName,
1570                            com.google.android.material.R.attr.colorOnSurfaceVariant));
1571        } else {
1572            this.binding.yourName.setText(displayName);
1573            this.binding.yourName.setTextColor(
1574                    MaterialColors.getColor(
1575                            binding.yourName,
1576                            com.google.android.material.R.attr.colorOnSurfaceVariant));
1577        }
1578    }
1579
1580    private void removeErrorsOnAllBut(TextInputLayout exception) {
1581        if (this.binding.accountJidLayout != exception) {
1582            this.binding.accountJidLayout.setErrorEnabled(false);
1583            this.binding.accountJidLayout.setError(null);
1584        }
1585        if (this.binding.accountPasswordLayout != exception) {
1586            this.binding.accountPasswordLayout.setErrorEnabled(false);
1587            this.binding.accountPasswordLayout.setError(null);
1588        }
1589        if (this.binding.hostnameLayout != exception) {
1590            this.binding.hostnameLayout.setErrorEnabled(false);
1591            this.binding.hostnameLayout.setError(null);
1592        }
1593        if (this.binding.portLayout != exception) {
1594            this.binding.portLayout.setErrorEnabled(false);
1595            this.binding.portLayout.setError(null);
1596        }
1597    }
1598
1599    private void showDeletePgpDialog() {
1600        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
1601        builder.setTitle(R.string.unpublish_pgp);
1602        builder.setMessage(R.string.unpublish_pgp_message);
1603        builder.setNegativeButton(R.string.cancel, null);
1604        builder.setPositiveButton(
1605                R.string.confirm,
1606                (dialogInterface, i) -> {
1607                    mAccount.setPgpSignId(0);
1608                    mAccount.unsetPgpSignature();
1609                    xmppConnectionService.databaseBackend.updateAccount(mAccount);
1610                    xmppConnectionService.sendPresence(mAccount);
1611                    refreshUiReal();
1612                });
1613        builder.create().show();
1614    }
1615
1616    private void showOsOptimizationWarning(
1617            boolean showBatteryWarning, boolean showDataSaverWarning) {
1618        this.binding.osOptimization.setVisibility(
1619                showBatteryWarning || showDataSaverWarning ? View.VISIBLE : View.GONE);
1620        if (showDataSaverWarning
1621                && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
1622            this.binding.osOptimizationHeadline.setText(R.string.data_saver_enabled);
1623            this.binding.osOptimizationBody.setText(
1624                    getString(R.string.data_saver_enabled_explained, getString(R.string.app_name)));
1625            this.binding.osOptimizationDisable.setText(R.string.allow);
1626            this.binding.osOptimizationDisable.setOnClickListener(
1627                    v -> {
1628                        Intent intent =
1629                                new Intent(
1630                                        Settings
1631                                                .ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS);
1632                        Uri uri = Uri.parse("package:" + getPackageName());
1633                        intent.setData(uri);
1634                        try {
1635                            startActivityForResult(intent, REQUEST_DATA_SAVER);
1636                        } catch (ActivityNotFoundException e) {
1637                            Toast.makeText(
1638                                            EditAccountActivity.this,
1639                                            getString(
1640                                                    R.string.device_does_not_support_data_saver,
1641                                                    getString(R.string.app_name)),
1642                                            Toast.LENGTH_SHORT)
1643                                    .show();
1644                        }
1645                    });
1646        } else if (showBatteryWarning) {
1647            this.binding.osOptimizationDisable.setText(R.string.disable);
1648            this.binding.osOptimizationHeadline.setText(R.string.battery_optimizations_enabled);
1649            this.binding.osOptimizationBody.setText(
1650                    getString(
1651                            R.string.battery_optimizations_enabled_explained,
1652                            getString(R.string.app_name)));
1653            this.binding.osOptimizationDisable.setOnClickListener(
1654                    v -> {
1655                        Intent intent =
1656                                new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1657                        Uri uri = Uri.parse("package:" + getPackageName());
1658                        intent.setData(uri);
1659                        try {
1660                            startActivityForResult(intent, REQUEST_BATTERY_OP);
1661                        } catch (ActivityNotFoundException e) {
1662                            Toast.makeText(
1663                                            EditAccountActivity.this,
1664                                            R.string.device_does_not_support_battery_op,
1665                                            Toast.LENGTH_SHORT)
1666                                    .show();
1667                        }
1668                    });
1669        }
1670    }
1671
1672    public void showWipePepDialog() {
1673        final MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
1674        builder.setTitle(getString(R.string.clear_other_devices));
1675        builder.setIconAttribute(android.R.attr.alertDialogIcon);
1676        builder.setMessage(getString(R.string.clear_other_devices_desc));
1677        builder.setNegativeButton(getString(R.string.cancel), null);
1678        builder.setPositiveButton(
1679                getString(R.string.accept),
1680                (dialog, which) -> mAccount.getAxolotlService().wipeOtherPepDevices());
1681        builder.create().show();
1682    }
1683
1684    private void editMamPrefs() {
1685        this.mFetchingMamPrefsToast =
1686                Toast.makeText(this, R.string.fetching_mam_prefs, Toast.LENGTH_LONG);
1687        this.mFetchingMamPrefsToast.show();
1688        xmppConnectionService.fetchMamPreferences(mAccount, this);
1689    }
1690
1691    @Override
1692    public void onKeyStatusUpdated(AxolotlService.FetchStatus report) {
1693        refreshUi();
1694    }
1695
1696    @Override
1697    public void onCaptchaRequested(
1698            final Account account, final String id, final Data data, final Bitmap captcha) {
1699        runOnUiThread(
1700                () -> {
1701                    if (mCaptchaDialog != null && mCaptchaDialog.isShowing()) {
1702                        mCaptchaDialog.dismiss();
1703                    }
1704                    if (!getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) {
1705                        Log.d(Config.LOGTAG, "activity not running when captcha was requested");
1706                        return;
1707                    }
1708                    final MaterialAlertDialogBuilder builder =
1709                            new MaterialAlertDialogBuilder(EditAccountActivity.this);
1710                    final View view = getLayoutInflater().inflate(R.layout.captcha, null);
1711                    final ImageView imageView = view.findViewById(R.id.captcha);
1712                    final EditText input = view.findViewById(R.id.input);
1713                    imageView.setImageBitmap(captcha);
1714
1715                    builder.setTitle(getString(R.string.captcha_required));
1716                    builder.setView(view);
1717
1718                    builder.setPositiveButton(
1719                            getString(R.string.ok),
1720                            (dialog, which) -> {
1721                                String rc = input.getText().toString();
1722                                data.put("username", account.getUsername());
1723                                data.put("password", account.getPassword());
1724                                data.put("ocr", rc);
1725                                data.submit();
1726
1727                                if (xmppConnectionServiceBound) {
1728                                    xmppConnectionService.sendCreateAccountWithCaptchaPacket(
1729                                            account, id, data);
1730                                }
1731                            });
1732                    builder.setNegativeButton(
1733                            getString(R.string.cancel),
1734                            (dialog, which) -> {
1735                                if (xmppConnectionService != null) {
1736                                    xmppConnectionService.sendCreateAccountWithCaptchaPacket(
1737                                            account, null, null);
1738                                }
1739                            });
1740
1741                    builder.setOnCancelListener(
1742                            dialog -> {
1743                                if (xmppConnectionService != null) {
1744                                    xmppConnectionService.sendCreateAccountWithCaptchaPacket(
1745                                            account, null, null);
1746                                }
1747                            });
1748                    mCaptchaDialog = builder.create();
1749                    mCaptchaDialog.show();
1750                    input.requestFocus();
1751                });
1752    }
1753
1754    public void onShowErrorToast(final int resId) {
1755        runOnUiThread(
1756                () -> Toast.makeText(EditAccountActivity.this, resId, Toast.LENGTH_SHORT).show());
1757    }
1758
1759    @Override
1760    public void onPreferencesFetched(final Element prefs) {
1761        runOnUiThread(
1762                () -> {
1763                    if (mFetchingMamPrefsToast != null) {
1764                        mFetchingMamPrefsToast.cancel();
1765                    }
1766                    final MaterialAlertDialogBuilder builder =
1767                            new MaterialAlertDialogBuilder(EditAccountActivity.this);
1768                    builder.setTitle(R.string.server_side_mam_prefs);
1769                    String defaultAttr = prefs.getAttribute("default");
1770                    final List<String> defaults = Arrays.asList("never", "roster", "always");
1771                    final AtomicInteger choice =
1772                            new AtomicInteger(Math.max(0, defaults.indexOf(defaultAttr)));
1773                    builder.setSingleChoiceItems(
1774                            R.array.mam_prefs, choice.get(), (dialog, which) -> choice.set(which));
1775                    builder.setNegativeButton(R.string.cancel, null);
1776                    builder.setPositiveButton(
1777                            R.string.ok,
1778                            (dialog, which) -> {
1779                                prefs.setAttribute("default", defaults.get(choice.get()));
1780                                xmppConnectionService.pushMamPreferences(mAccount, prefs);
1781                            });
1782                    if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) {
1783                        builder.create().show();
1784                    }
1785                });
1786    }
1787
1788    @Override
1789    public void onPreferencesFetchFailed() {
1790        runOnUiThread(
1791                () -> {
1792                    if (mFetchingMamPrefsToast != null) {
1793                        mFetchingMamPrefsToast.cancel();
1794                    }
1795                    Toast.makeText(
1796                                    EditAccountActivity.this,
1797                                    R.string.unable_to_fetch_mam_prefs,
1798                                    Toast.LENGTH_LONG)
1799                            .show();
1800                });
1801    }
1802
1803    @Override
1804    public void OnUpdateBlocklist(Status status) {
1805        refreshUi();
1806    }
1807
1808    @Override
1809    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
1810        if (grantResults.length > 0) {
1811            if (allGranted(grantResults)) {
1812                switch (requestCode) {
1813                    case REQUEST_IMPORT_BACKUP:
1814                        startActivity(new Intent(this, ImportBackupActivity.class));
1815                        break;
1816                }
1817            } else {
1818                Toast.makeText(this, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
1819            }
1820        }
1821        if (writeGranted(grantResults, permissions)) {
1822            if (xmppConnectionService != null) {
1823                xmppConnectionService.restartFileObserver();
1824            }
1825        }
1826    }
1827}