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