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