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 deleteAccount = menu.findItem(R.id.action_delete_account);
680 final MenuItem renewCertificate = menu.findItem(R.id.action_renew_certificate);
681 final MenuItem mamPrefs = menu.findItem(R.id.action_mam_prefs);
682 final MenuItem changePresence = menu.findItem(R.id.action_change_presence);
683 final MenuItem share = menu.findItem(R.id.action_share);
684 renewCertificate.setVisible(mAccount != null && mAccount.getPrivateKeyAlias() != null);
685
686 share.setVisible(mAccount != null && !mInitMode);
687
688 if (mAccount != null && mAccount.isOnlineAndConnected()) {
689 if (!mAccount.getXmppConnection().getFeatures().blocking()) {
690 showBlocklist.setVisible(false);
691 }
692
693 if (!mAccount.getXmppConnection().getFeatures().register()) {
694 changePassword.setVisible(false);
695 deleteAccount.setVisible(false);
696 }
697 mamPrefs.setVisible(mAccount.getXmppConnection().getFeatures().mam());
698 changePresence.setVisible(!mInitMode);
699 } else {
700 showBlocklist.setVisible(false);
701 showMoreInfo.setVisible(false);
702 changePassword.setVisible(false);
703 deleteAccount.setVisible(false);
704 mamPrefs.setVisible(false);
705 changePresence.setVisible(false);
706 }
707 return super.onCreateOptionsMenu(menu);
708 }
709
710 @Override
711 public boolean onPrepareOptionsMenu(Menu menu) {
712 final MenuItem showMoreInfo = menu.findItem(R.id.action_server_info_show_more);
713 if (showMoreInfo.isVisible()) {
714 showMoreInfo.setChecked(binding.serverInfoMore.getVisibility() == View.VISIBLE);
715 }
716 return super.onPrepareOptionsMenu(menu);
717 }
718
719 @Override
720 protected void onStart() {
721 super.onStart();
722 final Intent intent = getIntent();
723 final int theme = findTheme();
724 if (this.mTheme != theme) {
725 recreate();
726 } else if (intent != null) {
727 try {
728 this.jidToEdit = Jid.ofEscaped(intent.getStringExtra("jid"));
729 } catch (final IllegalArgumentException | NullPointerException ignored) {
730 this.jidToEdit = null;
731 }
732 final Uri data = intent.getData();
733 final XmppUri xmppUri = data == null ? null : new XmppUri(data);
734 final boolean scanned = intent.getBooleanExtra("scanned", false);
735 if (jidToEdit != null && xmppUri != null && xmppUri.hasFingerprints()) {
736 if (scanned) {
737 if (xmppConnectionServiceBound) {
738 processFingerprintVerification(xmppUri, false);
739 } else {
740 this.pendingUri = xmppUri;
741 }
742 } else {
743 displayVerificationWarningDialog(xmppUri);
744 }
745 }
746 boolean init = intent.getBooleanExtra("init", false);
747 boolean openedFromNotification = intent.getBooleanExtra(EXTRA_OPENED_FROM_NOTIFICATION, false);
748 Log.d(Config.LOGTAG, "extras " + intent.getExtras());
749 this.mForceRegister = intent.hasExtra(EXTRA_FORCE_REGISTER) ? intent.getBooleanExtra(EXTRA_FORCE_REGISTER, false) : null;
750 Log.d(Config.LOGTAG, "force register=" + mForceRegister);
751 this.mInitMode = init || this.jidToEdit == null;
752 this.messageFingerprint = intent.getStringExtra("fingerprint");
753 if (!mInitMode) {
754 this.binding.accountRegisterNew.setVisibility(View.GONE);
755 setTitle(getString(R.string.account_details));
756 configureActionBar(getSupportActionBar(), !openedFromNotification);
757 } else {
758 this.binding.avater.setVisibility(View.GONE);
759 configureActionBar(getSupportActionBar(), !(init && Config.MAGIC_CREATE_DOMAIN == null));
760 if (mForceRegister != null) {
761 if (mForceRegister) {
762 setTitle(R.string.register_new_account);
763 } else {
764 setTitle(R.string.add_existing_account);
765 }
766 } else {
767 setTitle(R.string.action_add_account);
768 }
769 }
770 }
771 SharedPreferences preferences = getPreferences();
772 mUseTor = preferences.getBoolean("use_tor", getResources().getBoolean(R.bool.use_tor));
773 this.mShowOptions = mUseTor || preferences.getBoolean("show_connection_options", getResources().getBoolean(R.bool.show_connection_options));
774 this.binding.namePort.setVisibility(mShowOptions ? View.VISIBLE : View.GONE);
775 if (mForceRegister != null) {
776 this.binding.accountRegisterNew.setVisibility(View.GONE);
777 }
778 if (intent.getBooleanExtra("snikket", false)) {
779 this.binding.accountJidLayout.setHint("Snikket Address");
780 }
781 }
782
783 private void displayVerificationWarningDialog(final XmppUri xmppUri) {
784 AlertDialog.Builder builder = new AlertDialog.Builder(this);
785 builder.setTitle(R.string.verify_omemo_keys);
786 View view = getLayoutInflater().inflate(R.layout.dialog_verify_fingerprints, null);
787 final CheckBox isTrustedSource = view.findViewById(R.id.trusted_source);
788 TextView warning = view.findViewById(R.id.warning);
789 warning.setText(R.string.verifying_omemo_keys_trusted_source_account);
790 builder.setView(view);
791 builder.setPositiveButton(R.string.continue_btn, (dialog, which) -> {
792 if (isTrustedSource.isChecked()) {
793 processFingerprintVerification(xmppUri, false);
794 } else {
795 finish();
796 }
797 });
798 builder.setNegativeButton(R.string.cancel, (dialog, which) -> finish());
799 AlertDialog dialog = builder.create();
800 dialog.setCanceledOnTouchOutside(false);
801 dialog.setOnCancelListener(d -> finish());
802 dialog.show();
803 }
804
805 @Override
806 public void onNewIntent(final Intent intent) {
807 super.onNewIntent(intent);
808 if (intent != null && intent.getData() != null) {
809 final XmppUri uri = new XmppUri(intent.getData());
810 if (xmppConnectionServiceBound) {
811 processFingerprintVerification(uri, false);
812 } else {
813 this.pendingUri = uri;
814 }
815 }
816 }
817
818 @Override
819 public void onSaveInstanceState(@NonNull final Bundle savedInstanceState) {
820 if (mAccount != null) {
821 savedInstanceState.putString("account", mAccount.getJid().asBareJid().toEscapedString());
822 savedInstanceState.putBoolean("initMode", mInitMode);
823 savedInstanceState.putBoolean("showMoreTable", binding.serverInfoMore.getVisibility() == View.VISIBLE);
824 }
825 super.onSaveInstanceState(savedInstanceState);
826 }
827
828 protected void onBackendConnected() {
829 boolean init = true;
830 if (mSavedInstanceAccount != null) {
831 try {
832 this.mAccount = xmppConnectionService.findAccountByJid(Jid.ofEscaped(mSavedInstanceAccount));
833 this.mInitMode = mSavedInstanceInit;
834 init = false;
835 } catch (IllegalArgumentException e) {
836 this.mAccount = null;
837 }
838
839 } else if (this.jidToEdit != null) {
840 this.mAccount = xmppConnectionService.findAccountByJid(jidToEdit);
841 }
842
843 if (mAccount != null) {
844 this.mInitMode |= this.mAccount.isOptionSet(Account.OPTION_REGISTER);
845 this.mUsernameMode |= mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE) && mAccount.isOptionSet(Account.OPTION_REGISTER);
846 if (mPendingFingerprintVerificationUri != null) {
847 processFingerprintVerification(mPendingFingerprintVerificationUri, false);
848 mPendingFingerprintVerificationUri = null;
849 }
850 updateAccountInformation(init);
851 }
852
853
854 if (Config.MAGIC_CREATE_DOMAIN == null && this.xmppConnectionService.getAccounts().size() == 0) {
855 this.binding.cancelButton.setEnabled(false);
856 }
857 if (mUsernameMode) {
858 this.binding.accountJidLayout.setHint(getString(R.string.username_hint));
859 } else {
860 final KnownHostsAdapter mKnownHostsAdapter = new KnownHostsAdapter(this,
861 R.layout.simple_list_item,
862 xmppConnectionService.getKnownHosts());
863 this.binding.accountJid.setAdapter(mKnownHostsAdapter);
864 }
865
866 if (pendingUri != null) {
867 processFingerprintVerification(pendingUri, false);
868 pendingUri = null;
869 }
870 updatePortLayout();
871 updateSaveButton();
872 invalidateOptionsMenu();
873 }
874
875 private String getUserModeDomain() {
876 if (mAccount != null && mAccount.getJid().getDomain() != null) {
877 return mAccount.getServer();
878 } else {
879 return Config.DOMAIN_LOCK;
880 }
881 }
882
883 @Override
884 public boolean onOptionsItemSelected(final MenuItem item) {
885 if (MenuDoubleTabUtil.shouldIgnoreTap()) {
886 return false;
887 }
888 switch (item.getItemId()) {
889 case android.R.id.home:
890 deleteAccountAndReturnIfNecessary();
891 break;
892 case R.id.action_show_block_list:
893 final Intent showBlocklistIntent = new Intent(this, BlocklistActivity.class);
894 showBlocklistIntent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toEscapedString());
895 startActivity(showBlocklistIntent);
896 break;
897 case R.id.action_server_info_show_more:
898 changeMoreTableVisibility(!item.isChecked());
899 break;
900 case R.id.action_share_barcode:
901 shareBarcode();
902 break;
903 case R.id.action_share_http:
904 shareLink(true);
905 break;
906 case R.id.action_share_uri:
907 shareLink(false);
908 break;
909 case R.id.action_change_password_on_server:
910 gotoChangePassword(null);
911 break;
912 case R.id.action_delete_account:
913 deleteAccount();
914 break;
915 case R.id.action_mam_prefs:
916 editMamPrefs();
917 break;
918 case R.id.action_renew_certificate:
919 renewCertificate();
920 break;
921 case R.id.action_change_presence:
922 changePresence();
923 break;
924 }
925 return super.onOptionsItemSelected(item);
926 }
927
928 private void deleteAccount() {
929 this.deleteAccount(mAccount,()->{
930 finish();
931 });
932 }
933
934 private boolean inNeedOfSaslAccept() {
935 return mAccount != null && mAccount.getLastErrorStatus() == Account.State.DOWNGRADE_ATTACK && mAccount.getPinnedMechanismPriority() >= 0 && !accountInfoEdited();
936 }
937
938 private void shareBarcode() {
939 Intent intent = new Intent(Intent.ACTION_SEND);
940 intent.putExtra(Intent.EXTRA_STREAM, BarcodeProvider.getUriForAccount(this, mAccount));
941 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
942 intent.setType("image/png");
943 startActivity(Intent.createChooser(intent, getText(R.string.share_with)));
944 }
945
946 private void changeMoreTableVisibility(boolean visible) {
947 binding.serverInfoMore.setVisibility(visible ? View.VISIBLE : View.GONE);
948 }
949
950 private void gotoChangePassword(String newPassword) {
951 this.newPassword = newPassword;
952 KeyguardManager keyguardManager = (KeyguardManager) this.getSystemService(Context.KEYGUARD_SERVICE);
953 Intent credentialsIntent = keyguardManager.createConfirmDeviceCredentialIntent("Unlock required", "Please unlock in order to change your password");
954 if (credentialsIntent == null) {
955 openChangePassword(false);
956 } else {
957 startActivityForResult(credentialsIntent, REQUEST_UNLOCK);
958 }
959 }
960
961 private void openChangePassword(boolean didUnlock) {
962 final Intent changePasswordIntent = new Intent(this, ChangePasswordActivity.class);
963 changePasswordIntent.putExtra(EXTRA_ACCOUNT, mAccount.getJid().toEscapedString());
964 changePasswordIntent.putExtra("did_unlock", didUnlock);
965 if (newPassword != null) {
966 changePasswordIntent.putExtra("password", newPassword);
967 }
968 this.newPassword = null;
969 startActivity(changePasswordIntent);
970 }
971
972 private void renewCertificate() {
973 KeyChain.choosePrivateKeyAlias(this, this, null, null, null, -1, null);
974 }
975
976 private void changePresence() {
977 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
978 boolean manualStatus = sharedPreferences.getBoolean(SettingsActivity.MANUALLY_CHANGE_PRESENCE, getResources().getBoolean(R.bool.manually_change_presence));
979 AlertDialog.Builder builder = new AlertDialog.Builder(this);
980 final DialogPresenceBinding binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.dialog_presence, null, false);
981 String current = mAccount.getPresenceStatusMessage();
982 if (current != null && !current.trim().isEmpty()) {
983 binding.statusMessage.append(current);
984 }
985 setAvailabilityRadioButton(mAccount.getPresenceStatus(), binding);
986 binding.show.setVisibility(manualStatus ? View.VISIBLE : View.GONE);
987 List<PresenceTemplate> templates = xmppConnectionService.getPresenceTemplates(mAccount);
988 PresenceTemplateAdapter presenceTemplateAdapter = new PresenceTemplateAdapter(this, R.layout.simple_list_item, templates);
989 binding.statusMessage.setAdapter(presenceTemplateAdapter);
990 binding.statusMessage.setOnItemClickListener((parent, view, position, id) -> {
991 PresenceTemplate template = (PresenceTemplate) parent.getItemAtPosition(position);
992 setAvailabilityRadioButton(template.getStatus(), binding);
993 });
994 builder.setTitle(R.string.edit_status_message_title);
995 builder.setView(binding.getRoot());
996 builder.setNegativeButton(R.string.cancel, null);
997 builder.setPositiveButton(R.string.confirm, (dialog, which) -> {
998 PresenceTemplate template = new PresenceTemplate(getAvailabilityRadioButton(binding), binding.statusMessage.getText().toString().trim());
999 if (mAccount.getPgpId() != 0 && hasPgp()) {
1000 generateSignature(null, template);
1001 } else {
1002 xmppConnectionService.changeStatus(mAccount, template, null);
1003 }
1004 });
1005 builder.create().show();
1006 }
1007
1008 private void generateSignature(Intent intent, PresenceTemplate template) {
1009 xmppConnectionService.getPgpEngine().generateSignature(intent, mAccount, template.getStatusMessage(), new UiCallback<String>() {
1010 @Override
1011 public void success(String signature) {
1012 xmppConnectionService.changeStatus(mAccount, template, signature);
1013 }
1014
1015 @Override
1016 public void error(int errorCode, String object) {
1017
1018 }
1019
1020 @Override
1021 public void userInputRequired(PendingIntent pi, String object) {
1022 mPendingPresenceTemplate.push(template);
1023 try {
1024 startIntentSenderForResult(pi.getIntentSender(), REQUEST_CHANGE_STATUS, null, 0, 0, 0);
1025 } catch (final IntentSender.SendIntentException ignored) {
1026 }
1027 }
1028 });
1029 }
1030
1031 @Override
1032 public void alias(String alias) {
1033 if (alias != null) {
1034 xmppConnectionService.updateKeyInAccount(mAccount, alias);
1035 }
1036 }
1037
1038 void showColorDialog() {
1039 AlertDialog.Builder builder = new AlertDialog.Builder(this);
1040 final ColorPickerView picker = new ColorPickerView(this);
1041
1042 if (mAccount != null) picker.setColor(mAccount.getColor(isDarkTheme()));
1043 picker.showAlpha(true);
1044 picker.showHex(true);
1045 picker.showPreview(true);
1046 builder
1047 .setTitle(null)
1048 .setView(picker)
1049 .setPositiveButton(R.string.ok, (dialog, which) -> {
1050 final int color = picker.getColor();
1051 binding.colorPreview.setBackgroundColor(color);
1052 updateSaveButton();
1053 })
1054 .setNegativeButton(R.string.cancel, (dialog, which) -> {});
1055 builder.show();
1056 }
1057
1058 private void updateAccountInformation(boolean init) {
1059 if (init) {
1060 this.binding.accountJid.getEditableText().clear();
1061 if (mUsernameMode) {
1062 this.binding.accountJid.getEditableText().append(this.mAccount.getJid().getEscapedLocal());
1063 } else {
1064 this.binding.accountJid.getEditableText().append(this.mAccount.getJid().asBareJid().toEscapedString());
1065 }
1066 this.binding.accountPassword.getEditableText().clear();
1067 this.binding.accountPassword.getEditableText().append(this.mAccount.getPassword());
1068 this.binding.hostname.setText("");
1069 this.binding.hostname.getEditableText().append(this.mAccount.getHostname());
1070 this.binding.port.setText("");
1071 this.binding.port.getEditableText().append(String.valueOf(this.mAccount.getPort()));
1072 this.binding.namePort.setVisibility(mShowOptions ? View.VISIBLE : View.GONE);
1073
1074 }
1075
1076 if (!mInitMode && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
1077 this.binding.accountPassword.setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_NO);
1078 }
1079
1080 final boolean editable = !mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY) && !mAccount.isOptionSet(Account.OPTION_FIXED_USERNAME) && QuickConversationsService.isConversations();
1081 this.binding.accountJid.setEnabled(editable);
1082 this.binding.accountJid.setFocusable(editable);
1083 this.binding.accountJid.setFocusableInTouchMode(editable);
1084 this.binding.accountJid.setCursorVisible(editable);
1085
1086
1087 final String displayName = mAccount.getDisplayName();
1088 updateDisplayName(displayName);
1089
1090 if (xmppConnectionService != null && xmppConnectionService.getAccounts().size() > 1) {
1091 binding.accountColorBox.setVisibility(View.VISIBLE);
1092 binding.colorPreview.setBackgroundColor(mAccount.getColor(isDarkTheme()));
1093 binding.quietHoursBox.setVisibility(View.VISIBLE);
1094 } else {
1095 binding.accountColorBox.setVisibility(View.GONE);
1096 binding.quietHoursBox.setVisibility(View.GONE);
1097 }
1098
1099 final boolean togglePassword = mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE) || !mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
1100 final boolean editPassword = !mAccount.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY) || mAccount.getLastErrorStatus() == Account.State.UNAUTHORIZED;
1101
1102 this.binding.accountPasswordLayout.setPasswordVisibilityToggleEnabled(togglePassword);
1103
1104 this.binding.accountPassword.setFocusable(editPassword);
1105 this.binding.accountPassword.setFocusableInTouchMode(editPassword);
1106 this.binding.accountPassword.setCursorVisible(editPassword);
1107 this.binding.accountPassword.setEnabled(editPassword);
1108
1109 if (!mInitMode) {
1110 this.binding.avater.setVisibility(View.VISIBLE);
1111 AvatarWorkerTask.loadAvatar(mAccount, binding.avater, R.dimen.avatar_on_details_screen_size);
1112 } else {
1113 this.binding.avater.setVisibility(View.GONE);
1114 }
1115 this.binding.accountRegisterNew.setChecked(this.mAccount.isOptionSet(Account.OPTION_REGISTER));
1116 if (this.mAccount.isOptionSet(Account.OPTION_MAGIC_CREATE)) {
1117 if (this.mAccount.isOptionSet(Account.OPTION_REGISTER)) {
1118 ActionBar actionBar = getSupportActionBar();
1119 if (actionBar != null) {
1120 actionBar.setTitle(R.string.create_account);
1121 }
1122 }
1123 this.binding.accountRegisterNew.setVisibility(View.GONE);
1124 } else if (this.mAccount.isOptionSet(Account.OPTION_REGISTER) && mForceRegister == null) {
1125 this.binding.accountRegisterNew.setVisibility(View.VISIBLE);
1126 } else {
1127 this.binding.accountRegisterNew.setVisibility(View.GONE);
1128 }
1129 if (this.mAccount.isOnlineAndConnected() && !this.mFetchingAvatar) {
1130 Features features = this.mAccount.getXmppConnection().getFeatures();
1131 this.binding.stats.setVisibility(View.VISIBLE);
1132 boolean showBatteryWarning = isOptimizingBattery();
1133 boolean showDataSaverWarning = isAffectedByDataSaver();
1134 showOsOptimizationWarning(showBatteryWarning, showDataSaverWarning);
1135 this.binding.sessionEst.setText(UIHelper.readableTimeDifferenceFull(this, this.mAccount.getXmppConnection()
1136 .getLastSessionEstablished()));
1137 if (features.rosterVersioning()) {
1138 this.binding.serverInfoRosterVersion.setText(R.string.server_info_available);
1139 } else {
1140 this.binding.serverInfoRosterVersion.setText(R.string.server_info_unavailable);
1141 }
1142 if (features.carbons()) {
1143 this.binding.serverInfoCarbons.setText(R.string.server_info_available);
1144 } else {
1145 this.binding.serverInfoCarbons.setText(R.string.server_info_unavailable);
1146 }
1147 if (features.mam()) {
1148 this.binding.serverInfoMam.setText(R.string.server_info_available);
1149 } else {
1150 this.binding.serverInfoMam.setText(R.string.server_info_unavailable);
1151 }
1152 if (features.csi()) {
1153 this.binding.serverInfoCsi.setText(R.string.server_info_available);
1154 } else {
1155 this.binding.serverInfoCsi.setText(R.string.server_info_unavailable);
1156 }
1157 if (features.blocking()) {
1158 this.binding.serverInfoBlocking.setText(R.string.server_info_available);
1159 } else {
1160 this.binding.serverInfoBlocking.setText(R.string.server_info_unavailable);
1161 }
1162 if (features.sm()) {
1163 this.binding.serverInfoSm.setText(R.string.server_info_available);
1164 } else {
1165 this.binding.serverInfoSm.setText(R.string.server_info_unavailable);
1166 }
1167 if (features.externalServiceDiscovery()) {
1168 this.binding.serverInfoExternalService.setText(R.string.server_info_available);
1169 } else {
1170 this.binding.serverInfoExternalService.setText(R.string.server_info_unavailable);
1171 }
1172 if (features.pep()) {
1173 AxolotlService axolotlService = this.mAccount.getAxolotlService();
1174 if (axolotlService != null && axolotlService.isPepBroken()) {
1175 this.binding.serverInfoPep.setText(R.string.server_info_broken);
1176 } else if (features.pepPublishOptions() || features.pepOmemoWhitelisted()) {
1177 this.binding.serverInfoPep.setText(R.string.server_info_available);
1178 } else {
1179 this.binding.serverInfoPep.setText(R.string.server_info_partial);
1180 }
1181 } else {
1182 this.binding.serverInfoPep.setText(R.string.server_info_unavailable);
1183 }
1184 if (features.httpUpload(0)) {
1185 final long maxFileSize = features.getMaxHttpUploadSize();
1186 if (maxFileSize > 0) {
1187 this.binding.serverInfoHttpUpload.setText(UIHelper.filesizeToString(maxFileSize));
1188 } else {
1189 this.binding.serverInfoHttpUpload.setText(R.string.server_info_available);
1190 }
1191 } else {
1192 this.binding.serverInfoHttpUpload.setText(R.string.server_info_unavailable);
1193 }
1194
1195 this.binding.pushRow.setVisibility(xmppConnectionService.getPushManagementService().isStub() ? View.GONE : View.VISIBLE);
1196
1197 if (xmppConnectionService.getPushManagementService().available(mAccount)) {
1198 this.binding.serverInfoPush.setText(R.string.server_info_available);
1199 } else {
1200 this.binding.serverInfoPush.setText(R.string.server_info_unavailable);
1201 }
1202 final long pgpKeyId = this.mAccount.getPgpId();
1203 if (pgpKeyId != 0 && Config.supportOpenPgp()) {
1204 OnClickListener openPgp = view -> launchOpenKeyChain(pgpKeyId);
1205 OnClickListener delete = view -> showDeletePgpDialog();
1206 this.binding.pgpFingerprintBox.setVisibility(View.VISIBLE);
1207 this.binding.pgpFingerprint.setText(OpenPgpUtils.convertKeyIdToHex(pgpKeyId));
1208 this.binding.pgpFingerprint.setOnClickListener(openPgp);
1209 if ("pgp".equals(messageFingerprint)) {
1210 this.binding.pgpFingerprintDesc.setTextAppearance(this, R.style.TextAppearance_Conversations_Caption_Highlight);
1211 }
1212 this.binding.pgpFingerprintDesc.setOnClickListener(openPgp);
1213 this.binding.actionDeletePgp.setOnClickListener(delete);
1214 } else {
1215 this.binding.pgpFingerprintBox.setVisibility(View.GONE);
1216 }
1217 final String ownAxolotlFingerprint = this.mAccount.getAxolotlService().getOwnFingerprint();
1218 if (ownAxolotlFingerprint != null && Config.supportOmemo()) {
1219 this.binding.axolotlFingerprintBox.setVisibility(View.VISIBLE);
1220 if (ownAxolotlFingerprint.equals(messageFingerprint)) {
1221 this.binding.ownFingerprintDesc.setTextAppearance(this, R.style.TextAppearance_Conversations_Caption_Highlight);
1222 this.binding.ownFingerprintDesc.setText(R.string.omemo_fingerprint_selected_message);
1223 } else {
1224 this.binding.ownFingerprintDesc.setTextAppearance(this, R.style.TextAppearance_Conversations_Caption);
1225 this.binding.ownFingerprintDesc.setText(R.string.omemo_fingerprint);
1226 }
1227 this.binding.axolotlFingerprint.setText(CryptoHelper.prettifyFingerprint(ownAxolotlFingerprint.substring(2)));
1228 this.binding.actionCopyAxolotlToClipboard.setVisibility(View.VISIBLE);
1229 this.binding.actionCopyAxolotlToClipboard.setOnClickListener(v -> copyOmemoFingerprint(ownAxolotlFingerprint));
1230 } else {
1231 this.binding.axolotlFingerprintBox.setVisibility(View.GONE);
1232 }
1233 boolean hasKeys = false;
1234 binding.otherDeviceKeys.removeAllViews();
1235 for (XmppAxolotlSession session : mAccount.getAxolotlService().findOwnSessions()) {
1236 if (!session.getTrust().isCompromised()) {
1237 boolean highlight = session.getFingerprint().equals(messageFingerprint);
1238 addFingerprintRow(binding.otherDeviceKeys, session, highlight);
1239 hasKeys = true;
1240 }
1241 }
1242 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
1243 this.binding.otherDeviceKeysCard.setVisibility(View.VISIBLE);
1244 Set<Integer> otherDevices = mAccount.getAxolotlService().getOwnDeviceIds();
1245 if (otherDevices == null || otherDevices.isEmpty()) {
1246 binding.clearDevices.setVisibility(View.GONE);
1247 } else {
1248 binding.clearDevices.setVisibility(View.VISIBLE);
1249 }
1250 } else {
1251 this.binding.otherDeviceKeysCard.setVisibility(View.GONE);
1252 }
1253 } else {
1254 final TextInputLayout errorLayout;
1255 if (this.mAccount.errorStatus()) {
1256 if (this.mAccount.getStatus() == Account.State.UNAUTHORIZED || this.mAccount.getStatus() == Account.State.DOWNGRADE_ATTACK) {
1257 errorLayout = this.binding.accountPasswordLayout;
1258 } else if (mShowOptions
1259 && this.mAccount.getStatus() == Account.State.SERVER_NOT_FOUND
1260 && this.binding.hostname.getText().length() > 0) {
1261 errorLayout = this.binding.hostnameLayout;
1262 } else {
1263 errorLayout = this.binding.accountJidLayout;
1264 }
1265 errorLayout.setError(getString(this.mAccount.getStatus().getReadableId()));
1266 if (init || !accountInfoEdited()) {
1267 errorLayout.requestFocus();
1268 }
1269 } else {
1270 errorLayout = null;
1271 }
1272 removeErrorsOnAllBut(errorLayout);
1273 this.binding.stats.setVisibility(View.GONE);
1274 this.binding.otherDeviceKeysCard.setVisibility(View.GONE);
1275 }
1276 }
1277
1278 private void updateDisplayName(String displayName) {
1279 if (TextUtils.isEmpty(displayName)) {
1280 this.binding.yourName.setText(R.string.no_name_set_instructions);
1281 this.binding.yourName.setTextAppearance(this, R.style.TextAppearance_Conversations_Body1_Tertiary);
1282 } else {
1283 this.binding.yourName.setText(displayName);
1284 this.binding.yourName.setTextAppearance(this, R.style.TextAppearance_Conversations_Body1);
1285 }
1286 }
1287
1288 private void removeErrorsOnAllBut(TextInputLayout exception) {
1289 if (this.binding.accountJidLayout != exception) {
1290 this.binding.accountJidLayout.setErrorEnabled(false);
1291 this.binding.accountJidLayout.setError(null);
1292 }
1293 if (this.binding.accountPasswordLayout != exception) {
1294 this.binding.accountPasswordLayout.setErrorEnabled(false);
1295 this.binding.accountPasswordLayout.setError(null);
1296 }
1297 if (this.binding.hostnameLayout != exception) {
1298 this.binding.hostnameLayout.setErrorEnabled(false);
1299 this.binding.hostnameLayout.setError(null);
1300 }
1301 if (this.binding.portLayout != exception) {
1302 this.binding.portLayout.setErrorEnabled(false);
1303 this.binding.portLayout.setError(null);
1304 }
1305 }
1306
1307 private void showDeletePgpDialog() {
1308 AlertDialog.Builder builder = new AlertDialog.Builder(this);
1309 builder.setTitle(R.string.unpublish_pgp);
1310 builder.setMessage(R.string.unpublish_pgp_message);
1311 builder.setNegativeButton(R.string.cancel, null);
1312 builder.setPositiveButton(R.string.confirm, (dialogInterface, i) -> {
1313 mAccount.setPgpSignId(0);
1314 mAccount.unsetPgpSignature();
1315 xmppConnectionService.databaseBackend.updateAccount(mAccount);
1316 xmppConnectionService.sendPresence(mAccount);
1317 refreshUiReal();
1318 });
1319 builder.create().show();
1320 }
1321
1322 private void showOsOptimizationWarning(boolean showBatteryWarning, boolean showDataSaverWarning) {
1323 this.binding.osOptimization.setVisibility(showBatteryWarning || showDataSaverWarning ? View.VISIBLE : View.GONE);
1324 if (showDataSaverWarning && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
1325 this.binding.osOptimizationHeadline.setText(R.string.data_saver_enabled);
1326 this.binding.osOptimizationBody.setText(getString(R.string.data_saver_enabled_explained, getString(R.string.app_name)));
1327 this.binding.osOptimizationDisable.setText(R.string.allow);
1328 this.binding.osOptimizationDisable.setOnClickListener(v -> {
1329 Intent intent = new Intent(Settings.ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS);
1330 Uri uri = Uri.parse("package:" + getPackageName());
1331 intent.setData(uri);
1332 try {
1333 startActivityForResult(intent, REQUEST_DATA_SAVER);
1334 } catch (ActivityNotFoundException e) {
1335 Toast.makeText(EditAccountActivity.this, getString(R.string.device_does_not_support_data_saver, getString(R.string.app_name)), Toast.LENGTH_SHORT).show();
1336 }
1337 });
1338 } else if (showBatteryWarning && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
1339 this.binding.osOptimizationDisable.setText(R.string.disable);
1340 this.binding.osOptimizationHeadline.setText(R.string.battery_optimizations_enabled);
1341 this.binding.osOptimizationBody.setText(getString(R.string.battery_optimizations_enabled_explained, getString(R.string.app_name)));
1342 this.binding.osOptimizationDisable.setOnClickListener(v -> {
1343 Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1344 Uri uri = Uri.parse("package:" + getPackageName());
1345 intent.setData(uri);
1346 try {
1347 startActivityForResult(intent, REQUEST_BATTERY_OP);
1348 } catch (ActivityNotFoundException e) {
1349 Toast.makeText(EditAccountActivity.this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
1350 }
1351 });
1352 }
1353 }
1354
1355 public void showWipePepDialog() {
1356 Builder builder = new Builder(this);
1357 builder.setTitle(getString(R.string.clear_other_devices));
1358 builder.setIconAttribute(android.R.attr.alertDialogIcon);
1359 builder.setMessage(getString(R.string.clear_other_devices_desc));
1360 builder.setNegativeButton(getString(R.string.cancel), null);
1361 builder.setPositiveButton(getString(R.string.accept),
1362 (dialog, which) -> mAccount.getAxolotlService().wipeOtherPepDevices());
1363 builder.create().show();
1364 }
1365
1366 private void editMamPrefs() {
1367 this.mFetchingMamPrefsToast = Toast.makeText(this, R.string.fetching_mam_prefs, Toast.LENGTH_LONG);
1368 this.mFetchingMamPrefsToast.show();
1369 xmppConnectionService.fetchMamPreferences(mAccount, this);
1370 }
1371
1372 @Override
1373 public void onKeyStatusUpdated(AxolotlService.FetchStatus report) {
1374 refreshUi();
1375 }
1376
1377 @Override
1378 public void onCaptchaRequested(final Account account, final String id, final Data data, final Bitmap captcha) {
1379 runOnUiThread(() -> {
1380 if (mCaptchaDialog != null && mCaptchaDialog.isShowing()) {
1381 mCaptchaDialog.dismiss();
1382 }
1383 final Builder builder = new Builder(EditAccountActivity.this);
1384 final View view = getLayoutInflater().inflate(R.layout.captcha, null);
1385 final ImageView imageView = view.findViewById(R.id.captcha);
1386 final EditText input = view.findViewById(R.id.input);
1387 imageView.setImageBitmap(captcha);
1388
1389 builder.setTitle(getString(R.string.captcha_required));
1390 builder.setView(view);
1391
1392 builder.setPositiveButton(getString(R.string.ok),
1393 (dialog, which) -> {
1394 String rc = input.getText().toString();
1395 data.put("username", account.getUsername());
1396 data.put("password", account.getPassword());
1397 data.put("ocr", rc);
1398 data.submit();
1399
1400 if (xmppConnectionServiceBound) {
1401 xmppConnectionService.sendCreateAccountWithCaptchaPacket(account, id, data);
1402 }
1403 });
1404 builder.setNegativeButton(getString(R.string.cancel), (dialog, which) -> {
1405 if (xmppConnectionService != null) {
1406 xmppConnectionService.sendCreateAccountWithCaptchaPacket(account, null, null);
1407 }
1408 });
1409
1410 builder.setOnCancelListener(dialog -> {
1411 if (xmppConnectionService != null) {
1412 xmppConnectionService.sendCreateAccountWithCaptchaPacket(account, null, null);
1413 }
1414 });
1415 mCaptchaDialog = builder.create();
1416 mCaptchaDialog.show();
1417 input.requestFocus();
1418 });
1419 }
1420
1421 public void onShowErrorToast(final int resId) {
1422 runOnUiThread(() -> Toast.makeText(EditAccountActivity.this, resId, Toast.LENGTH_SHORT).show());
1423 }
1424
1425 @Override
1426 public void onPreferencesFetched(final Element prefs) {
1427 runOnUiThread(() -> {
1428 if (mFetchingMamPrefsToast != null) {
1429 mFetchingMamPrefsToast.cancel();
1430 }
1431 Builder builder = new Builder(EditAccountActivity.this);
1432 builder.setTitle(R.string.server_side_mam_prefs);
1433 String defaultAttr = prefs.getAttribute("default");
1434 final List<String> defaults = Arrays.asList("never", "roster", "always");
1435 final AtomicInteger choice = new AtomicInteger(Math.max(0, defaults.indexOf(defaultAttr)));
1436 builder.setSingleChoiceItems(R.array.mam_prefs, choice.get(), (dialog, which) -> choice.set(which));
1437 builder.setNegativeButton(R.string.cancel, null);
1438 builder.setPositiveButton(R.string.ok, (dialog, which) -> {
1439 prefs.setAttribute("default", defaults.get(choice.get()));
1440 xmppConnectionService.pushMamPreferences(mAccount, prefs);
1441 });
1442 builder.create().show();
1443 });
1444 }
1445
1446 @Override
1447 public void onPreferencesFetchFailed() {
1448 runOnUiThread(() -> {
1449 if (mFetchingMamPrefsToast != null) {
1450 mFetchingMamPrefsToast.cancel();
1451 }
1452 Toast.makeText(EditAccountActivity.this, R.string.unable_to_fetch_mam_prefs, Toast.LENGTH_LONG).show();
1453 });
1454 }
1455
1456 @Override
1457 public void OnUpdateBlocklist(Status status) {
1458 refreshUi();
1459 }
1460}