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