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