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