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