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