1package eu.siacs.conversations.ui;
2
3import android.app.Activity;
4import android.app.PendingIntent;
5import android.content.ActivityNotFoundException;
6import android.content.Intent;
7import android.content.IntentSender;
8import android.content.SharedPreferences;
9import android.databinding.DataBindingUtil;
10import android.graphics.Bitmap;
11import android.net.Uri;
12import android.os.Bundle;
13import android.os.Handler;
14import android.preference.PreferenceManager;
15import android.provider.Settings;
16import android.security.KeyChain;
17import android.security.KeyChainAliasCallback;
18import android.support.design.widget.TextInputLayout;
19import android.support.v7.app.ActionBar;
20import android.support.v7.app.AlertDialog;
21import android.support.v7.app.AlertDialog.Builder;
22import android.support.v7.widget.Toolbar;
23import android.text.Editable;
24import android.text.TextUtils;
25import android.text.TextWatcher;
26import android.util.Log;
27import android.view.Menu;
28import android.view.MenuItem;
29import android.view.View;
30import android.view.View.OnClickListener;
31import android.widget.Button;
32import android.widget.CompoundButton;
33import android.widget.CompoundButton.OnCheckedChangeListener;
34import android.widget.EditText;
35import android.widget.ImageButton;
36import android.widget.ImageView;
37import android.widget.LinearLayout;
38import android.widget.RelativeLayout;
39import android.widget.TableLayout;
40import android.widget.TextView;
41import android.widget.Toast;
42
43import org.openintents.openpgp.util.OpenPgpUtils;
44
45import java.net.URL;
46import java.util.Arrays;
47import java.util.List;
48import java.util.Set;
49import java.util.concurrent.atomic.AtomicInteger;
50
51import eu.siacs.conversations.Config;
52import eu.siacs.conversations.R;
53import eu.siacs.conversations.crypto.axolotl.AxolotlService;
54import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession;
55import eu.siacs.conversations.databinding.ActivityEditAccountBinding;
56import eu.siacs.conversations.databinding.DialogPresenceBinding;
57import eu.siacs.conversations.entities.Account;
58import eu.siacs.conversations.entities.Presence;
59import eu.siacs.conversations.entities.PresenceTemplate;
60import eu.siacs.conversations.services.BarcodeProvider;
61import eu.siacs.conversations.services.XmppConnectionService;
62import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
63import eu.siacs.conversations.services.XmppConnectionService.OnCaptchaRequested;
64import eu.siacs.conversations.ui.adapter.KnownHostsAdapter;
65import eu.siacs.conversations.ui.adapter.PresenceTemplateAdapter;
66import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
67import eu.siacs.conversations.ui.util.PendingItem;
68import eu.siacs.conversations.ui.util.SoftKeyboardUtils;
69import eu.siacs.conversations.utils.CryptoHelper;
70import eu.siacs.conversations.utils.SignupUtils;
71import eu.siacs.conversations.utils.UIHelper;
72import eu.siacs.conversations.utils.XmppUri;
73import eu.siacs.conversations.xml.Element;
74import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
75import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
76import eu.siacs.conversations.xmpp.XmppConnection;
77import eu.siacs.conversations.xmpp.XmppConnection.Features;
78import eu.siacs.conversations.xmpp.forms.Data;
79import eu.siacs.conversations.xmpp.pep.Avatar;
80import rocks.xmpp.addr.Jid;
81
82public class EditAccountActivity extends OmemoActivity implements OnAccountUpdate, OnUpdateBlocklist,
83 OnKeyStatusUpdated, OnCaptchaRequested, KeyChainAliasCallback, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnMamPreferencesFetched {
84
85 private static final int REQUEST_DATA_SAVER = 0xf244;
86 private static final int REQUEST_CHANGE_STATUS = 0xee11;
87 private TextInputLayout mAccountJidLayout;
88 private EditText mPassword;
89 private TextInputLayout mPasswordLayout;
90 private Button mCancelButton;
91 private Button mSaveButton;
92 private Button mDisableOsOptimizationsButton;
93 private TextView getmDisableOsOptimizationsBody;
94 private TableLayout mMoreTable;
95
96 private TextView mAxolotlFingerprint;
97 private TextView mPgpFingerprint;
98 private TextView mOwnFingerprintDesc;
99 private TextView getmPgpFingerprintDesc;
100 private ImageView mAvatar;
101 private RelativeLayout mAxolotlFingerprintBox;
102 private RelativeLayout mPgpFingerprintBox;
103 private ImageButton mAxolotlFingerprintToClipboardButton;
104 private ImageButton mPgpDeleteFingerprintButton;
105 private LinearLayout keys;
106 private EditText mPort;
107 private AlertDialog mCaptchaDialog = null;
108
109 private Jid jidToEdit;
110 private boolean mInitMode = false;
111 private boolean mUsernameMode = Config.DOMAIN_LOCK != null;
112 private boolean mShowOptions = false;
113 private Account mAccount;
114 private String messageFingerprint;
115
116 private final PendingItem<PresenceTemplate> mPendingPresenceTemplate = new PendingItem<>();
117
118 private boolean mFetchingAvatar = false;
119
120 private final OnClickListener mSaveButtonClickListener = new OnClickListener() {
121
122 @Override
123 public void onClick(final View v) {
124 final String password = mPassword.getText().toString();
125 final boolean wasDisabled = mAccount != null && mAccount.getStatus() == Account.State.DISABLED;
126 final boolean accountInfoEdited = accountInfoEdited();
127
128 if (!mInitMode && passwordChangedInMagicCreateMode()) {
129 gotoChangePassword(password);
130 return;
131 }
132 if (mInitMode && mAccount != null) {
133 mAccount.setOption(Account.OPTION_DISABLED, false);
134 }
135 if (mAccount != null && mAccount.getStatus() == Account.State.DISABLED && !accountInfoEdited) {
136 mAccount.setOption(Account.OPTION_DISABLED, false);
137 if (!xmppConnectionService.updateAccount(mAccount)) {
138 Toast.makeText(EditAccountActivity.this, R.string.unable_to_update_account, Toast.LENGTH_SHORT).show();
139 }
140 return;
141 }
142 final boolean registerNewAccount = binding.accountRegisterNew.isChecked() && !Config.DISALLOW_REGISTRATION_IN_UI;
143 if (mUsernameMode && binding.accountJid.getText().toString().contains("@")) {
144 mAccountJidLayout.setError(getString(R.string.invalid_username));
145 removeErrorsOnAllBut(mAccountJidLayout);
146 binding.accountJid.requestFocus();
147 return;
148 }
149
150 XmppConnection connection = mAccount == null ? null : mAccount.getXmppConnection();
151 boolean openRegistrationUrl = registerNewAccount && !accountInfoEdited && mAccount != null && mAccount.getStatus() == Account.State.REGISTRATION_WEB;
152 boolean openPaymentUrl = mAccount != null && mAccount.getStatus() == Account.State.PAYMENT_REQUIRED;
153 final boolean redirectionWorthyStatus = openPaymentUrl || openRegistrationUrl;
154 URL url = connection != null && redirectionWorthyStatus ? connection.getRedirectionUrl() : null;
155 if (url != null && !wasDisabled) {
156 try {
157 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url.toString())));
158 return;
159 } catch (ActivityNotFoundException e) {
160 Toast.makeText(EditAccountActivity.this, R.string.application_found_to_open_website, Toast.LENGTH_SHORT).show();
161 return;
162 }
163 }
164
165 final Jid jid;
166 try {
167 if (mUsernameMode) {
168 jid = Jid.of(binding.accountJid.getText().toString(), getUserModeDomain(), null);
169 } else {
170 jid = Jid.of(binding.accountJid.getText().toString());
171 }
172 } catch (final NullPointerException | IllegalArgumentException e) {
173 if (mUsernameMode) {
174 mAccountJidLayout.setError(getString(R.string.invalid_username));
175 } else {
176 mAccountJidLayout.setError(getString(R.string.invalid_jid));
177 }
178 binding.accountJid.requestFocus();
179 removeErrorsOnAllBut(mAccountJidLayout);
180 return;
181 }
182 String hostname = null;
183 int numericPort = 5222;
184 if (mShowOptions) {
185 hostname = binding.hostname.getText().toString().replaceAll("\\s", "");
186 final String port = mPort.getText().toString().replaceAll("\\s", "");
187 if (hostname.contains(" ")) {
188 binding.hostnameLayout.setError(getString(R.string.not_valid_hostname));
189 binding.hostname.requestFocus();
190 removeErrorsOnAllBut(binding.hostnameLayout);
191 return;
192 }
193 try {
194 numericPort = Integer.parseInt(port);
195 if (numericPort < 0 || numericPort > 65535) {
196 binding.portLayout.setError(getString(R.string.not_a_valid_port));
197 removeErrorsOnAllBut(binding.portLayout);
198 mPort.requestFocus();
199 return;
200 }
201
202 } catch (NumberFormatException e) {
203 binding.portLayout.setError(getString(R.string.not_a_valid_port));
204 removeErrorsOnAllBut(binding.portLayout);
205 mPort.requestFocus();
206 return;
207 }
208 }
209
210 if (jid.getLocal() == null) {
211 if (mUsernameMode) {
212 mAccountJidLayout.setError(getString(R.string.invalid_username));
213 } else {
214 mAccountJidLayout.setError(getString(R.string.invalid_jid));
215 }
216 removeErrorsOnAllBut(mAccountJidLayout);
217 binding.accountJid.requestFocus();
218 return;
219 }
220 if (mAccount != null) {
221 if (mInitMode && mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE)) {
222 mAccount.setOption(Account.OPTION_MAGIC_CREATE, mAccount.getPassword().contains(password));
223 }
224 mAccount.setJid(jid);
225 mAccount.setPort(numericPort);
226 mAccount.setHostname(hostname);
227 mAccountJidLayout.setError(null);
228 mAccount.setPassword(password);
229 mAccount.setOption(Account.OPTION_REGISTER, registerNewAccount);
230 if (!xmppConnectionService.updateAccount(mAccount)) {
231 Toast.makeText(EditAccountActivity.this, R.string.unable_to_update_account, Toast.LENGTH_SHORT).show();
232 return;
233 }
234 } else {
235 if (xmppConnectionService.findAccountByJid(jid) != null) {
236 mAccountJidLayout.setError(getString(R.string.account_already_exists));
237 removeErrorsOnAllBut(mAccountJidLayout);
238 binding.accountJid.requestFocus();
239 return;
240 }
241 mAccount = new Account(jid.asBareJid(), password);
242 mAccount.setPort(numericPort);
243 mAccount.setHostname(hostname);
244 mAccount.setOption(Account.OPTION_USETLS, true);
245 mAccount.setOption(Account.OPTION_USECOMPRESSION, true);
246 mAccount.setOption(Account.OPTION_REGISTER, registerNewAccount);
247 xmppConnectionService.createAccount(mAccount);
248 }
249 binding.hostnameLayout.setError(null);
250 binding.portLayout.setError(null);
251 if (mAccount.isEnabled()
252 && !registerNewAccount
253 && !mInitMode) {
254 finish();
255 } else {
256 updateSaveButton();
257 updateAccountInformation(true);
258 }
259
260 }
261 };
262 private final OnClickListener mCancelButtonClickListener = new OnClickListener() {
263
264 @Override
265 public void onClick(final View v) {
266 deleteAccountAndReturnIfNecessary();
267 finish();
268 }
269 };
270 private Toast mFetchingMamPrefsToast;
271 private String mSavedInstanceAccount;
272 private boolean mSavedInstanceInit = false;
273 private Button mClearDevicesButton;
274 private XmppUri pendingUri = null;
275 private boolean mUseTor;
276 private ActivityEditAccountBinding binding;
277
278 public void refreshUiReal() {
279 invalidateOptionsMenu();
280 if (mAccount != null
281 && mAccount.getStatus() != Account.State.ONLINE
282 && mFetchingAvatar) {
283 Intent intent = new Intent(this, StartConversationActivity.class);
284 StartConversationActivity.addInviteUri(intent, getIntent());
285 startActivity(intent);
286 finish();
287 } else if (mInitMode && mAccount != null && mAccount.getStatus() == Account.State.ONLINE) {
288 if (!mFetchingAvatar) {
289 mFetchingAvatar = true;
290 xmppConnectionService.checkForAvatar(mAccount, mAvatarFetchCallback);
291 }
292 }
293 if (mAccount != null) {
294 updateAccountInformation(false);
295 }
296 updateSaveButton();
297 }
298
299 @Override
300 public boolean onNavigateUp() {
301 deleteAccountAndReturnIfNecessary();
302 return super.onNavigateUp();
303 }
304
305 @Override
306 public void onBackPressed() {
307 deleteAccountAndReturnIfNecessary();
308 super.onBackPressed();
309 }
310
311 private void deleteAccountAndReturnIfNecessary() {
312 if (mInitMode && mAccount != null && !mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY)) {
313 xmppConnectionService.deleteAccount(mAccount);
314 }
315
316 if (xmppConnectionService.getAccounts().size() == 0 && Config.MAGIC_CREATE_DOMAIN != null) {
317 Intent intent = SignupUtils.getSignUpIntent(this);
318 startActivity(intent);
319 }
320 }
321
322 @Override
323 public void onAccountUpdate() {
324 refreshUi();
325 }
326
327 private final UiCallback<Avatar> mAvatarFetchCallback = new UiCallback<Avatar>() {
328
329 @Override
330 public void userInputRequried(final PendingIntent pi, final Avatar avatar) {
331 finishInitialSetup(avatar);
332 }
333
334 @Override
335 public void success(final Avatar avatar) {
336 finishInitialSetup(avatar);
337 }
338
339 @Override
340 public void error(final int errorCode, final Avatar avatar) {
341 finishInitialSetup(avatar);
342 }
343 };
344 private final TextWatcher mTextWatcher = new TextWatcher() {
345
346 @Override
347 public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {
348 updatePortLayout();
349 updateSaveButton();
350 }
351
352 @Override
353 public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {
354 }
355
356 @Override
357 public void afterTextChanged(final Editable s) {
358
359 }
360 };
361
362 private View.OnFocusChangeListener mEditTextFocusListener = new View.OnFocusChangeListener() {
363 @Override
364 public void onFocusChange(View view, boolean b) {
365 EditText et = (EditText) view;
366 if (b) {
367 int resId = mUsernameMode ? R.string.username : R.string.account_settings_example_jabber_id;
368 if (view.getId() == R.id.hostname) {
369 resId = mUseTor ? R.string.hostname_or_onion : R.string.hostname_example;
370 }
371 final int res = resId;
372 new Handler().postDelayed(() -> et.setHint(res), 200);
373 } else {
374 et.setHint(null);
375 }
376 }
377 };
378
379
380 private final OnClickListener mAvatarClickListener = new OnClickListener() {
381 @Override
382 public void onClick(final View view) {
383 if (mAccount != null) {
384 final Intent intent = new Intent(getApplicationContext(), PublishProfilePictureActivity.class);
385 intent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().asBareJid().toString());
386 startActivity(intent);
387 }
388 }
389 };
390
391 protected void finishInitialSetup(final Avatar avatar) {
392 runOnUiThread(() -> {
393 SoftKeyboardUtils.hideSoftKeyboard(EditAccountActivity.this);
394 final Intent intent;
395 final XmppConnection connection = mAccount.getXmppConnection();
396 final boolean wasFirstAccount = xmppConnectionService != null && xmppConnectionService.getAccounts().size() == 1;
397 if (avatar != null || (connection != null && !connection.getFeatures().pep())) {
398 intent = new Intent(getApplicationContext(), StartConversationActivity.class);
399 if (wasFirstAccount) {
400 intent.putExtra("init", true);
401 }
402 } else {
403 intent = new Intent(getApplicationContext(), PublishProfilePictureActivity.class);
404 intent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().asBareJid().toString());
405 intent.putExtra("setup", true);
406 }
407 if (wasFirstAccount) {
408 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
409 }
410 StartConversationActivity.addInviteUri(intent, getIntent());
411 startActivity(intent);
412 finish();
413 });
414 }
415
416 @Override
417 public void onActivityResult(int requestCode, int resultCode, Intent data) {
418 super.onActivityResult(requestCode, resultCode, data);
419 if (requestCode == REQUEST_BATTERY_OP || requestCode == REQUEST_DATA_SAVER) {
420 updateAccountInformation(mAccount == null);
421 }
422 if (requestCode == REQUEST_CHANGE_STATUS) {
423 PresenceTemplate template = mPendingPresenceTemplate.pop();
424 if (template != null && resultCode == Activity.RESULT_OK) {
425 generateSignature(data, template);
426 } else {
427 Log.d(Config.LOGTAG, "pgp result not ok");
428 }
429 }
430 }
431
432 @Override
433 protected void processFingerprintVerification(XmppUri uri) {
434 processFingerprintVerification(uri, true);
435 }
436
437
438 protected void processFingerprintVerification(XmppUri uri, boolean showWarningToast) {
439 if (mAccount != null && mAccount.getJid().asBareJid().equals(uri.getJid()) && uri.hasFingerprints()) {
440 if (xmppConnectionService.verifyFingerprints(mAccount, uri.getFingerprints())) {
441 Toast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show();
442 updateAccountInformation(false);
443 }
444 } else if (showWarningToast) {
445 Toast.makeText(this, R.string.invalid_barcode, Toast.LENGTH_SHORT).show();
446 }
447 }
448
449 private void updatePortLayout() {
450 String hostname = this.binding.hostname.getText().toString();
451 this.binding.portLayout.setEnabled(!TextUtils.isEmpty(hostname));
452 }
453
454 protected void updateSaveButton() {
455 boolean accountInfoEdited = accountInfoEdited();
456
457 if (!mInitMode && passwordChangedInMagicCreateMode()) {
458 this.mSaveButton.setText(R.string.change_password);
459 this.mSaveButton.setEnabled(true);
460 } else if (accountInfoEdited && !mInitMode) {
461 this.mSaveButton.setText(R.string.save);
462 this.mSaveButton.setEnabled(true);
463 } else if (mAccount != null
464 && (mAccount.getStatus() == Account.State.CONNECTING || mAccount.getStatus() == Account.State.REGISTRATION_SUCCESSFUL || mFetchingAvatar)) {
465 this.mSaveButton.setEnabled(false);
466 this.mSaveButton.setText(R.string.account_status_connecting);
467 } else if (mAccount != null && mAccount.getStatus() == Account.State.DISABLED && !mInitMode) {
468 this.mSaveButton.setEnabled(true);
469 this.mSaveButton.setText(R.string.enable);
470 } else {
471 this.mSaveButton.setEnabled(true);
472 if (!mInitMode) {
473 if (mAccount != null && mAccount.isOnlineAndConnected()) {
474 this.mSaveButton.setText(R.string.save);
475 if (!accountInfoEdited) {
476 this.mSaveButton.setEnabled(false);
477 }
478 } else {
479 XmppConnection connection = mAccount == null ? null : mAccount.getXmppConnection();
480 URL url = connection != null && mAccount.getStatus() == Account.State.PAYMENT_REQUIRED ? connection.getRedirectionUrl() : null;
481 if (url != null) {
482 this.mSaveButton.setText(R.string.open_website);
483 } else {
484 this.mSaveButton.setText(R.string.connect);
485 }
486 }
487 } else {
488 XmppConnection connection = mAccount == null ? null : mAccount.getXmppConnection();
489 URL url = connection != null && mAccount.getStatus() == Account.State.REGISTRATION_WEB ? connection.getRedirectionUrl() : null;
490 if (url != null && this.binding.accountRegisterNew.isChecked() && !accountInfoEdited) {
491 this.mSaveButton.setText(R.string.open_website);
492 } else {
493 this.mSaveButton.setText(R.string.next);
494 }
495 }
496 }
497 }
498
499 protected boolean accountInfoEdited() {
500 if (this.mAccount == null) {
501 return false;
502 }
503 return jidEdited() ||
504 !this.mAccount.getPassword().equals(this.mPassword.getText().toString()) ||
505 !this.mAccount.getHostname().equals(this.binding.hostname.getText().toString()) ||
506 !String.valueOf(this.mAccount.getPort()).equals(this.mPort.getText().toString());
507 }
508
509 protected boolean jidEdited() {
510 final String unmodified;
511 if (mUsernameMode) {
512 unmodified = this.mAccount.getJid().getLocal();
513 } else {
514 unmodified = this.mAccount.getJid().asBareJid().toString();
515 }
516 return !unmodified.equals(this.binding.accountJid.getText().toString());
517 }
518
519 protected boolean passwordChangedInMagicCreateMode() {
520 return mAccount != null
521 && mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE)
522 && !this.mAccount.getPassword().equals(this.mPassword.getText().toString())
523 && !this.jidEdited()
524 && mAccount.isOnlineAndConnected();
525 }
526
527 @Override
528 protected String getShareableUri(boolean http) {
529 if (mAccount != null) {
530 return http ? mAccount.getShareableLink() : mAccount.getShareableUri();
531 } else {
532 return null;
533 }
534 }
535
536 @Override
537 protected void onCreate(final Bundle savedInstanceState) {
538 super.onCreate(savedInstanceState);
539 if (savedInstanceState != null) {
540 this.mSavedInstanceAccount = savedInstanceState.getString("account");
541 this.mSavedInstanceInit = savedInstanceState.getBoolean("initMode", false);
542 }
543 this.binding = DataBindingUtil.setContentView(this, R.layout.activity_edit_account);
544 setSupportActionBar((Toolbar) binding.toolbar);
545 configureActionBar(getSupportActionBar());
546 binding.accountJid.addTextChangedListener(this.mTextWatcher);
547 binding.accountJid.setOnFocusChangeListener(this.mEditTextFocusListener);
548 this.mAccountJidLayout = (TextInputLayout) findViewById(R.id.account_jid_layout);
549 this.mPassword = (EditText) findViewById(R.id.account_password);
550 this.mPassword.addTextChangedListener(this.mTextWatcher);
551 this.mPasswordLayout = (TextInputLayout) findViewById(R.id.account_password_layout);
552 this.mAvatar = (ImageView) findViewById(R.id.avater);
553 this.mAvatar.setOnClickListener(this.mAvatarClickListener);
554 this.mDisableOsOptimizationsButton = (Button) findViewById(R.id.os_optimization_disable);
555 this.getmDisableOsOptimizationsBody = (TextView) findViewById(R.id.os_optimization_body);
556 this.mPgpFingerprintBox = (RelativeLayout) findViewById(R.id.pgp_fingerprint_box);
557 this.mPgpFingerprint = (TextView) findViewById(R.id.pgp_fingerprint);
558 this.getmPgpFingerprintDesc = (TextView) findViewById(R.id.pgp_fingerprint_desc);
559 this.mPgpDeleteFingerprintButton = (ImageButton) findViewById(R.id.action_delete_pgp);
560 this.mAxolotlFingerprint = (TextView) findViewById(R.id.axolotl_fingerprint);
561 this.mAxolotlFingerprintBox = (RelativeLayout) findViewById(R.id.axolotl_fingerprint_box);
562 this.mAxolotlFingerprintToClipboardButton = (ImageButton) findViewById(R.id.action_copy_axolotl_to_clipboard);
563 this.mOwnFingerprintDesc = (TextView) findViewById(R.id.own_fingerprint_desc);
564 this.keys = findViewById(R.id.other_device_keys);
565 this.binding.hostname.addTextChangedListener(mTextWatcher);
566 this.binding.hostname.setOnFocusChangeListener(mEditTextFocusListener);
567 this.mClearDevicesButton = (Button) findViewById(R.id.clear_devices);
568 this.mClearDevicesButton.setOnClickListener(v -> showWipePepDialog());
569 this.mPort = (EditText) findViewById(R.id.port);
570 this.mPort.setText("5222");
571 this.mPort.addTextChangedListener(mTextWatcher);
572 this.mSaveButton = (Button) findViewById(R.id.save_button);
573 this.mCancelButton = (Button) findViewById(R.id.cancel_button);
574 this.mSaveButton.setOnClickListener(this.mSaveButtonClickListener);
575 this.mCancelButton.setOnClickListener(this.mCancelButtonClickListener);
576 this.mMoreTable = (TableLayout) findViewById(R.id.server_info_more);
577 if (savedInstanceState != null && savedInstanceState.getBoolean("showMoreTable")) {
578 changeMoreTableVisibility(true);
579 }
580 final OnCheckedChangeListener OnCheckedShowConfirmPassword = new OnCheckedChangeListener() {
581 @Override
582 public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
583 updateSaveButton();
584 }
585 };
586 this.binding.accountRegisterNew.setOnCheckedChangeListener(OnCheckedShowConfirmPassword);
587 if (Config.DISALLOW_REGISTRATION_IN_UI) {
588 this.binding.accountRegisterNew.setVisibility(View.GONE);
589 }
590 }
591
592 @Override
593 public boolean onCreateOptionsMenu(final Menu menu) {
594 super.onCreateOptionsMenu(menu);
595 getMenuInflater().inflate(R.menu.editaccount, menu);
596 final MenuItem showBlocklist = menu.findItem(R.id.action_show_block_list);
597 final MenuItem showMoreInfo = menu.findItem(R.id.action_server_info_show_more);
598 final MenuItem changePassword = menu.findItem(R.id.action_change_password_on_server);
599 final MenuItem renewCertificate = menu.findItem(R.id.action_renew_certificate);
600 final MenuItem mamPrefs = menu.findItem(R.id.action_mam_prefs);
601 final MenuItem changePresence = menu.findItem(R.id.action_change_presence);
602 final MenuItem share = menu.findItem(R.id.action_share);
603 renewCertificate.setVisible(mAccount != null && mAccount.getPrivateKeyAlias() != null);
604
605 share.setVisible(mAccount != null && !mInitMode);
606
607 if (mAccount != null && mAccount.isOnlineAndConnected()) {
608 if (!mAccount.getXmppConnection().getFeatures().blocking()) {
609 showBlocklist.setVisible(false);
610 }
611
612 if (!mAccount.getXmppConnection().getFeatures().register()) {
613 changePassword.setVisible(false);
614 }
615 mamPrefs.setVisible(mAccount.getXmppConnection().getFeatures().mam());
616 changePresence.setVisible(!mInitMode);
617 } else {
618 showBlocklist.setVisible(false);
619 showMoreInfo.setVisible(false);
620 changePassword.setVisible(false);
621 mamPrefs.setVisible(false);
622 changePresence.setVisible(false);
623 }
624 return super.onCreateOptionsMenu(menu);
625 }
626
627 @Override
628 public boolean onPrepareOptionsMenu(Menu menu) {
629 final MenuItem showMoreInfo = menu.findItem(R.id.action_server_info_show_more);
630 if (showMoreInfo.isVisible()) {
631 showMoreInfo.setChecked(mMoreTable.getVisibility() == View.VISIBLE);
632 }
633 return super.onPrepareOptionsMenu(menu);
634 }
635
636 @Override
637 protected void onStart() {
638 super.onStart();
639 final Intent intent = getIntent();
640 final int theme = findTheme();
641 if (this.mTheme != theme) {
642 recreate();
643 } else if (intent != null) {
644 try {
645 this.jidToEdit = Jid.of(intent.getStringExtra("jid"));
646 } catch (final IllegalArgumentException | NullPointerException ignored) {
647 this.jidToEdit = null;
648 }
649 if (jidToEdit != null && intent.getData() != null && intent.getBooleanExtra("scanned", false)) {
650 final XmppUri uri = new XmppUri(intent.getData());
651 if (xmppConnectionServiceBound) {
652 processFingerprintVerification(uri, false);
653 } else {
654 this.pendingUri = uri;
655 }
656 }
657 boolean init = intent.getBooleanExtra("init", false);
658 this.mInitMode = init || this.jidToEdit == null;
659 this.messageFingerprint = intent.getStringExtra("fingerprint");
660 if (!mInitMode) {
661 this.binding.accountRegisterNew.setVisibility(View.GONE);
662 if (getSupportActionBar() != null) {
663 getSupportActionBar().setTitle(getString(R.string.account_details));
664 }
665 } else {
666 this.mAvatar.setVisibility(View.GONE);
667 ActionBar ab = getSupportActionBar();
668 if (ab != null) {
669 if (init && Config.MAGIC_CREATE_DOMAIN == null) {
670 ab.setDisplayShowHomeEnabled(false);
671 ab.setDisplayHomeAsUpEnabled(false);
672 }
673 ab.setTitle(R.string.action_add_account);
674 }
675 }
676 }
677 SharedPreferences preferences = getPreferences();
678 mUseTor = Config.FORCE_ORBOT || preferences.getBoolean("use_tor", false);
679 this.mShowOptions = mUseTor || preferences.getBoolean("show_connection_options", false);
680 this.binding.namePort.setVisibility(mShowOptions ? View.VISIBLE : View.GONE);
681 }
682
683 @Override
684 public void onNewIntent(Intent intent) {
685 if (intent != null && intent.getData() != null) {
686 final XmppUri uri = new XmppUri(intent.getData());
687 if (xmppConnectionServiceBound) {
688 processFingerprintVerification(uri, false);
689 } else {
690 this.pendingUri = uri;
691 }
692 }
693 }
694
695 @Override
696 public void onSaveInstanceState(final Bundle savedInstanceState) {
697 if (mAccount != null) {
698 savedInstanceState.putString("account", mAccount.getJid().asBareJid().toString());
699 savedInstanceState.putBoolean("initMode", mInitMode);
700 savedInstanceState.putBoolean("showMoreTable", mMoreTable.getVisibility() == View.VISIBLE);
701 }
702 super.onSaveInstanceState(savedInstanceState);
703 }
704
705 protected void onBackendConnected() {
706 boolean init = true;
707 if (mSavedInstanceAccount != null) {
708 try {
709 this.mAccount = xmppConnectionService.findAccountByJid(Jid.of(mSavedInstanceAccount));
710 this.mInitMode = mSavedInstanceInit;
711 init = false;
712 } catch (IllegalArgumentException e) {
713 this.mAccount = null;
714 }
715
716 } else if (this.jidToEdit != null) {
717 this.mAccount = xmppConnectionService.findAccountByJid(jidToEdit);
718 }
719
720 if (mAccount != null) {
721 this.mInitMode |= this.mAccount.isOptionSet(Account.OPTION_REGISTER);
722 this.mUsernameMode |= mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE) && mAccount.isOptionSet(Account.OPTION_REGISTER);
723 if (this.mAccount.getPrivateKeyAlias() != null) {
724 this.mPassword.setHint(R.string.authenticate_with_certificate);
725 if (this.mInitMode) {
726 this.mPassword.requestFocus();
727 }
728 }
729 if (mPendingFingerprintVerificationUri != null) {
730 processFingerprintVerification(mPendingFingerprintVerificationUri, false);
731 mPendingFingerprintVerificationUri = null;
732 }
733 updateAccountInformation(init);
734 }
735
736
737 if (Config.MAGIC_CREATE_DOMAIN == null && this.xmppConnectionService.getAccounts().size() == 0) {
738 this.mCancelButton.setEnabled(false);
739 }
740 if (mUsernameMode) {
741 this.binding.accountJidLayout.setHint(getString(R.string.username_hint));
742 this.binding.accountJid.setHint(R.string.username_hint);
743 } else {
744 final KnownHostsAdapter mKnownHostsAdapter = new KnownHostsAdapter(this,
745 R.layout.simple_list_item,
746 xmppConnectionService.getKnownHosts());
747 this.binding.accountJid.setAdapter(mKnownHostsAdapter);
748 }
749
750 if (pendingUri != null) {
751 processFingerprintVerification(pendingUri, false);
752 pendingUri = null;
753 }
754 updatePortLayout();
755 updateSaveButton();
756 invalidateOptionsMenu();
757 }
758
759 private String getUserModeDomain() {
760 if (mAccount != null && mAccount.getJid().getDomain() != null) {
761 return mAccount.getJid().getDomain();
762 } else {
763 return Config.DOMAIN_LOCK;
764 }
765 }
766
767 @Override
768 public boolean onOptionsItemSelected(final MenuItem item) {
769 if (MenuDoubleTabUtil.shouldIgnoreTap()) {
770 return false;
771 }
772 switch (item.getItemId()) {
773 case R.id.action_show_block_list:
774 final Intent showBlocklistIntent = new Intent(this, BlocklistActivity.class);
775 showBlocklistIntent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toString());
776 startActivity(showBlocklistIntent);
777 break;
778 case R.id.action_server_info_show_more:
779 changeMoreTableVisibility(!item.isChecked());
780 break;
781 case R.id.action_share_barcode:
782 shareBarcode();
783 break;
784 case R.id.action_share_http:
785 shareLink(true);
786 break;
787 case R.id.action_share_uri:
788 shareLink(false);
789 break;
790 case R.id.action_change_password_on_server:
791 gotoChangePassword(null);
792 break;
793 case R.id.action_mam_prefs:
794 editMamPrefs();
795 break;
796 case R.id.action_renew_certificate:
797 renewCertificate();
798 break;
799 case R.id.action_change_presence:
800 changePresence();
801 break;
802 }
803 return super.onOptionsItemSelected(item);
804 }
805
806 private void shareBarcode() {
807 Intent intent = new Intent(Intent.ACTION_SEND);
808 intent.putExtra(Intent.EXTRA_STREAM, BarcodeProvider.getUriForAccount(this, mAccount));
809 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
810 intent.setType("image/png");
811 startActivity(Intent.createChooser(intent, getText(R.string.share_with)));
812 }
813
814 private void changeMoreTableVisibility(boolean visible) {
815 mMoreTable.setVisibility(visible ? View.VISIBLE : View.GONE);
816 }
817
818 private void gotoChangePassword(String newPassword) {
819 final Intent changePasswordIntent = new Intent(this, ChangePasswordActivity.class);
820 changePasswordIntent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toString());
821 if (newPassword != null) {
822 changePasswordIntent.putExtra("password", newPassword);
823 }
824 startActivity(changePasswordIntent);
825 }
826
827 private void renewCertificate() {
828 KeyChain.choosePrivateKeyAlias(this, this, null, null, null, -1, null);
829 }
830
831 private void changePresence() {
832 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
833 boolean manualStatus = sharedPreferences.getBoolean(SettingsActivity.MANUALLY_CHANGE_PRESENCE, getResources().getBoolean(R.bool.manually_change_presence));
834 AlertDialog.Builder builder = new AlertDialog.Builder(this);
835 final DialogPresenceBinding binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.dialog_presence, null, false);
836 String current = mAccount.getPresenceStatusMessage();
837 if (current != null && !current.trim().isEmpty()) {
838 binding.statusMessage.append(current);
839 }
840 setAvailabilityRadioButton(mAccount.getPresenceStatus(), binding);
841 binding.show.setVisibility(manualStatus ? View.VISIBLE : View.GONE);
842 List<PresenceTemplate> templates = xmppConnectionService.getPresenceTemplates(mAccount);
843 PresenceTemplateAdapter presenceTemplateAdapter = new PresenceTemplateAdapter(this, R.layout.simple_list_item, templates);
844 binding.statusMessage.setAdapter(presenceTemplateAdapter);
845 binding.statusMessage.setOnItemClickListener((parent, view, position, id) -> {
846 PresenceTemplate template = (PresenceTemplate) parent.getItemAtPosition(position);
847 setAvailabilityRadioButton(template.getStatus(), binding);
848 });
849 builder.setTitle(R.string.edit_status_message_title);
850 builder.setView(binding.getRoot());
851 builder.setNegativeButton(R.string.cancel, null);
852 builder.setPositiveButton(R.string.confirm, (dialog, which) -> {
853 PresenceTemplate template = new PresenceTemplate(getAvailabilityRadioButton(binding), binding.statusMessage.getText().toString().trim());
854 if (mAccount.getPgpId() != 0 && hasPgp()) {
855 generateSignature(null, template);
856 } else {
857 xmppConnectionService.changeStatus(mAccount, template, null);
858 }
859 });
860 builder.create().show();
861 }
862
863 private void generateSignature(Intent intent, PresenceTemplate template) {
864 xmppConnectionService.getPgpEngine().generateSignature(intent, mAccount, template.getStatusMessage(), new UiCallback<String>() {
865 @Override
866 public void success(String signature) {
867 xmppConnectionService.changeStatus(mAccount, template, signature);
868 }
869
870 @Override
871 public void error(int errorCode, String object) {
872
873 }
874
875 @Override
876 public void userInputRequried(PendingIntent pi, String object) {
877 mPendingPresenceTemplate.push(template);
878 try {
879 startIntentSenderForResult(pi.getIntentSender(), REQUEST_CHANGE_STATUS, null, 0, 0, 0);
880 } catch (final IntentSender.SendIntentException ignored) {
881 }
882 }
883 });
884 }
885
886 private static void setAvailabilityRadioButton(Presence.Status status, DialogPresenceBinding binding) {
887 if (status == null) {
888 binding.online.setChecked(true);
889 return;
890 }
891 switch (status) {
892 case DND:
893 binding.dnd.setChecked(true);
894 break;
895 case XA:
896 binding.xa.setChecked(true);
897 break;
898 case AWAY:
899 binding.xa.setChecked(true);
900 break;
901 default:
902 binding.online.setChecked(true);
903 }
904 }
905
906 private static Presence.Status getAvailabilityRadioButton(DialogPresenceBinding binding) {
907 if (binding.dnd.isChecked()) {
908 return Presence.Status.DND;
909 } else if (binding.xa.isChecked()) {
910 return Presence.Status.XA;
911 } else if (binding.away.isChecked()) {
912 return Presence.Status.AWAY;
913 } else {
914 return Presence.Status.ONLINE;
915 }
916 }
917
918 @Override
919 public void alias(String alias) {
920 if (alias != null) {
921 xmppConnectionService.updateKeyInAccount(mAccount, alias);
922 }
923 }
924
925 private void updateAccountInformation(boolean init) {
926 if (init) {
927 this.binding.accountJid.getEditableText().clear();
928 if (mUsernameMode) {
929 this.binding.accountJid.getEditableText().append(this.mAccount.getJid().getLocal());
930 } else {
931 this.binding.accountJid.getEditableText().append(this.mAccount.getJid().asBareJid().toString());
932 }
933 this.mPassword.getEditableText().clear();
934 this.mPassword.getEditableText().append(this.mAccount.getPassword());
935 this.binding.hostname.setText("");
936 this.binding.hostname.getEditableText().append(this.mAccount.getHostname());
937 this.mPort.setText("");
938 this.mPort.getEditableText().append(String.valueOf(this.mAccount.getPort()));
939 this.binding.namePort.setVisibility(mShowOptions ? View.VISIBLE : View.GONE);
940
941 }
942
943 final boolean editable = !mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
944 this.binding.accountJid.setEnabled(editable);
945 this.binding.accountJid.setFocusable(editable);
946 this.binding.accountJid.setFocusableInTouchMode(editable);
947
948
949 if (mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE) || !mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY)) {
950 this.binding.accountPasswordLayout.setPasswordVisibilityToggleEnabled(true);
951 } else {
952 this.binding.accountPasswordLayout.setPasswordVisibilityToggleEnabled(false);
953 }
954
955 if (!mInitMode) {
956 this.mAvatar.setVisibility(View.VISIBLE);
957 this.mAvatar.setImageBitmap(avatarService().get(this.mAccount, (int) getResources().getDimension(R.dimen.avatar_on_details_screen_size)));
958 } else {
959 this.mAvatar.setVisibility(View.GONE);
960 }
961 this.binding.accountRegisterNew.setChecked(this.mAccount.isOptionSet(Account.OPTION_REGISTER));
962 if (this.mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE)) {
963 if (this.mAccount.isOptionSet(Account.OPTION_REGISTER)) {
964 ActionBar actionBar = getSupportActionBar();
965 if (actionBar != null) {
966 actionBar.setTitle(R.string.create_account);
967 }
968 }
969 this.binding.accountRegisterNew.setVisibility(View.GONE);
970 } else if (this.mAccount.isOptionSet(Account.OPTION_REGISTER)) {
971 this.binding.accountRegisterNew.setVisibility(View.VISIBLE);
972 } else {
973 this.binding.accountRegisterNew.setVisibility(View.GONE);
974 }
975 if (this.mAccount.isOnlineAndConnected() && !this.mFetchingAvatar) {
976 Features features = this.mAccount.getXmppConnection().getFeatures();
977 this.binding.stats.setVisibility(View.VISIBLE);
978 boolean showBatteryWarning = !xmppConnectionService.getPushManagementService().available(mAccount) && isOptimizingBattery();
979 boolean showDataSaverWarning = isAffectedByDataSaver();
980 showOsOptimizationWarning(showBatteryWarning, showDataSaverWarning);
981 this.binding.sessionEst.setText(UIHelper.readableTimeDifferenceFull(this, this.mAccount.getXmppConnection()
982 .getLastSessionEstablished()));
983 if (features.rosterVersioning()) {
984 this.binding.serverInfoRosterVersion.setText(R.string.server_info_available);
985 } else {
986 this.binding.serverInfoRosterVersion.setText(R.string.server_info_unavailable);
987 }
988 if (features.carbons()) {
989 this.binding.serverInfoCarbons.setText(R.string.server_info_available);
990 } else {
991 this.binding.serverInfoCarbons.setText(R.string.server_info_unavailable);
992 }
993 if (features.mam()) {
994 this.binding.serverInfoMam.setText(R.string.server_info_available);
995 } else {
996 this.binding.serverInfoMam.setText(R.string.server_info_unavailable);
997 }
998 if (features.csi()) {
999 this.binding.serverInfoCsi.setText(R.string.server_info_available);
1000 } else {
1001 this.binding.serverInfoCsi.setText(R.string.server_info_unavailable);
1002 }
1003 if (features.blocking()) {
1004 this.binding.serverInfoBlocking.setText(R.string.server_info_available);
1005 } else {
1006 this.binding.serverInfoBlocking.setText(R.string.server_info_unavailable);
1007 }
1008 if (features.sm()) {
1009 this.binding.serverInfoSm.setText(R.string.server_info_available);
1010 } else {
1011 this.binding.serverInfoSm.setText(R.string.server_info_unavailable);
1012 }
1013 if (features.pep()) {
1014 AxolotlService axolotlService = this.mAccount.getAxolotlService();
1015 if (axolotlService != null && axolotlService.isPepBroken()) {
1016 this.binding.serverInfoPep.setText(R.string.server_info_broken);
1017 } else if (features.pepPublishOptions() || features.pepOmemoWhitelisted()) {
1018 this.binding.serverInfoPep.setText(R.string.server_info_available);
1019 } else {
1020 this.binding.serverInfoPep.setText(R.string.server_info_partial);
1021 }
1022 } else {
1023 this.binding.serverInfoPep.setText(R.string.server_info_unavailable);
1024 }
1025 if (features.httpUpload(0)) {
1026 this.binding.serverInfoHttpUpload.setText(R.string.server_info_available);
1027 } else if (features.p1S3FileTransfer()) {
1028 this.binding.serverInfoHttpUploadDescription.setText(R.string.p1_s3_filetransfer);
1029 this.binding.serverInfoHttpUpload.setText(R.string.server_info_available);
1030 } else {
1031 this.binding.serverInfoHttpUpload.setText(R.string.server_info_unavailable);
1032 }
1033
1034 this.binding.pushRow.setVisibility(xmppConnectionService.getPushManagementService().isStub() ? View.GONE : View.VISIBLE);
1035
1036 if (xmppConnectionService.getPushManagementService().available(mAccount)) {
1037 this.binding.serverInfoPush.setText(R.string.server_info_available);
1038 } else {
1039 this.binding.serverInfoPush.setText(R.string.server_info_unavailable);
1040 }
1041 final long pgpKeyId = this.mAccount.getPgpId();
1042 if (pgpKeyId != 0 && Config.supportOpenPgp()) {
1043 OnClickListener openPgp = view -> launchOpenKeyChain(pgpKeyId);
1044 OnClickListener delete = view -> showDeletePgpDialog();
1045 this.mPgpFingerprintBox.setVisibility(View.VISIBLE);
1046 this.mPgpFingerprint.setText(OpenPgpUtils.convertKeyIdToHex(pgpKeyId));
1047 this.mPgpFingerprint.setOnClickListener(openPgp);
1048 if ("pgp".equals(messageFingerprint)) {
1049 this.getmPgpFingerprintDesc.setTextAppearance(this, R.style.TextAppearance_Conversations_Caption_Highlight);
1050 }
1051 this.getmPgpFingerprintDesc.setOnClickListener(openPgp);
1052 this.mPgpDeleteFingerprintButton.setOnClickListener(delete);
1053 } else {
1054 this.mPgpFingerprintBox.setVisibility(View.GONE);
1055 }
1056 final String ownAxolotlFingerprint = this.mAccount.getAxolotlService().getOwnFingerprint();
1057 if (ownAxolotlFingerprint != null && Config.supportOmemo()) {
1058 this.mAxolotlFingerprintBox.setVisibility(View.VISIBLE);
1059 if (ownAxolotlFingerprint.equals(messageFingerprint)) {
1060 this.mOwnFingerprintDesc.setTextAppearance(this, R.style.TextAppearance_Conversations_Caption_Highlight);
1061 this.mOwnFingerprintDesc.setText(R.string.omemo_fingerprint_selected_message);
1062 } else {
1063 this.mOwnFingerprintDesc.setTextAppearance(this, R.style.TextAppearance_Conversations_Caption);
1064 this.mOwnFingerprintDesc.setText(R.string.omemo_fingerprint);
1065 }
1066 this.mAxolotlFingerprint.setText(CryptoHelper.prettifyFingerprint(ownAxolotlFingerprint.substring(2)));
1067 this.mAxolotlFingerprintToClipboardButton.setVisibility(View.VISIBLE);
1068 this.mAxolotlFingerprintToClipboardButton.setOnClickListener(v -> copyOmemoFingerprint(ownAxolotlFingerprint));
1069 } else {
1070 this.mAxolotlFingerprintBox.setVisibility(View.GONE);
1071 }
1072 boolean hasKeys = false;
1073 keys.removeAllViews();
1074 for (XmppAxolotlSession session : mAccount.getAxolotlService().findOwnSessions()) {
1075 if (!session.getTrust().isCompromised()) {
1076 boolean highlight = session.getFingerprint().equals(messageFingerprint);
1077 addFingerprintRow(keys, session, highlight);
1078 hasKeys = true;
1079 }
1080 }
1081 if (hasKeys && Config.supportOmemo()) { //TODO: either the button should be visible if we print an active device or the device list should be fed with reactived devices
1082 this.binding.otherDeviceKeysCard.setVisibility(View.VISIBLE);
1083 Set<Integer> otherDevices = mAccount.getAxolotlService().getOwnDeviceIds();
1084 if (otherDevices == null || otherDevices.isEmpty()) {
1085 mClearDevicesButton.setVisibility(View.GONE);
1086 } else {
1087 mClearDevicesButton.setVisibility(View.VISIBLE);
1088 }
1089 } else {
1090 this.binding.otherDeviceKeysCard.setVisibility(View.GONE);
1091 }
1092 } else {
1093 final TextInputLayout errorLayout;
1094 if (this.mAccount.errorStatus()) {
1095 if (this.mAccount.getStatus() == Account.State.UNAUTHORIZED) {
1096 errorLayout = this.mPasswordLayout;
1097 } else if (mShowOptions
1098 && this.mAccount.getStatus() == Account.State.SERVER_NOT_FOUND
1099 && this.binding.hostname.getText().length() > 0) {
1100 errorLayout = this.binding.hostnameLayout;
1101 } else {
1102 errorLayout = this.mAccountJidLayout;
1103 }
1104 errorLayout.setError(getString(this.mAccount.getStatus().getReadableId()));
1105 if (init || !accountInfoEdited()) {
1106 errorLayout.requestFocus();
1107 }
1108 } else {
1109 errorLayout = null;
1110 }
1111 removeErrorsOnAllBut(errorLayout);
1112 this.binding.stats.setVisibility(View.GONE);
1113 this.binding.otherDeviceKeysCard.setVisibility(View.GONE);
1114 }
1115 }
1116
1117 private void removeErrorsOnAllBut(TextInputLayout exception) {
1118 if (this.mAccountJidLayout != exception) {
1119 this.mAccountJidLayout.setErrorEnabled(false);
1120 this.mAccountJidLayout.setError(null);
1121 }
1122 if (this.mPasswordLayout != exception) {
1123 this.mPasswordLayout.setErrorEnabled(false);
1124 this.mPasswordLayout.setError(null);
1125 }
1126 if (this.binding.hostnameLayout != exception) {
1127 this.binding.hostnameLayout.setErrorEnabled(false);
1128 this.binding.hostnameLayout.setError(null);
1129 }
1130 if (this.binding.portLayout != exception) {
1131 this.binding.portLayout.setErrorEnabled(false);
1132 this.binding.portLayout.setError(null);
1133 }
1134 }
1135
1136 private void showDeletePgpDialog() {
1137 AlertDialog.Builder builder = new AlertDialog.Builder(this);
1138 builder.setTitle(R.string.unpublish_pgp);
1139 builder.setMessage(R.string.unpublish_pgp_message);
1140 builder.setNegativeButton(R.string.cancel, null);
1141 builder.setPositiveButton(R.string.confirm, (dialogInterface, i) -> {
1142 mAccount.setPgpSignId(0);
1143 mAccount.unsetPgpSignature();
1144 xmppConnectionService.databaseBackend.updateAccount(mAccount);
1145 xmppConnectionService.sendPresence(mAccount);
1146 refreshUiReal();
1147 });
1148 builder.create().show();
1149 }
1150
1151 private void showOsOptimizationWarning(boolean showBatteryWarning, boolean showDataSaverWarning) {
1152 this.binding.osOptimization.setVisibility(showBatteryWarning || showDataSaverWarning ? View.VISIBLE : View.GONE);
1153 if (showDataSaverWarning) {
1154 this.binding.osOptimizationHeadline.setText(R.string.data_saver_enabled);
1155 this.getmDisableOsOptimizationsBody.setText(R.string.data_saver_enabled_explained);
1156 this.mDisableOsOptimizationsButton.setText(R.string.allow);
1157 this.mDisableOsOptimizationsButton.setOnClickListener(v -> {
1158 Intent intent = new Intent(Settings.ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS);
1159 Uri uri = Uri.parse("package:" + getPackageName());
1160 intent.setData(uri);
1161 try {
1162 startActivityForResult(intent, REQUEST_DATA_SAVER);
1163 } catch (ActivityNotFoundException e) {
1164 Toast.makeText(EditAccountActivity.this, R.string.device_does_not_support_data_saver, Toast.LENGTH_SHORT).show();
1165 }
1166 });
1167 } else if (showBatteryWarning) {
1168 this.mDisableOsOptimizationsButton.setText(R.string.disable);
1169 this.binding.osOptimizationHeadline.setText(R.string.battery_optimizations_enabled);
1170 this.getmDisableOsOptimizationsBody.setText(R.string.battery_optimizations_enabled_explained);
1171 this.mDisableOsOptimizationsButton.setOnClickListener(v -> {
1172 Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1173 Uri uri = Uri.parse("package:" + getPackageName());
1174 intent.setData(uri);
1175 try {
1176 startActivityForResult(intent, REQUEST_BATTERY_OP);
1177 } catch (ActivityNotFoundException e) {
1178 Toast.makeText(EditAccountActivity.this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
1179 }
1180 });
1181 }
1182 }
1183
1184 public void showWipePepDialog() {
1185 Builder builder = new Builder(this);
1186 builder.setTitle(getString(R.string.clear_other_devices));
1187 builder.setIconAttribute(android.R.attr.alertDialogIcon);
1188 builder.setMessage(getString(R.string.clear_other_devices_desc));
1189 builder.setNegativeButton(getString(R.string.cancel), null);
1190 builder.setPositiveButton(getString(R.string.accept),
1191 (dialog, which) -> mAccount.getAxolotlService().wipeOtherPepDevices());
1192 builder.create().show();
1193 }
1194
1195 private void editMamPrefs() {
1196 this.mFetchingMamPrefsToast = Toast.makeText(this, R.string.fetching_mam_prefs, Toast.LENGTH_LONG);
1197 this.mFetchingMamPrefsToast.show();
1198 xmppConnectionService.fetchMamPreferences(mAccount, this);
1199 }
1200
1201 @Override
1202 public void onKeyStatusUpdated(AxolotlService.FetchStatus report) {
1203 refreshUi();
1204 }
1205
1206 @Override
1207 public void onCaptchaRequested(final Account account, final String id, final Data data, final Bitmap captcha) {
1208 runOnUiThread(() -> {
1209 if (mCaptchaDialog != null && mCaptchaDialog.isShowing()) {
1210 mCaptchaDialog.dismiss();
1211 }
1212 final Builder builder = new Builder(EditAccountActivity.this);
1213 final View view = getLayoutInflater().inflate(R.layout.captcha, null);
1214 final ImageView imageView = view.findViewById(R.id.captcha);
1215 final EditText input = view.findViewById(R.id.input);
1216 imageView.setImageBitmap(captcha);
1217
1218 builder.setTitle(getString(R.string.captcha_required));
1219 builder.setView(view);
1220
1221 builder.setPositiveButton(getString(R.string.ok),
1222 (dialog, which) -> {
1223 String rc = input.getText().toString();
1224 data.put("username", account.getUsername());
1225 data.put("password", account.getPassword());
1226 data.put("ocr", rc);
1227 data.submit();
1228
1229 if (xmppConnectionServiceBound) {
1230 xmppConnectionService.sendCreateAccountWithCaptchaPacket(account, id, data);
1231 }
1232 });
1233 builder.setNegativeButton(getString(R.string.cancel), (dialog, which) -> {
1234 if (xmppConnectionService != null) {
1235 xmppConnectionService.sendCreateAccountWithCaptchaPacket(account, null, null);
1236 }
1237 });
1238
1239 builder.setOnCancelListener(dialog -> {
1240 if (xmppConnectionService != null) {
1241 xmppConnectionService.sendCreateAccountWithCaptchaPacket(account, null, null);
1242 }
1243 });
1244 mCaptchaDialog = builder.create();
1245 mCaptchaDialog.show();
1246 input.requestFocus();
1247 });
1248 }
1249
1250 public void onShowErrorToast(final int resId) {
1251 runOnUiThread(() -> Toast.makeText(EditAccountActivity.this, resId, Toast.LENGTH_SHORT).show());
1252 }
1253
1254 @Override
1255 public void onPreferencesFetched(final Element prefs) {
1256 runOnUiThread(() -> {
1257 if (mFetchingMamPrefsToast != null) {
1258 mFetchingMamPrefsToast.cancel();
1259 }
1260 Builder builder = new Builder(EditAccountActivity.this);
1261 builder.setTitle(R.string.server_side_mam_prefs);
1262 String defaultAttr = prefs.getAttribute("default");
1263 final List<String> defaults = Arrays.asList("never", "roster", "always");
1264 final AtomicInteger choice = new AtomicInteger(Math.max(0, defaults.indexOf(defaultAttr)));
1265 builder.setSingleChoiceItems(R.array.mam_prefs, choice.get(), (dialog, which) -> choice.set(which));
1266 builder.setNegativeButton(R.string.cancel, null);
1267 builder.setPositiveButton(R.string.ok, (dialog, which) -> {
1268 prefs.setAttribute("default", defaults.get(choice.get()));
1269 xmppConnectionService.pushMamPreferences(mAccount, prefs);
1270 });
1271 builder.create().show();
1272 });
1273 }
1274
1275 @Override
1276 public void onPreferencesFetchFailed() {
1277 runOnUiThread(() -> {
1278 if (mFetchingMamPrefsToast != null) {
1279 mFetchingMamPrefsToast.cancel();
1280 }
1281 Toast.makeText(EditAccountActivity.this, R.string.unable_to_fetch_mam_prefs, Toast.LENGTH_LONG).show();
1282 });
1283 }
1284
1285 @Override
1286 public void OnUpdateBlocklist(Status status) {
1287 refreshUi();
1288 }
1289}