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