EditAccountActivity.java

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