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