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