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