EditAccountActivity.java

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