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.Features;
 54import eu.siacs.conversations.xmpp.forms.Data;
 55import eu.siacs.conversations.xmpp.jid.InvalidJidException;
 56import eu.siacs.conversations.xmpp.jid.Jid;
 57import eu.siacs.conversations.xmpp.pep.Avatar;
 58
 59public class EditAccountActivity extends XmppActivity implements OnAccountUpdate,
 60		OnKeyStatusUpdated, OnCaptchaRequested, KeyChainAliasCallback, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnMamPreferencesFetched {
 61
 62	private AutoCompleteTextView mAccountJid;
 63	private EditText mPassword;
 64	private EditText mPasswordConfirm;
 65	private CheckBox mRegisterNew;
 66	private Button mCancelButton;
 67	private Button mSaveButton;
 68	private Button mDisableBatterOptimizations;
 69	private TableLayout mMoreTable;
 70
 71	private LinearLayout mStats;
 72	private RelativeLayout mBatteryOptimizations;
 73	private TextView mServerInfoSm;
 74	private TextView mServerInfoRosterVersion;
 75	private TextView mServerInfoCarbons;
 76	private TextView mServerInfoMam;
 77	private TextView mServerInfoCSI;
 78	private TextView mServerInfoBlocking;
 79	private TextView mServerInfoPep;
 80	private TextView mServerInfoHttpUpload;
 81	private TextView mServerInfoPush;
 82	private TextView mSessionEst;
 83	private TextView mOtrFingerprint;
 84	private TextView mAxolotlFingerprint;
 85	private TextView mAccountJidLabel;
 86	private ImageView mAvatar;
 87	private RelativeLayout mOtrFingerprintBox;
 88	private RelativeLayout mAxolotlFingerprintBox;
 89	private ImageButton mOtrFingerprintToClipboardButton;
 90	private ImageButton mAxolotlFingerprintToClipboardButton;
 91	private ImageButton mRegenerateAxolotlKeyButton;
 92	private LinearLayout keys;
 93	private LinearLayout keysCard;
 94	private LinearLayout mNamePort;
 95	private EditText mHostname;
 96	private EditText mPort;
 97	private AlertDialog mCaptchaDialog = null;
 98
 99	private Jid jidToEdit;
100	private boolean mInitMode = false;
101	private boolean mShowOptions = false;
102	private Account mAccount;
103	private String messageFingerprint;
104
105	private boolean mFetchingAvatar = false;
106
107	private final OnClickListener mSaveButtonClickListener = new OnClickListener() {
108
109		@Override
110		public void onClick(final View v) {
111			if (mInitMode && mAccount != null) {
112				mAccount.setOption(Account.OPTION_DISABLED, false);
113			}
114			if (mAccount != null && mAccount.getStatus() == Account.State.DISABLED && !accountInfoEdited()) {
115				mAccount.setOption(Account.OPTION_DISABLED, false);
116				xmppConnectionService.updateAccount(mAccount);
117				return;
118			}
119			final boolean registerNewAccount = mRegisterNew.isChecked() && !Config.DISALLOW_REGISTRATION_IN_UI;
120			if (Config.DOMAIN_LOCK != null && mAccountJid.getText().toString().contains("@")) {
121				mAccountJid.setError(getString(R.string.invalid_username));
122				mAccountJid.requestFocus();
123				return;
124			}
125			final Jid jid;
126			try {
127				if (Config.DOMAIN_LOCK != null) {
128					jid = Jid.fromParts(mAccountJid.getText().toString(), Config.DOMAIN_LOCK, null);
129				} else {
130					jid = Jid.fromString(mAccountJid.getText().toString());
131				}
132			} catch (final InvalidJidException e) {
133				if (Config.DOMAIN_LOCK != null) {
134					mAccountJid.setError(getString(R.string.invalid_username));
135				} else {
136					mAccountJid.setError(getString(R.string.invalid_jid));
137				}
138				mAccountJid.requestFocus();
139				return;
140			}
141			String hostname = null;
142			int numericPort = 5222;
143			if (mShowOptions) {
144				hostname = mHostname.getText().toString();
145				final String port = mPort.getText().toString();
146				if (hostname.contains(" ")) {
147					mHostname.setError(getString(R.string.not_valid_hostname));
148					mHostname.requestFocus();
149					return;
150				}
151				try {
152					numericPort = Integer.parseInt(port);
153					if (numericPort < 0 || numericPort > 65535) {
154						mPort.setError(getString(R.string.not_a_valid_port));
155						mPort.requestFocus();
156						return;
157					}
158
159				} catch (NumberFormatException e) {
160					mPort.setError(getString(R.string.not_a_valid_port));
161					mPort.requestFocus();
162					return;
163				}
164			}
165
166			if (jid.isDomainJid()) {
167				if (Config.DOMAIN_LOCK != null) {
168					mAccountJid.setError(getString(R.string.invalid_username));
169				} else {
170					mAccountJid.setError(getString(R.string.invalid_jid));
171				}
172				mAccountJid.requestFocus();
173				return;
174			}
175			final String password = mPassword.getText().toString();
176			final String passwordConfirm = mPasswordConfirm.getText().toString();
177			if (registerNewAccount) {
178				if (!password.equals(passwordConfirm)) {
179					mPasswordConfirm.setError(getString(R.string.passwords_do_not_match));
180					mPasswordConfirm.requestFocus();
181					return;
182				}
183			}
184			if (mAccount != null) {
185				mAccount.setJid(jid);
186				mAccount.setPort(numericPort);
187				mAccount.setHostname(hostname);
188				mAccountJid.setError(null);
189				mPasswordConfirm.setError(null);
190				mAccount.setPassword(password);
191				mAccount.setOption(Account.OPTION_REGISTER, registerNewAccount);
192				xmppConnectionService.updateAccount(mAccount);
193			} else {
194				if (xmppConnectionService.findAccountByJid(jid) != null) {
195					mAccountJid.setError(getString(R.string.account_already_exists));
196					mAccountJid.requestFocus();
197					return;
198				}
199				mAccount = new Account(jid.toBareJid(), password);
200				mAccount.setPort(numericPort);
201				mAccount.setHostname(hostname);
202				mAccount.setOption(Account.OPTION_USETLS, true);
203				mAccount.setOption(Account.OPTION_USECOMPRESSION, true);
204				mAccount.setOption(Account.OPTION_REGISTER, registerNewAccount);
205				xmppConnectionService.createAccount(mAccount);
206			}
207			mHostname.setError(null);
208			mPort.setError(null);
209			if (!mAccount.isOptionSet(Account.OPTION_DISABLED)
210					&& !registerNewAccount
211					&& !mInitMode) {
212				finish();
213			} else {
214				updateSaveButton();
215				updateAccountInformation(true);
216			}
217
218		}
219	};
220	private final OnClickListener mCancelButtonClickListener = new OnClickListener() {
221
222		@Override
223		public void onClick(final View v) {
224			finish();
225		}
226	};
227	private Toast mFetchingMamPrefsToast;
228	private TableRow mPushRow;
229
230	public void refreshUiReal() {
231		invalidateOptionsMenu();
232		if (mAccount != null
233				&& mAccount.getStatus() != Account.State.ONLINE
234				&& mFetchingAvatar) {
235			startActivity(new Intent(getApplicationContext(),
236					ManageAccountActivity.class));
237			finish();
238		} else if (mInitMode && mAccount != null && mAccount.getStatus() == Account.State.ONLINE) {
239			if (!mFetchingAvatar) {
240				mFetchingAvatar = true;
241				xmppConnectionService.checkForAvatar(mAccount, mAvatarFetchCallback);
242			}
243		} else {
244			updateSaveButton();
245		}
246		if (mAccount != null) {
247			updateAccountInformation(false);
248		}
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				if (avatar != null) {
308					intent = new Intent(getApplicationContext(),
309							StartConversationActivity.class);
310					if (xmppConnectionService != null && xmppConnectionService.getAccounts().size() == 1) {
311						intent.putExtra("init", true);
312					}
313				} else {
314					intent = new Intent(getApplicationContext(),
315							PublishProfilePictureActivity.class);
316					intent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toBareJid().toString());
317					intent.putExtra("setup", true);
318				}
319				startActivity(intent);
320				finish();
321			}
322		});
323	}
324
325	@Override
326	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
327		super.onActivityResult(requestCode, resultCode, data);
328		if (requestCode == REQUEST_BATTERY_OP) {
329			updateAccountInformation(mAccount == null);
330		}
331	}
332
333	protected void updateSaveButton() {
334		if (accountInfoEdited() && !mInitMode) {
335			this.mSaveButton.setText(R.string.save);
336			this.mSaveButton.setEnabled(true);
337			this.mSaveButton.setTextColor(getPrimaryTextColor());
338		} else if (mAccount != null && (mAccount.getStatus() == Account.State.CONNECTING || 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
480		renewCertificate.setVisible(mAccount != null && mAccount.getPrivateKeyAlias() != null);
481
482		if (mAccount != null && mAccount.isOnlineAndConnected()) {
483			if (!mAccount.getXmppConnection().getFeatures().blocking()) {
484				showBlocklist.setVisible(false);
485			}
486			if (!mAccount.getXmppConnection().getFeatures().register()) {
487				changePassword.setVisible(false);
488			}
489			mamPrefs.setVisible(mAccount.getXmppConnection().getFeatures().mam());
490			Set<Integer> otherDevices = mAccount.getAxolotlService().getOwnDeviceIds();
491			if (otherDevices == null || otherDevices.isEmpty()) {
492				clearDevices.setVisible(false);
493			}
494		} else {
495			showQrCode.setVisible(false);
496			showBlocklist.setVisible(false);
497			showMoreInfo.setVisible(false);
498			changePassword.setVisible(false);
499			clearDevices.setVisible(false);
500			mamPrefs.setVisible(false);
501		}
502		return true;
503	}
504
505	@Override
506	protected void onStart() {
507		super.onStart();
508		if (getIntent() != null) {
509			try {
510				this.jidToEdit = Jid.fromString(getIntent().getStringExtra("jid"));
511			} catch (final InvalidJidException | NullPointerException ignored) {
512				this.jidToEdit = null;
513			}
514			this.mInitMode = getIntent().getBooleanExtra("init", false) || this.jidToEdit == null;
515			this.messageFingerprint = getIntent().getStringExtra("fingerprint");
516			if (!mInitMode) {
517				this.mRegisterNew.setVisibility(View.GONE);
518				if (getActionBar() != null) {
519					getActionBar().setTitle(getString(R.string.account_details));
520				}
521			} else {
522				this.mAvatar.setVisibility(View.GONE);
523				if (getActionBar() != null) {
524					getActionBar().setTitle(R.string.action_add_account);
525				}
526			}
527		}
528		SharedPreferences preferences = getPreferences();
529		boolean useTor = Config.FORCE_ORBOT || preferences.getBoolean("use_tor", false);
530		this.mShowOptions = useTor || preferences.getBoolean("show_connection_options", false);
531		mHostname.setHint(useTor ? R.string.hostname_or_onion : R.string.hostname_example);
532		this.mNamePort.setVisibility(mShowOptions ? View.VISIBLE : View.GONE);
533	}
534
535	@Override
536	protected void onBackendConnected() {
537		if (this.jidToEdit != null) {
538			this.mAccount = xmppConnectionService.findAccountByJid(jidToEdit);
539			if (this.mAccount != null) {
540				if (this.mAccount.getPrivateKeyAlias() != null) {
541					this.mPassword.setHint(R.string.authenticate_with_certificate);
542					if (this.mInitMode) {
543						this.mPassword.requestFocus();
544					}
545				}
546				updateAccountInformation(true);
547			}
548		} else if (this.xmppConnectionService.getAccounts().size() == 0) {
549			if (getActionBar() != null) {
550				getActionBar().setDisplayHomeAsUpEnabled(false);
551				getActionBar().setDisplayShowHomeEnabled(false);
552				getActionBar().setHomeButtonEnabled(false);
553			}
554			this.mCancelButton.setEnabled(false);
555			this.mCancelButton.setTextColor(getSecondaryTextColor());
556		}
557		if (Config.DOMAIN_LOCK == null) {
558			final KnownHostsAdapter mKnownHostsAdapter = new KnownHostsAdapter(this,
559					android.R.layout.simple_list_item_1,
560					xmppConnectionService.getKnownHosts());
561			this.mAccountJid.setAdapter(mKnownHostsAdapter);
562		}
563		updateSaveButton();
564		invalidateOptionsMenu();
565	}
566
567	@Override
568	public boolean onOptionsItemSelected(final MenuItem item) {
569		switch (item.getItemId()) {
570			case R.id.action_show_block_list:
571				final Intent showBlocklistIntent = new Intent(this, BlocklistActivity.class);
572				showBlocklistIntent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toString());
573				startActivity(showBlocklistIntent);
574				break;
575			case R.id.action_server_info_show_more:
576				mMoreTable.setVisibility(item.isChecked() ? View.GONE : View.VISIBLE);
577				item.setChecked(!item.isChecked());
578				break;
579			case R.id.action_change_password_on_server:
580				final Intent changePasswordIntent = new Intent(this, ChangePasswordActivity.class);
581				changePasswordIntent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toString());
582				startActivity(changePasswordIntent);
583				break;
584			case R.id.action_mam_prefs:
585				editMamPrefs();
586				break;
587			case R.id.action_clear_devices:
588				showWipePepDialog();
589				break;
590			case R.id.action_renew_certificate:
591				renewCertificate();
592				break;
593		}
594		return super.onOptionsItemSelected(item);
595	}
596
597	private void renewCertificate() {
598		KeyChain.choosePrivateKeyAlias(this, this, null, null, null, -1, null);
599	}
600
601	@Override
602	public void alias(String alias) {
603		if (alias != null) {
604			xmppConnectionService.updateKeyInAccount(mAccount, alias);
605		}
606	}
607
608	private void updateAccountInformation(boolean init) {
609		if (init) {
610			this.mAccountJid.getEditableText().clear();
611			if (Config.DOMAIN_LOCK != null) {
612				this.mAccountJid.getEditableText().append(this.mAccount.getJid().getLocalpart());
613			} else {
614				this.mAccountJid.getEditableText().append(this.mAccount.getJid().toBareJid().toString());
615			}
616			this.mPassword.setText(this.mAccount.getPassword());
617			this.mHostname.setText("");
618			this.mHostname.getEditableText().append(this.mAccount.getHostname());
619			this.mPort.setText("");
620			this.mPort.getEditableText().append(String.valueOf(this.mAccount.getPort()));
621			this.mNamePort.setVisibility(mShowOptions ? View.VISIBLE : View.GONE);
622
623		}
624		if (!mInitMode) {
625			this.mAvatar.setVisibility(View.VISIBLE);
626			this.mAvatar.setImageBitmap(avatarService().get(this.mAccount, getPixel(72)));
627		}
628		if (this.mAccount.isOptionSet(Account.OPTION_REGISTER)) {
629			this.mRegisterNew.setVisibility(View.VISIBLE);
630			this.mRegisterNew.setChecked(true);
631			this.mPasswordConfirm.setText(this.mAccount.getPassword());
632		} else {
633			this.mRegisterNew.setVisibility(View.GONE);
634			this.mRegisterNew.setChecked(false);
635		}
636		if (this.mAccount.isOnlineAndConnected() && !this.mFetchingAvatar) {
637			this.mStats.setVisibility(View.VISIBLE);
638			this.mBatteryOptimizations.setVisibility(showBatteryOptimizationWarning() ? View.VISIBLE : View.GONE);
639			this.mSessionEst.setText(UIHelper.readableTimeDifferenceFull(this, this.mAccount.getXmppConnection()
640					.getLastSessionEstablished()));
641			Features features = this.mAccount.getXmppConnection().getFeatures();
642			if (features.rosterVersioning()) {
643				this.mServerInfoRosterVersion.setText(R.string.server_info_available);
644			} else {
645				this.mServerInfoRosterVersion.setText(R.string.server_info_unavailable);
646			}
647			if (features.carbons()) {
648				this.mServerInfoCarbons.setText(R.string.server_info_available);
649			} else {
650				this.mServerInfoCarbons
651						.setText(R.string.server_info_unavailable);
652			}
653			if (features.mam()) {
654				this.mServerInfoMam.setText(R.string.server_info_available);
655			} else {
656				this.mServerInfoMam.setText(R.string.server_info_unavailable);
657			}
658			if (features.csi()) {
659				this.mServerInfoCSI.setText(R.string.server_info_available);
660			} else {
661				this.mServerInfoCSI.setText(R.string.server_info_unavailable);
662			}
663			if (features.blocking()) {
664				this.mServerInfoBlocking.setText(R.string.server_info_available);
665			} else {
666				this.mServerInfoBlocking.setText(R.string.server_info_unavailable);
667			}
668			if (features.sm()) {
669				this.mServerInfoSm.setText(R.string.server_info_available);
670			} else {
671				this.mServerInfoSm.setText(R.string.server_info_unavailable);
672			}
673			if (features.pep()) {
674				AxolotlService axolotlService = this.mAccount.getAxolotlService();
675				if (axolotlService != null && axolotlService.isPepBroken()) {
676					this.mServerInfoPep.setText(R.string.server_info_broken);
677				} else {
678					this.mServerInfoPep.setText(R.string.server_info_available);
679				}
680			} else {
681				this.mServerInfoPep.setText(R.string.server_info_unavailable);
682			}
683			if (features.httpUpload()) {
684				this.mServerInfoHttpUpload.setText(R.string.server_info_available);
685			} else {
686				this.mServerInfoHttpUpload.setText(R.string.server_info_unavailable);
687			}
688
689			this.mPushRow.setVisibility(xmppConnectionService.getPushManagementService().available(mAccount) ? View.VISIBLE : View.GONE);
690
691			if (features.push()) {
692				this.mServerInfoPush.setText(R.string.server_info_available);
693			} else {
694				this.mServerInfoPush.setText(R.string.server_info_unavailable);
695			}
696			final String otrFingerprint = this.mAccount.getOtrFingerprint();
697			if (otrFingerprint != null) {
698				this.mOtrFingerprintBox.setVisibility(View.VISIBLE);
699				this.mOtrFingerprint.setText(CryptoHelper.prettifyFingerprint(otrFingerprint));
700				this.mOtrFingerprintToClipboardButton
701						.setVisibility(View.VISIBLE);
702				this.mOtrFingerprintToClipboardButton
703						.setOnClickListener(new View.OnClickListener() {
704
705							@Override
706							public void onClick(final View v) {
707
708								if (copyTextToClipboard(otrFingerprint, R.string.otr_fingerprint)) {
709									Toast.makeText(
710											EditAccountActivity.this,
711											R.string.toast_message_otr_fingerprint,
712											Toast.LENGTH_SHORT).show();
713								}
714							}
715						});
716			} else {
717				this.mOtrFingerprintBox.setVisibility(View.GONE);
718			}
719			final String axolotlFingerprint = this.mAccount.getAxolotlService().getOwnFingerprint();
720			if (axolotlFingerprint != null) {
721				this.mAxolotlFingerprintBox.setVisibility(View.VISIBLE);
722				this.mAxolotlFingerprint.setText(CryptoHelper.prettifyFingerprint(axolotlFingerprint.substring(2)));
723				this.mAxolotlFingerprintToClipboardButton
724						.setVisibility(View.VISIBLE);
725				this.mAxolotlFingerprintToClipboardButton
726						.setOnClickListener(new View.OnClickListener() {
727
728							@Override
729							public void onClick(final View v) {
730
731								if (copyTextToClipboard(axolotlFingerprint.substring(2), R.string.omemo_fingerprint)) {
732									Toast.makeText(
733											EditAccountActivity.this,
734											R.string.toast_message_omemo_fingerprint,
735											Toast.LENGTH_SHORT).show();
736								}
737							}
738						});
739				if (Config.SHOW_REGENERATE_AXOLOTL_KEYS_BUTTON) {
740					this.mRegenerateAxolotlKeyButton
741							.setVisibility(View.VISIBLE);
742					this.mRegenerateAxolotlKeyButton
743							.setOnClickListener(new View.OnClickListener() {
744
745								@Override
746								public void onClick(final View v) {
747									showRegenerateAxolotlKeyDialog();
748								}
749							});
750				}
751			} else {
752				this.mAxolotlFingerprintBox.setVisibility(View.GONE);
753			}
754			final String ownFingerprint = mAccount.getAxolotlService().getOwnFingerprint();
755			boolean hasKeys = false;
756			keys.removeAllViews();
757			for (final String fingerprint : mAccount.getAxolotlService().getFingerprintsForOwnSessions()) {
758				if (ownFingerprint.equals(fingerprint)) {
759					continue;
760				}
761				boolean highlight = fingerprint.equals(messageFingerprint);
762				hasKeys |= addFingerprintRow(keys, mAccount, fingerprint, highlight, null);
763			}
764			if (hasKeys) {
765				keysCard.setVisibility(View.VISIBLE);
766			} else {
767				keysCard.setVisibility(View.GONE);
768			}
769		} else {
770			if (this.mAccount.errorStatus()) {
771				final EditText errorTextField;
772				if (this.mAccount.getStatus() == Account.State.UNAUTHORIZED) {
773					errorTextField = this.mPassword;
774				} else if (mShowOptions
775						&& this.mAccount.getStatus() == Account.State.SERVER_NOT_FOUND
776						&& this.mHostname.getText().length() > 0) {
777					errorTextField = this.mHostname;
778				} else {
779					errorTextField = this.mAccountJid;
780				}
781				errorTextField.setError(getString(this.mAccount.getStatus().getReadableId()));
782				if (init || !accountInfoEdited()) {
783					errorTextField.requestFocus();
784				}
785			} else {
786				this.mAccountJid.setError(null);
787				this.mPassword.setError(null);
788				this.mHostname.setError(null);
789			}
790			this.mStats.setVisibility(View.GONE);
791		}
792	}
793
794	public void showRegenerateAxolotlKeyDialog() {
795		Builder builder = new Builder(this);
796		builder.setTitle("Regenerate Key");
797		builder.setIconAttribute(android.R.attr.alertDialogIcon);
798		builder.setMessage("Are you sure you want to regenerate your Identity Key? (This will also wipe all established sessions and contact Identity Keys)");
799		builder.setNegativeButton(getString(R.string.cancel), null);
800		builder.setPositiveButton("Yes",
801				new DialogInterface.OnClickListener() {
802					@Override
803					public void onClick(DialogInterface dialog, int which) {
804						mAccount.getAxolotlService().regenerateKeys(false);
805					}
806				});
807		builder.create().show();
808	}
809
810	public void showWipePepDialog() {
811		Builder builder = new Builder(this);
812		builder.setTitle(getString(R.string.clear_other_devices));
813		builder.setIconAttribute(android.R.attr.alertDialogIcon);
814		builder.setMessage(getString(R.string.clear_other_devices_desc));
815		builder.setNegativeButton(getString(R.string.cancel), null);
816		builder.setPositiveButton(getString(R.string.accept),
817				new DialogInterface.OnClickListener() {
818					@Override
819					public void onClick(DialogInterface dialog, int which) {
820						mAccount.getAxolotlService().wipeOtherPepDevices();
821					}
822				});
823		builder.create().show();
824	}
825
826	private void editMamPrefs() {
827		this.mFetchingMamPrefsToast = Toast.makeText(this, R.string.fetching_mam_prefs, Toast.LENGTH_LONG);
828		this.mFetchingMamPrefsToast.show();
829		xmppConnectionService.fetchMamPreferences(mAccount, this);
830	}
831
832	@Override
833	public void onKeyStatusUpdated(AxolotlService.FetchStatus report) {
834		refreshUi();
835	}
836
837	@Override
838	public void onCaptchaRequested(final Account account, final String id, final Data data,
839								   final Bitmap captcha) {
840		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
841		final ImageView view = new ImageView(this);
842		final LinearLayout layout = new LinearLayout(this);
843		final EditText input = new EditText(this);
844
845		view.setImageBitmap(captcha);
846		view.setScaleType(ImageView.ScaleType.FIT_CENTER);
847
848		input.setHint(getString(R.string.captcha_hint));
849
850		layout.setOrientation(LinearLayout.VERTICAL);
851		layout.addView(view);
852		layout.addView(input);
853
854		builder.setTitle(getString(R.string.captcha_required));
855		builder.setView(layout);
856
857		builder.setPositiveButton(getString(R.string.ok),
858				new DialogInterface.OnClickListener() {
859					@Override
860					public void onClick(DialogInterface dialog, int which) {
861						String rc = input.getText().toString();
862						data.put("username", account.getUsername());
863						data.put("password", account.getPassword());
864						data.put("ocr", rc);
865						data.submit();
866
867						if (xmppConnectionServiceBound) {
868							xmppConnectionService.sendCreateAccountWithCaptchaPacket(
869									account, id, data);
870						}
871					}
872				});
873		builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
874			@Override
875			public void onClick(DialogInterface dialog, int which) {
876				if (xmppConnectionService != null) {
877					xmppConnectionService.sendCreateAccountWithCaptchaPacket(account, null, null);
878				}
879			}
880		});
881
882		builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
883			@Override
884			public void onCancel(DialogInterface dialog) {
885				if (xmppConnectionService != null) {
886					xmppConnectionService.sendCreateAccountWithCaptchaPacket(account, null, null);
887				}
888			}
889		});
890
891		runOnUiThread(new Runnable() {
892			@Override
893			public void run() {
894				if ((mCaptchaDialog != null) && mCaptchaDialog.isShowing()) {
895					mCaptchaDialog.dismiss();
896				}
897				mCaptchaDialog = builder.create();
898				mCaptchaDialog.show();
899			}
900		});
901	}
902
903	public void onShowErrorToast(final int resId) {
904		runOnUiThread(new Runnable() {
905			@Override
906			public void run() {
907				Toast.makeText(EditAccountActivity.this, resId, Toast.LENGTH_SHORT).show();
908			}
909		});
910	}
911
912	@Override
913	public void onPreferencesFetched(final Element prefs) {
914		runOnUiThread(new Runnable() {
915			@Override
916			public void run() {
917				if (mFetchingMamPrefsToast != null) {
918					mFetchingMamPrefsToast.cancel();
919				}
920				AlertDialog.Builder builder = new Builder(EditAccountActivity.this);
921				builder.setTitle(R.string.mam_prefs);
922				String defaultAttr = prefs.getAttribute("default");
923				final List<String> defaults = Arrays.asList("never", "roster", "always");
924				final AtomicInteger choice = new AtomicInteger(Math.max(0,defaults.indexOf(defaultAttr)));
925				builder.setSingleChoiceItems(R.array.mam_prefs, choice.get(), new DialogInterface.OnClickListener() {
926					@Override
927					public void onClick(DialogInterface dialog, int which) {
928						choice.set(which);
929					}
930				});
931				builder.setNegativeButton(R.string.cancel, null);
932				builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
933					@Override
934					public void onClick(DialogInterface dialog, int which) {
935						prefs.setAttribute("default",defaults.get(choice.get()));
936						xmppConnectionService.pushMamPreferences(mAccount, prefs);
937					}
938				});
939				builder.create().show();
940			}
941		});
942	}
943
944	@Override
945	public void onPreferencesFetchFailed() {
946		runOnUiThread(new Runnable() {
947			@Override
948			public void run() {
949				if (mFetchingMamPrefsToast != null) {
950					mFetchingMamPrefsToast.cancel();
951				}
952				Toast.makeText(EditAccountActivity.this,R.string.unable_to_fetch_mam_prefs,Toast.LENGTH_LONG).show();
953			}
954		});
955	}
956}