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