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