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		if (getIntent() != null) {
 591			try {
 592				this.jidToEdit = Jid.fromString(getIntent().getStringExtra("jid"));
 593			} catch (final InvalidJidException | NullPointerException ignored) {
 594				this.jidToEdit = null;
 595			}
 596			boolean init = getIntent().getBooleanExtra("init", false);
 597			this.mInitMode = init || this.jidToEdit == null;
 598			this.messageFingerprint = getIntent().getStringExtra("fingerprint");
 599			if (!mInitMode) {
 600				this.mRegisterNew.setVisibility(View.GONE);
 601				if (getActionBar() != null) {
 602					getActionBar().setTitle(getString(R.string.account_details));
 603				}
 604			} else {
 605				this.mAvatar.setVisibility(View.GONE);
 606				ActionBar ab = getActionBar();
 607				if (ab != null) {
 608					if (init && Config.MAGIC_CREATE_DOMAIN == null) {
 609						ab.setDisplayShowHomeEnabled(false);
 610						ab.setDisplayHomeAsUpEnabled(false);
 611					}
 612					ab.setTitle(R.string.action_add_account);
 613				}
 614			}
 615		}
 616		SharedPreferences preferences = getPreferences();
 617		boolean useTor = Config.FORCE_ORBOT || preferences.getBoolean("use_tor", false);
 618		this.mShowOptions = useTor || preferences.getBoolean("show_connection_options", false);
 619		mHostname.setHint(useTor ? R.string.hostname_or_onion : R.string.hostname_example);
 620		this.mNamePort.setVisibility(mShowOptions ? View.VISIBLE : View.GONE);
 621	}
 622
 623	@Override
 624	public void onSaveInstanceState(final Bundle savedInstanceState) {
 625		if (mAccount != null) {
 626			savedInstanceState.putString("account", mAccount.getJid().toBareJid().toString());
 627			savedInstanceState.putBoolean("initMode", mInitMode);
 628		}
 629		super.onSaveInstanceState(savedInstanceState);
 630	}
 631
 632	@Override
 633	protected void onBackendConnected() {
 634		boolean init = true;
 635		if (mSavedInstanceAccount != null) {
 636			try {
 637				this.mAccount = xmppConnectionService.findAccountByJid(Jid.fromString(mSavedInstanceAccount));
 638				this.mInitMode = mSavedInstanceInit;
 639				init = false;
 640			} catch (InvalidJidException e) {
 641				this.mAccount = null;
 642			}
 643
 644		} else if (this.jidToEdit != null) {
 645			this.mAccount = xmppConnectionService.findAccountByJid(jidToEdit);
 646		}
 647
 648		if (mAccount != null) {
 649			this.mInitMode |= this.mAccount.isOptionSet(Account.OPTION_REGISTER);
 650			this.mUsernameMode |= mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE) && mAccount.isOptionSet(Account.OPTION_REGISTER);
 651			if (this.mAccount.getPrivateKeyAlias() != null) {
 652				this.mPassword.setHint(R.string.authenticate_with_certificate);
 653				if (this.mInitMode) {
 654					this.mPassword.requestFocus();
 655				}
 656			}
 657			updateAccountInformation(init);
 658		}
 659
 660
 661		if (Config.MAGIC_CREATE_DOMAIN == null && this.xmppConnectionService.getAccounts().size() == 0) {
 662			this.mCancelButton.setEnabled(false);
 663			this.mCancelButton.setTextColor(getSecondaryTextColor());
 664		}
 665		if (mUsernameMode) {
 666			this.mAccountJidLabel.setText(R.string.username);
 667			this.mAccountJid.setHint(R.string.username_hint);
 668		} else {
 669			final KnownHostsAdapter mKnownHostsAdapter = new KnownHostsAdapter(this,
 670					R.layout.simple_list_item,
 671					xmppConnectionService.getKnownHosts());
 672			this.mAccountJid.setAdapter(mKnownHostsAdapter);
 673		}
 674		updateSaveButton();
 675		invalidateOptionsMenu();
 676	}
 677
 678	private String getUserModeDomain() {
 679		if (mAccount != null) {
 680			return mAccount.getJid().getDomainpart();
 681		} else {
 682			return Config.DOMAIN_LOCK;
 683		}
 684	}
 685
 686	@Override
 687	public boolean onOptionsItemSelected(final MenuItem item) {
 688		switch (item.getItemId()) {
 689			case R.id.action_show_block_list:
 690				final Intent showBlocklistIntent = new Intent(this, BlocklistActivity.class);
 691				showBlocklistIntent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toString());
 692				startActivity(showBlocklistIntent);
 693				break;
 694			case R.id.action_server_info_show_more:
 695				mMoreTable.setVisibility(item.isChecked() ? View.GONE : View.VISIBLE);
 696				item.setChecked(!item.isChecked());
 697				break;
 698			case R.id.action_change_password_on_server:
 699				gotoChangePassword(null);
 700				break;
 701			case R.id.action_mam_prefs:
 702				editMamPrefs();
 703				break;
 704			case R.id.action_clear_devices:
 705				showWipePepDialog();
 706				break;
 707			case R.id.action_renew_certificate:
 708				renewCertificate();
 709				break;
 710			case R.id.action_change_presence:
 711				changePresence();
 712				break;
 713			case R.id.action_show_password:
 714				showPassword();
 715				break;
 716		}
 717		return super.onOptionsItemSelected(item);
 718	}
 719
 720	private void gotoChangePassword(String newPassword) {
 721		final Intent changePasswordIntent = new Intent(this, ChangePasswordActivity.class);
 722		changePasswordIntent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toString());
 723		if (newPassword != null) {
 724			changePasswordIntent.putExtra("password", newPassword);
 725		}
 726		startActivity(changePasswordIntent);
 727	}
 728
 729	private void renewCertificate() {
 730		KeyChain.choosePrivateKeyAlias(this, this, null, null, null, -1, null);
 731	}
 732
 733	private void changePresence() {
 734		Intent intent = new Intent(this, SetPresenceActivity.class);
 735		intent.putExtra(SetPresenceActivity.EXTRA_ACCOUNT,mAccount.getJid().toBareJid().toString());
 736		startActivity(intent);
 737	}
 738
 739	@Override
 740	public void alias(String alias) {
 741		if (alias != null) {
 742			xmppConnectionService.updateKeyInAccount(mAccount, alias);
 743		}
 744	}
 745
 746	private void updateAccountInformation(boolean init) {
 747		if (init) {
 748			this.mAccountJid.getEditableText().clear();
 749			if (mUsernameMode) {
 750				this.mAccountJid.getEditableText().append(this.mAccount.getJid().getLocalpart());
 751			} else {
 752				this.mAccountJid.getEditableText().append(this.mAccount.getJid().toBareJid().toString());
 753			}
 754			this.mPassword.setText(this.mAccount.getPassword());
 755			this.mHostname.setText("");
 756			this.mHostname.getEditableText().append(this.mAccount.getHostname());
 757			this.mPort.setText("");
 758			this.mPort.getEditableText().append(String.valueOf(this.mAccount.getPort()));
 759			this.mNamePort.setVisibility(mShowOptions ? View.VISIBLE : View.GONE);
 760
 761		}
 762
 763		if (!mInitMode) {
 764			this.mAvatar.setVisibility(View.VISIBLE);
 765			this.mAvatar.setImageBitmap(avatarService().get(this.mAccount, getPixel(72)));
 766		} else {
 767			this.mAvatar.setVisibility(View.GONE);
 768		}
 769		if (this.mAccount.isOptionSet(Account.OPTION_REGISTER)) {
 770			this.mRegisterNew.setVisibility(View.VISIBLE);
 771			this.mRegisterNew.setChecked(true);
 772			this.mPasswordConfirm.setText(this.mAccount.getPassword());
 773		} else {
 774			this.mRegisterNew.setVisibility(View.GONE);
 775			this.mRegisterNew.setChecked(false);
 776		}
 777		if (this.mAccount.isOnlineAndConnected() && !this.mFetchingAvatar) {
 778			Features features = this.mAccount.getXmppConnection().getFeatures();
 779			this.mStats.setVisibility(View.VISIBLE);
 780			boolean showOptimizingWarning = !xmppConnectionService.getPushManagementService().available(mAccount) && isOptimizingBattery();
 781			this.mBatteryOptimizations.setVisibility(showOptimizingWarning ? View.VISIBLE : View.GONE);
 782			this.mSessionEst.setText(UIHelper.readableTimeDifferenceFull(this, this.mAccount.getXmppConnection()
 783					.getLastSessionEstablished()));
 784			if (features.rosterVersioning()) {
 785				this.mServerInfoRosterVersion.setText(R.string.server_info_available);
 786			} else {
 787				this.mServerInfoRosterVersion.setText(R.string.server_info_unavailable);
 788			}
 789			if (features.carbons()) {
 790				this.mServerInfoCarbons.setText(R.string.server_info_available);
 791			} else {
 792				this.mServerInfoCarbons
 793						.setText(R.string.server_info_unavailable);
 794			}
 795			if (features.mam()) {
 796				this.mServerInfoMam.setText(R.string.server_info_available);
 797			} else {
 798				this.mServerInfoMam.setText(R.string.server_info_unavailable);
 799			}
 800			if (features.csi()) {
 801				this.mServerInfoCSI.setText(R.string.server_info_available);
 802			} else {
 803				this.mServerInfoCSI.setText(R.string.server_info_unavailable);
 804			}
 805			if (features.blocking()) {
 806				this.mServerInfoBlocking.setText(R.string.server_info_available);
 807			} else {
 808				this.mServerInfoBlocking.setText(R.string.server_info_unavailable);
 809			}
 810			if (features.sm()) {
 811				this.mServerInfoSm.setText(R.string.server_info_available);
 812			} else {
 813				this.mServerInfoSm.setText(R.string.server_info_unavailable);
 814			}
 815			if (features.pep()) {
 816				AxolotlService axolotlService = this.mAccount.getAxolotlService();
 817				if (axolotlService != null && axolotlService.isPepBroken()) {
 818					this.mServerInfoPep.setText(R.string.server_info_broken);
 819				} else {
 820					this.mServerInfoPep.setText(R.string.server_info_available);
 821				}
 822			} else {
 823				this.mServerInfoPep.setText(R.string.server_info_unavailable);
 824			}
 825			if (features.httpUpload(0)) {
 826				this.mServerInfoHttpUpload.setText(R.string.server_info_available);
 827			} else {
 828				this.mServerInfoHttpUpload.setText(R.string.server_info_unavailable);
 829			}
 830
 831			this.mPushRow.setVisibility(xmppConnectionService.getPushManagementService().isStub() ? View.GONE : View.VISIBLE);
 832
 833			if (xmppConnectionService.getPushManagementService().available(mAccount)) {
 834				this.mServerInfoPush.setText(R.string.server_info_available);
 835			} else {
 836				this.mServerInfoPush.setText(R.string.server_info_unavailable);
 837			}
 838			final String otrFingerprint = this.mAccount.getOtrFingerprint();
 839			if (otrFingerprint != null && Config.supportOtr()) {
 840				this.mOtrFingerprintBox.setVisibility(View.VISIBLE);
 841				this.mOtrFingerprint.setText(CryptoHelper.prettifyFingerprint(otrFingerprint));
 842				this.mOtrFingerprintToClipboardButton
 843						.setVisibility(View.VISIBLE);
 844				this.mOtrFingerprintToClipboardButton
 845						.setOnClickListener(new View.OnClickListener() {
 846
 847							@Override
 848							public void onClick(final View v) {
 849
 850								if (copyTextToClipboard(otrFingerprint, R.string.otr_fingerprint)) {
 851									Toast.makeText(
 852											EditAccountActivity.this,
 853											R.string.toast_message_otr_fingerprint,
 854											Toast.LENGTH_SHORT).show();
 855								}
 856							}
 857						});
 858			} else {
 859				this.mOtrFingerprintBox.setVisibility(View.GONE);
 860			}
 861			final String ownAxolotlFingerprint = this.mAccount.getAxolotlService().getOwnFingerprint();
 862			if (ownAxolotlFingerprint != null && Config.supportOmemo()) {
 863				this.mAxolotlFingerprintBox.setVisibility(View.VISIBLE);
 864				if (ownAxolotlFingerprint.equals(messageFingerprint)) {
 865					this.mOwnFingerprintDesc.setTextColor(getResources().getColor(R.color.accent));
 866				} else {
 867					this.mOwnFingerprintDesc.setTextColor(getSecondaryTextColor());
 868				}
 869				this.mAxolotlFingerprint.setText(CryptoHelper.prettifyFingerprint(ownAxolotlFingerprint.substring(2)));
 870				this.mAxolotlFingerprintToClipboardButton
 871						.setVisibility(View.VISIBLE);
 872				this.mAxolotlFingerprintToClipboardButton
 873						.setOnClickListener(new View.OnClickListener() {
 874
 875							@Override
 876							public void onClick(final View v) {
 877
 878								if (copyTextToClipboard(ownAxolotlFingerprint.substring(2), R.string.omemo_fingerprint)) {
 879									Toast.makeText(
 880											EditAccountActivity.this,
 881											R.string.toast_message_omemo_fingerprint,
 882											Toast.LENGTH_SHORT).show();
 883								}
 884							}
 885						});
 886				if (Config.SHOW_REGENERATE_AXOLOTL_KEYS_BUTTON) {
 887					this.mRegenerateAxolotlKeyButton
 888							.setVisibility(View.VISIBLE);
 889					this.mRegenerateAxolotlKeyButton
 890							.setOnClickListener(new View.OnClickListener() {
 891
 892								@Override
 893								public void onClick(final View v) {
 894									showRegenerateAxolotlKeyDialog();
 895								}
 896							});
 897				}
 898			} else {
 899				this.mAxolotlFingerprintBox.setVisibility(View.GONE);
 900			}
 901			boolean hasKeys = false;
 902			keys.removeAllViews();
 903			for (final String fingerprint : mAccount.getAxolotlService().getFingerprintsForOwnSessions()) {
 904				if (ownAxolotlFingerprint.equals(fingerprint)) {
 905					continue;
 906				}
 907				boolean highlight = fingerprint.equals(messageFingerprint);
 908				hasKeys |= addFingerprintRow(keys, mAccount, fingerprint, highlight, null);
 909			}
 910			if (hasKeys && Config.supportOmemo()) {
 911				keysCard.setVisibility(View.VISIBLE);
 912			} else {
 913				keysCard.setVisibility(View.GONE);
 914			}
 915		} else {
 916			if (this.mAccount.errorStatus()) {
 917				final EditText errorTextField;
 918				if (this.mAccount.getStatus() == Account.State.UNAUTHORIZED) {
 919					errorTextField = this.mPassword;
 920				} else if (mShowOptions
 921						&& this.mAccount.getStatus() == Account.State.SERVER_NOT_FOUND
 922						&& this.mHostname.getText().length() > 0) {
 923					errorTextField = this.mHostname;
 924				} else {
 925					errorTextField = this.mAccountJid;
 926				}
 927				errorTextField.setError(getString(this.mAccount.getStatus().getReadableId()));
 928				if (init || !accountInfoEdited()) {
 929					errorTextField.requestFocus();
 930				}
 931			} else {
 932				this.mAccountJid.setError(null);
 933				this.mPassword.setError(null);
 934				this.mHostname.setError(null);
 935			}
 936			this.mStats.setVisibility(View.GONE);
 937		}
 938	}
 939
 940	public void showRegenerateAxolotlKeyDialog() {
 941		Builder builder = new Builder(this);
 942		builder.setTitle("Regenerate Key");
 943		builder.setIconAttribute(android.R.attr.alertDialogIcon);
 944		builder.setMessage("Are you sure you want to regenerate your Identity Key? (This will also wipe all established sessions and contact Identity Keys)");
 945		builder.setNegativeButton(getString(R.string.cancel), null);
 946		builder.setPositiveButton("Yes",
 947				new DialogInterface.OnClickListener() {
 948					@Override
 949					public void onClick(DialogInterface dialog, int which) {
 950						mAccount.getAxolotlService().regenerateKeys(false);
 951					}
 952				});
 953		builder.create().show();
 954	}
 955
 956	public void showWipePepDialog() {
 957		Builder builder = new Builder(this);
 958		builder.setTitle(getString(R.string.clear_other_devices));
 959		builder.setIconAttribute(android.R.attr.alertDialogIcon);
 960		builder.setMessage(getString(R.string.clear_other_devices_desc));
 961		builder.setNegativeButton(getString(R.string.cancel), null);
 962		builder.setPositiveButton(getString(R.string.accept),
 963				new DialogInterface.OnClickListener() {
 964					@Override
 965					public void onClick(DialogInterface dialog, int which) {
 966						mAccount.getAxolotlService().wipeOtherPepDevices();
 967					}
 968				});
 969		builder.create().show();
 970	}
 971
 972	private void editMamPrefs() {
 973		this.mFetchingMamPrefsToast = Toast.makeText(this, R.string.fetching_mam_prefs, Toast.LENGTH_LONG);
 974		this.mFetchingMamPrefsToast.show();
 975		xmppConnectionService.fetchMamPreferences(mAccount, this);
 976	}
 977
 978	private void showPassword() {
 979		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 980		View view = getLayoutInflater().inflate(R.layout.dialog_show_password, null);
 981		TextView password = (TextView) view.findViewById(R.id.password);
 982		password.setText(mAccount.getPassword());
 983		builder.setTitle(R.string.password);
 984		builder.setView(view);
 985		builder.setPositiveButton(R.string.cancel, null);
 986		builder.create().show();
 987	}
 988
 989	@Override
 990	public void onKeyStatusUpdated(AxolotlService.FetchStatus report) {
 991		refreshUi();
 992	}
 993
 994	@Override
 995	public void onCaptchaRequested(final Account account, final String id, final Data data, final Bitmap captcha) {
 996		runOnUiThread(new Runnable() {
 997			@Override
 998			public void run() {
 999				if ((mCaptchaDialog != null) && mCaptchaDialog.isShowing()) {
1000					mCaptchaDialog.dismiss();
1001				}
1002				final AlertDialog.Builder builder = new AlertDialog.Builder(EditAccountActivity.this);
1003				final View view = getLayoutInflater().inflate(R.layout.captcha, null);
1004				final ImageView imageView = (ImageView) view.findViewById(R.id.captcha);
1005				final EditText input = (EditText) view.findViewById(R.id.input);
1006				imageView.setImageBitmap(captcha);
1007
1008				builder.setTitle(getString(R.string.captcha_required));
1009				builder.setView(view);
1010
1011				builder.setPositiveButton(getString(R.string.ok),
1012						new DialogInterface.OnClickListener() {
1013							@Override
1014							public void onClick(DialogInterface dialog, int which) {
1015								String rc = input.getText().toString();
1016								data.put("username", account.getUsername());
1017								data.put("password", account.getPassword());
1018								data.put("ocr", rc);
1019								data.submit();
1020
1021								if (xmppConnectionServiceBound) {
1022									xmppConnectionService.sendCreateAccountWithCaptchaPacket(
1023											account, id, data);
1024								}
1025							}
1026						});
1027				builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
1028					@Override
1029					public void onClick(DialogInterface dialog, int which) {
1030						if (xmppConnectionService != null) {
1031							xmppConnectionService.sendCreateAccountWithCaptchaPacket(account, null, null);
1032						}
1033					}
1034				});
1035
1036				builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
1037					@Override
1038					public void onCancel(DialogInterface dialog) {
1039						if (xmppConnectionService != null) {
1040							xmppConnectionService.sendCreateAccountWithCaptchaPacket(account, null, null);
1041						}
1042					}
1043				});
1044				mCaptchaDialog = builder.create();
1045				mCaptchaDialog.show();
1046			}
1047		});
1048	}
1049
1050	public void onShowErrorToast(final int resId) {
1051		runOnUiThread(new Runnable() {
1052			@Override
1053			public void run() {
1054				Toast.makeText(EditAccountActivity.this, resId, Toast.LENGTH_SHORT).show();
1055			}
1056		});
1057	}
1058
1059	@Override
1060	public void onPreferencesFetched(final Element prefs) {
1061		runOnUiThread(new Runnable() {
1062			@Override
1063			public void run() {
1064				if (mFetchingMamPrefsToast != null) {
1065					mFetchingMamPrefsToast.cancel();
1066				}
1067				AlertDialog.Builder builder = new Builder(EditAccountActivity.this);
1068				builder.setTitle(R.string.server_side_mam_prefs);
1069				String defaultAttr = prefs.getAttribute("default");
1070				final List<String> defaults = Arrays.asList("never", "roster", "always");
1071				final AtomicInteger choice = new AtomicInteger(Math.max(0,defaults.indexOf(defaultAttr)));
1072				builder.setSingleChoiceItems(R.array.mam_prefs, choice.get(), new DialogInterface.OnClickListener() {
1073					@Override
1074					public void onClick(DialogInterface dialog, int which) {
1075						choice.set(which);
1076					}
1077				});
1078				builder.setNegativeButton(R.string.cancel, null);
1079				builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
1080					@Override
1081					public void onClick(DialogInterface dialog, int which) {
1082						prefs.setAttribute("default",defaults.get(choice.get()));
1083						xmppConnectionService.pushMamPreferences(mAccount, prefs);
1084					}
1085				});
1086				builder.create().show();
1087			}
1088		});
1089	}
1090
1091	@Override
1092	public void onPreferencesFetchFailed() {
1093		runOnUiThread(new Runnable() {
1094			@Override
1095			public void run() {
1096				if (mFetchingMamPrefsToast != null) {
1097					mFetchingMamPrefsToast.cancel();
1098				}
1099				Toast.makeText(EditAccountActivity.this,R.string.unable_to_fetch_mam_prefs,Toast.LENGTH_LONG).show();
1100			}
1101		});
1102	}
1103}