EditAccountActivity.java

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