EditAccountActivity.java

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