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