mirror of
https://github.com/samuelthomas2774/nxapi.git
synced 2026-03-22 02:14:10 -05:00
Compare commits
271 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
28109239a3 | ||
|
|
71be9c8795 | ||
|
|
c3506daad1 | ||
|
|
c5f86a718a | ||
|
|
10dbc366eb | ||
|
|
8cae29d035 | ||
|
|
e993706671 | ||
|
|
373a348d65 | ||
|
|
41f6182dc2 | ||
|
|
fbaa188e13 | ||
|
|
abf6fa9ca9 | ||
|
|
2de9ce365f | ||
|
|
d5723f9ea7 | ||
|
|
7569d44ca9 | ||
|
|
8b9b0cbe80 | ||
|
|
8e1f9bde1b | ||
|
|
a53721f27c | ||
|
|
a281729a18 | ||
|
|
c021f20ef6 | ||
|
|
b683dca8b4 | ||
|
|
aecf9556ef | ||
|
|
07691de7b5 | ||
|
|
7a2fe3d35c | ||
|
|
05b254e69c | ||
|
|
f59caa3d6f | ||
|
|
2e26ea2725 | ||
|
|
5ba004f9ab | ||
|
|
34e399932a | ||
|
|
af44a2cc7a | ||
|
|
ec202d1ff8 | ||
|
|
73feb930ac | ||
|
|
ff777a06ab | ||
|
|
be21d69a4c | ||
|
|
56086c0651 | ||
|
|
d3e3ecd280 | ||
|
|
116bae844a | ||
|
|
d00c988220 | ||
|
|
2ddac1619f | ||
|
|
3bfee7559f | ||
|
|
426f97ff6d | ||
|
|
fd08c4ddde | ||
|
|
b6490f9639 | ||
|
|
64b6a663e5 | ||
|
|
f7084107c6 | ||
|
|
c809722ca8 | ||
|
|
3657da89b6 | ||
|
|
3cd774b299 | ||
|
|
8d5981c8f7 | ||
|
|
4897aca3e6 | ||
|
|
ddaa7a5ba0 | ||
|
|
3746f76812 | ||
|
|
080d110d1f | ||
|
|
00ab5fc623 | ||
|
|
8492db43d9 | ||
|
|
706e41133d | ||
|
|
e9137a41c6 | ||
|
|
cd96ed7960 | ||
|
|
0f0f666ea6 | ||
|
|
4452947187 | ||
|
|
eb778f0c8e | ||
|
|
748f058d10 | ||
|
|
78b5d6748e | ||
|
|
b92dc5e310 | ||
|
|
fa82661911 | ||
|
|
9561a9523e | ||
|
|
9cb122c365 | ||
|
|
b63526e13c | ||
|
|
9339eb73fc | ||
|
|
e1e2a2223e | ||
|
|
4889b0d93e | ||
|
|
e6c97f2924 | ||
|
|
e55b8dc965 | ||
|
|
8cac7935f2 | ||
|
|
e00a0a6e3b | ||
|
|
57ce3c21de | ||
|
|
2959c923bb | ||
|
|
d482987231 | ||
|
|
4888544f11 | ||
|
|
059799164d | ||
|
|
90b520c444 | ||
|
|
9985e32d0b | ||
|
|
7666191600 | ||
|
|
8a05e4c6ef | ||
|
|
8e30643bc8 | ||
|
|
a02d2f5553 | ||
|
|
018b3b121f | ||
|
|
dd73e31df5 | ||
|
|
cdf175a3bd | ||
|
|
93f0c56340 | ||
|
|
17e61eada5 | ||
|
|
bde495fcce | ||
|
|
83456275fb | ||
|
|
6f989104c7 | ||
|
|
8c911d5bca | ||
|
|
859ecea027 | ||
|
|
589a5ea220 | ||
|
|
88068dcf89 | ||
|
|
02faac2782 | ||
|
|
445093e58a | ||
|
|
c966b7309e | ||
|
|
c3a53a7cfa | ||
|
|
6d225b6552 | ||
|
|
8276b70de7 | ||
|
|
bd908c130e | ||
|
|
f5773419e9 | ||
|
|
dfc8ad3e83 | ||
|
|
4df9a4f495 | ||
|
|
a5e98e807b | ||
|
|
90e41c837b | ||
|
|
e3937ae843 | ||
|
|
865f55780a | ||
|
|
a12fdb2878 | ||
|
|
9a56d04ba1 | ||
|
|
6be0ca949a | ||
|
|
3e0ba063f8 | ||
|
|
ff3f8e1704 | ||
|
|
4b5f1898eb | ||
|
|
38db4a0b3a | ||
|
|
1ec08c02f4 | ||
|
|
e697f86359 | ||
|
|
6fd0f3f2f1 | ||
|
|
b5d86bf2d6 | ||
|
|
597d3ba554 | ||
|
|
b7afcfb175 | ||
|
|
01fdfb1fec | ||
|
|
98af75441b | ||
|
|
6ee7a9382a | ||
|
|
cbf6e257be | ||
|
|
f122ef8c92 | ||
|
|
64bc2be2ec | ||
|
|
0445ab46af | ||
|
|
5ef9101c1e | ||
|
|
6656ca97e0 | ||
|
|
0dcf1e3598 | ||
|
|
f35f2ab549 | ||
|
|
58413a0024 | ||
|
|
c5c870fe5c | ||
|
|
5d26922660 | ||
|
|
0d2ec91019 | ||
|
|
f07cd5a2e7 | ||
|
|
cb3bdda283 | ||
|
|
2680b03c46 | ||
|
|
c5d8d25334 | ||
|
|
2cbfdc5e04 | ||
|
|
69afbc6d69 | ||
|
|
f043d8ebb0 | ||
|
|
c7514a0635 | ||
|
|
cd6f614a99 | ||
|
|
fbc1bc1682 | ||
|
|
eda75b4dee | ||
|
|
584f0e2d89 | ||
|
|
7bdf9f578a | ||
|
|
0a9e5d859d | ||
|
|
d147c2a5e8 | ||
|
|
0457746e5e | ||
|
|
d7a64b9807 | ||
|
|
10a6784fa7 | ||
|
|
bb45ee39f5 | ||
|
|
dfb2a3eea7 | ||
|
|
7b838e9b3e | ||
|
|
419ac22774 | ||
|
|
3e1bd2621a | ||
|
|
826ee51a68 | ||
|
|
3c6025790e | ||
|
|
5bd62cd576 | ||
|
|
d1785ee1fc | ||
|
|
865a09ee99 | ||
|
|
8ba5a787cf | ||
|
|
991a5f7a7c | ||
|
|
72c2927de8 | ||
|
|
0af48a18ae | ||
|
|
62d1982193 | ||
|
|
82021bb9c4 | ||
|
|
d60b0f260f | ||
|
|
e395a80431 | ||
|
|
b689da3426 | ||
|
|
3c43019e00 | ||
|
|
2635632e97 | ||
|
|
8e5e42dfa4 | ||
|
|
c145a1af35 | ||
|
|
cf5192a9da | ||
|
|
fcbf6f4f7d | ||
|
|
4acebd1608 | ||
|
|
1af368d80e | ||
|
|
b306d1d786 | ||
|
|
c3016f9889 | ||
|
|
49b6d0dce2 | ||
|
|
b16f77d13e | ||
|
|
4e45c3b339 | ||
|
|
99a511080a | ||
|
|
0aad3e3ea6 | ||
|
|
9a8edb5bff | ||
|
|
f8ab372171 | ||
|
|
52a5ddba2d | ||
|
|
edfd55a7a9 | ||
|
|
79e0a5516f | ||
|
|
ce0fd9cf9b | ||
|
|
95c2664678 | ||
|
|
947c62214a | ||
|
|
ccbe3fb8dd | ||
|
|
681f9a5946 | ||
|
|
1d0664e84f | ||
|
|
4d0b708469 | ||
|
|
512a9a2b60 | ||
|
|
f6aa9a17ab | ||
|
|
8c4ba4dbc5 | ||
|
|
cde3f4c7a3 | ||
|
|
1518780b45 | ||
|
|
776a635b29 | ||
|
|
ed33fd2a32 | ||
|
|
30333dec8e | ||
|
|
ed63648ddf | ||
|
|
7b82af5c40 | ||
|
|
5379cdd805 | ||
|
|
28492f1dad | ||
|
|
32a5d98609 | ||
|
|
8a86db4196 | ||
|
|
e37830355a | ||
|
|
f418583382 | ||
|
|
5e563d7c05 | ||
|
|
66939d26fe | ||
|
|
36f84d563a | ||
|
|
bb093d6b22 | ||
|
|
2da7f4f66e | ||
|
|
6f6148fcad | ||
|
|
c6c8ff9d2d | ||
|
|
41f29328d9 | ||
|
|
ccf0951df5 | ||
|
|
9b038c76da | ||
|
|
a7406bd850 | ||
|
|
1d4781f4f6 | ||
|
|
af2535da20 | ||
|
|
8d745845a2 | ||
|
|
1272cd6b68 | ||
|
|
8c04ecde5f | ||
|
|
23dec3773f | ||
|
|
693fd5d312 | ||
|
|
82744fec54 | ||
|
|
b0603e1e82 | ||
|
|
b9b9f6a8d7 | ||
|
|
a661f91efb | ||
|
|
ecb7c578c9 | ||
|
|
b91b98060d | ||
|
|
4dc85dace9 | ||
|
|
f94bf1c221 | ||
|
|
912d976aa1 | ||
|
|
ac3100f40e | ||
|
|
ae94bd6a8e | ||
|
|
e235efebd5 | ||
|
|
9849abb8e2 | ||
|
|
76ad85ee09 | ||
|
|
b4a6eac7e4 | ||
|
|
ee73e5bc44 | ||
|
|
e4a1467d45 | ||
|
|
5d431a58d0 | ||
|
|
0b7e5b618f | ||
|
|
27e41f7735 | ||
|
|
4a9c0085f1 | ||
|
|
24a0d2bdc8 | ||
|
|
de44296d7b | ||
|
|
1ee984984c | ||
|
|
186c34b8fd | ||
|
|
dce5af6f57 | ||
|
|
76114452e4 | ||
|
|
6867b6be9d | ||
|
|
2914fcc76b | ||
|
|
67fb379e22 | ||
|
|
5c6f106b78 | ||
|
|
f658befb3b | ||
|
|
d3c4c2d1de | ||
|
|
788083b7f6 |
55
.github/ISSUE_TEMPLATE/bug.yml
vendored
Normal file
55
.github/ISSUE_TEMPLATE/bug.yml
vendored
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
name: Bug
|
||||
description: Report something that isn't working as expected
|
||||
|
||||
labels:
|
||||
- bug
|
||||
|
||||
body:
|
||||
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Please remember to search other issues before opening an issue, but make sure it is the same as the issue you have before commenting on other issues, for example make sure any error messages are the same.
|
||||
|
||||
Not all issues are bugs - some error messages may indicate a different problem, for example, the error code `ENOTFOUND` may mean there is a problem with your network. Make sure your Internet connection is working and there are no [known service issues](https://nxapi-status.fancy.org.uk).
|
||||
|
||||
Make sure you test the latest development build as the issue may have already been fixed: [macOS/Linux](https://gitlab.fancy.org.uk/samuel/nxapi/-/jobs/artifacts/main/browse/app?job=build-app), [Windows](https://gitlab.fancy.org.uk/samuel/nxapi/-/jobs/artifacts/main/browse/app?job=build-windows).
|
||||
|
||||
> [!IMPORTANT]
|
||||
> The latest release of nxapi no longer works due to changes by Nintendo. If you are using nxapi 1.6.1 or before and do not update to the latest development build you will see an error message from the f-generation API as client authentication is not sent.
|
||||
|
||||
- type: textarea
|
||||
id: what-you-did
|
||||
attributes:
|
||||
label: What did you try to do?
|
||||
description: |
|
||||
Describe the steps you took to reproduce the issue. You can upload screenshots or screen recordings. Please don't add links to files or take photos of your screen using a phone or camera.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: what-should-happen
|
||||
attributes:
|
||||
label: What should happen?
|
||||
description: |
|
||||
Describe what you expected to happen.
|
||||
|
||||
- type: textarea
|
||||
id: what-did-happen
|
||||
attributes:
|
||||
label: What did happen?
|
||||
description: |
|
||||
Describe what actually happened instead of what you expected. You can upload screenshots or screen recordings. Please don't add links to files or take photos of your screen using a phone or camera.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: other-information
|
||||
attributes:
|
||||
label: Other information
|
||||
description: |
|
||||
Include any other relevant information, such as when the problem started, or if it only happens sometimes, and information about your system such as your operating system and nxapi version.
|
||||
|
||||
You can upload log files from nxapi by selecting export logs in the help menu. On Windows/Linux, press the <kbd>Alt</kbd> key in the main window to temporarily show the application menus. This will generate a file containing nxapi's debug logs, which are stored on your computer for 14 days. Log files may contain sensitive information, but the export logs option encrypts the saved logs so only @samuelthomas2774 can read them. You can also use the `nxapi util log-archive` command to generate an encrypted log archive.
|
||||
validations:
|
||||
required: true
|
||||
15
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
15
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
blank_issues_enabled: true
|
||||
|
||||
contact_links:
|
||||
|
||||
- name: Discussions
|
||||
about: Suggest new features and ask questions.
|
||||
url: https://github.com/samuelthomas2774/nxapi/discussions
|
||||
|
||||
- name: Discord
|
||||
about: https://discord.com/invite/4D82rFkXRv
|
||||
url: https://discord.com/invite/4D82rFkXRv
|
||||
|
||||
- name: nxapi Service Status
|
||||
about: Check the status of services used by nxapi. Issues may take a few minutes to appear here.
|
||||
url: https://nxapi-status.fancy.org.uk
|
||||
|
|
@ -8,11 +8,18 @@ assignees:
|
|||
- samuelthomas2774
|
||||
|
||||
body:
|
||||
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
> [!IMPORTANT]
|
||||
> Discord now allows requesting to show the details or state field under the user's name, which allows showing the full title name instead of "Nintendo Switch"/"Nintendo Switch 2" for all titles, although this doesn't allow fully customising the activity name. It is no longer necessary add title configuration that only sets a custom Discord application.
|
||||
|
||||
- type: input
|
||||
id: title-name
|
||||
attributes:
|
||||
label: Title name
|
||||
description: The full name of the title, exactly as it appears on a Nintendo Switch console or Nintendo eShop. If you are requesting a custom Discord application for this title, this will be used as it's name.
|
||||
description: The full name of the title, exactly as it appears on a Nintendo Switch console or Nintendo eShop.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
|
|
@ -33,7 +40,7 @@ body:
|
|||
|
||||
If the title/s already has/have custom Discord configuration, you don't need to include all title IDs - just one to identify it. If the title hasn't been released yet and doesn't have a title ID, add a note in the other information section below, and the expected release date and links to Nintendo websites/Nintendo eShop NSUIDs.
|
||||
|
||||
Application title IDs are 16 hexadecimal digits, and should start with `0100` and end with `0000`, `2000`, `4000`, `6000`, `8000`, `a000`, `c000` or `e000`.
|
||||
Application title IDs are 16 hexadecimal digits, and should start with `0100` (Nintendo Switch) or `0400` (Nintendo Switch 2) and end with `0000`, `2000`, `4000`, `6000`, `8000`, `a000`, `c000` or `e000`.
|
||||
placeholder: |
|
||||
0100d2f00d5c0000 Nintendo Switch Sports
|
||||
01000ee017182000 Nintendo Switch Sports Online Play Test
|
||||
|
|
@ -49,13 +56,3 @@ body:
|
|||
Include any other relevant information, such as custom attributes that should be set for the title, or any changes that should be made to the existing configuration, or any other related titles that have/will be released.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: checkboxes
|
||||
id: review-checklist
|
||||
attributes:
|
||||
label: Review checklist
|
||||
options:
|
||||
- label: No other open issues related to this title exist (if any issues do exist, add a comment/reaction to those instead of opening a new issue)
|
||||
required: true
|
||||
- label: I am requesting a custom Discord application for this title - this title is a very popular game and/or has high ratings, is currently available for purchase (or will be soon) in most Nintendo eShop regions, and it would be useful for a number of users to have it's own Discord application (I don't have any strict guidelines for which titles should have custom Discord applications - tick if you think the title should have it's own Discord application - I just want to keep the list short so I don't have to create 100s of Discord applications)
|
||||
required: false
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ build:
|
|||
stage: build
|
||||
script:
|
||||
- npx tsc
|
||||
# Uses CI_COMMIT_TAG
|
||||
# Uses CI_COMMIT_TAG, NXAPI_AUTH_CLI_CLIENT_ID, NXAPI_AUTH_APP_CLIENT_ID
|
||||
- NODE_ENV=production npx rollup --config
|
||||
|
||||
- node bin/nxapi.js util validate-discord-titles
|
||||
|
|
@ -27,7 +27,9 @@ build:
|
|||
|
||||
build-docker:
|
||||
stage: build
|
||||
image: node:20-alpine
|
||||
before_script:
|
||||
- apk add docker git
|
||||
- docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" "$CI_REGISTRY"
|
||||
- |
|
||||
[ "$DH_REGISTRY_IMAGE" != "" ] && docker login -u "$DH_REGISTRY_USER" -p "$DH_REGISTRY_PASSWORD" "$DH_REGISTRY"
|
||||
|
|
@ -77,11 +79,8 @@ build-docker:
|
|||
docker tag "$CI_REGISTRY_IMAGE:ref-$CI_COMMIT_REF_SLUG" "$GH_REGISTRY_IMAGE:latest"
|
||||
docker push "$GH_REGISTRY_IMAGE:latest"
|
||||
fi
|
||||
tags:
|
||||
- docker
|
||||
only:
|
||||
variables:
|
||||
- $BUILD_DOCKER_IMAGE == "true"
|
||||
rules:
|
||||
- if: $BUILD_DOCKER_IMAGE == "true"
|
||||
cache:
|
||||
policy: pull
|
||||
|
||||
|
|
@ -90,7 +89,7 @@ build-app:
|
|||
script:
|
||||
- node resources/build/ci-package-json.js
|
||||
|
||||
- npx electron-builder build --macos zip:x64 zip:arm64 --linux deb snap appimage --publish never
|
||||
- npx electron-builder build --macos zip:x64 zip:arm64 --linux deb snap appimage deb:arm64 appimage:arm64 --publish never
|
||||
- mv dist/app/package app
|
||||
needs:
|
||||
- job: build
|
||||
|
|
@ -101,9 +100,8 @@ build-app:
|
|||
- app/mac/**/*
|
||||
- app/mac-arm64/**/*
|
||||
- app/linux-unpacked/**/*
|
||||
only:
|
||||
variables:
|
||||
- $BUILD_APP == "true"
|
||||
rules:
|
||||
- if: $BUILD_APP == "true"
|
||||
cache:
|
||||
paths:
|
||||
- node_modules/
|
||||
|
|
@ -124,9 +122,8 @@ build-windows:
|
|||
- app
|
||||
exclude:
|
||||
- app/win-unpacked/**/*
|
||||
only:
|
||||
variables:
|
||||
- $BUILD_WINDOWS_APP == "true"
|
||||
rules:
|
||||
- if: $BUILD_WINDOWS_APP == "true"
|
||||
cache:
|
||||
paths:
|
||||
- node_modules/
|
||||
|
|
@ -141,13 +138,8 @@ publish-npm:
|
|||
- npm --color="always" publish
|
||||
needs:
|
||||
- build
|
||||
only:
|
||||
refs:
|
||||
- /^v.*$/
|
||||
variables:
|
||||
- $NPM_TOKEN
|
||||
except:
|
||||
- branches
|
||||
rules:
|
||||
- if: $CI_COMMIT_TAG =~ /^v/ && $NPM_TOKEN
|
||||
cache:
|
||||
paths:
|
||||
- node_modules/
|
||||
|
|
@ -163,14 +155,8 @@ publish-gitlab:
|
|||
- npm --color="always" --registry=${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/npm/ publish
|
||||
needs:
|
||||
- build
|
||||
only:
|
||||
refs:
|
||||
- /^v.*$/
|
||||
variables:
|
||||
- $GITLAB_NPM_PUBLISH == "true"
|
||||
- $GITLAB_NPM_PACKAGE_NAME
|
||||
except:
|
||||
- branches
|
||||
rules:
|
||||
- if: $CI_COMMIT_TAG =~ /^v/ && $GITLAB_NPM_PUBLISH == "true" && $GITLAB_NPM_PACKAGE_NAME
|
||||
cache:
|
||||
paths:
|
||||
- node_modules/
|
||||
|
|
@ -186,15 +172,33 @@ publish-github:
|
|||
- npm --color="always" --registry=https://npm.pkg.github.com/ publish
|
||||
needs:
|
||||
- build
|
||||
only:
|
||||
refs:
|
||||
- /^v.*$/
|
||||
variables:
|
||||
- $GITHUB_REPOSITORY
|
||||
- $GITHUB_NPM_PACKAGE_NAME
|
||||
- $GITHUB_NPM_TOKEN
|
||||
except:
|
||||
- branches
|
||||
rules:
|
||||
- if: $CI_COMMIT_TAG =~ /^v/ && $GITHUB_NPM_REPOSITORY && $GITHUB_NPM_PACKAGE_NAME && $GITHUB_NPM_TOKEN
|
||||
cache:
|
||||
paths:
|
||||
- node_modules/
|
||||
policy: pull
|
||||
|
||||
publish-github-releases:
|
||||
stage: deploy
|
||||
image: alpine
|
||||
before_script:
|
||||
- apk add github-cli
|
||||
script:
|
||||
- gh release --repo "$GITHUB_REPOSITORY" view "$CI_COMMIT_TAG" --json id,url || gh release --repo "$GITHUB_REPOSITORY" create "$CI_COMMIT_TAG" --verify-tag --draft --generate-notes
|
||||
|
||||
- |
|
||||
gh release --repo "$GITHUB_REPOSITORY" upload "$CI_COMMIT_TAG" \
|
||||
"app/Nintendo\ Switch\ Online-*-mac.zip" \
|
||||
"app/Nintendo\ Switch\ Online-*.AppImage" \
|
||||
"app/nxapi-app_*.deb" \
|
||||
"app/nxapi-app_*.snap" \
|
||||
"app/Nintendo\ Switch\ Online\ Setup\ *.exe"
|
||||
needs:
|
||||
- build-app
|
||||
- build-windows
|
||||
rules:
|
||||
- if: $CI_COMMIT_TAG =~ /^v/ && $GITLAB_REPOSITORY && $GITHUB_TOKEN && $GITHUB_UPLOAD_RELEASE_ASSETS == "true"
|
||||
cache:
|
||||
paths:
|
||||
- node_modules/
|
||||
|
|
@ -233,9 +237,8 @@ publish-next:
|
|||
fi
|
||||
needs:
|
||||
- build
|
||||
only:
|
||||
refs:
|
||||
- main
|
||||
rules:
|
||||
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
|
||||
cache:
|
||||
paths:
|
||||
- node_modules/
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
FROM node:18 as build
|
||||
FROM node:20 as build
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
|
|
@ -13,7 +13,7 @@ ADD tsconfig.json /app
|
|||
|
||||
RUN npx tsc
|
||||
|
||||
FROM node:18
|
||||
FROM node:20
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
|
|
@ -24,6 +24,7 @@ RUN npm ci --production
|
|||
|
||||
COPY bin /app/bin
|
||||
COPY resources /app/resources
|
||||
COPY resources/cli/fonts /usr/local/share/fonts
|
||||
COPY --from=build /app/dist /app/dist
|
||||
|
||||
RUN ln -s /app/bin/nxapi.js /usr/local/bin/nxapi
|
||||
|
|
|
|||
188
README.md
188
README.md
|
|
@ -1,80 +1,81 @@
|
|||
nxapi
|
||||
===
|
||||
|
||||
JavaScript library and command line and Electron app for accessing the Nintendo Switch Online and Nintendo Switch Parental Controls app APIs. Show your Nintendo Switch presence in Discord, get friend notifications on desktop, and download and access SplatNet 2, NookLink, SplatNet 3 and Parental Controls data.
|
||||
JavaScript library, command line tool and Electron app for accessing the Nintendo Switch Online and Nintendo Switch Parental Controls app APIs. Show your Nintendo Switch presence on Discord, get friend notifications on desktop, and download and access SplatNet 2, NookLink, SplatNet 3 and Parental Controls data.
|
||||
|
||||
[](https://discord.com/invite/4D82rFkXRv)
|
||||
[](https://discord.com/invite/4D82rFkXRv)
|
||||
|
||||
### Features
|
||||
|
||||
- Command line and Electron app interfaces
|
||||
- Interactive Nintendo Account login for the Nintendo Switch Online and Nintendo Switch Parental Controls apps
|
||||
- Automated login to the Nintendo Switch Online app API
|
||||
- This uses the imink API by default.
|
||||
- This uses [nxapi-znca-api.fancy.org.uk](https://github.com/samuelthomas2774/nxapi-znca-api) API by default.
|
||||
- Alternatively a custom server can be used.
|
||||
- A custom server using a rooted Android device/emulator is included.
|
||||
- Get Nintendo Switch account information, friends list and game-specific services
|
||||
- Show Discord Rich Presence using your own or a friend's Nintendo Switch presence
|
||||
- Show your account's friend code (or a custom friend code)
|
||||
- Fetch presence from a custom URL
|
||||
- All titles are supported using a default Nintendo Switch app. A limited number of titles have their own
|
||||
Discord apps (meaning they appear under your name with the title's name instead of "Nintendo Switch")
|
||||
or other custom Discord features. [See here for Discord title overrides](src/discord/titles) or
|
||||
[create an issue if you'd like another title added](https://github.com/samuelthomas2774/nxapi/issues/new/choose).
|
||||
|
||||

|
||||
|
||||
- Show Discord Rich Presence using your Nintendo Switch presence
|
||||
- Fetch presence using a secondary account or from a custom URL.
|
||||
- Show your account's friend code (or a custom friend code).
|
||||
- All titles are supported, and since August 2025 all titles can show their full name next to your name
|
||||
in Discord without any extra configuration.
|
||||
- Additional presence information for Splatoon 3
|
||||
|
||||
<img src="resources/discord-activity-splatoon3.png" alt="Screenshot showing Splatoon 3 as a Discord activity with SplatNet 3 presence information" width="308">
|
||||
- Show notifications for friend Nintendo Switch presences
|
||||
|
||||

|
||||
- [Electron app] Open game-specific services
|
||||
- Including NookLink, which doesn't work in web browsers as it requires custom JavaScript APIs.
|
||||
- Nintendo Switch Online app API proxy server
|
||||
- Nintendo Switch Online app API proxy server and presence server
|
||||
- This allows a single account to fetch presence for multiple users.
|
||||
- Data will be cached for a short time to reduce the number of requests to Nintendo's server.
|
||||
- This automatically handles authentication when given a Nintendo Account session token. This makes it much
|
||||
easier to access the API from a browser, in scripts or in other software.
|
||||
- Download all personalised SplatNet 2 data, including battle and Salmon Run results
|
||||
- This supports monitoring the authenticated user's presence and only checking for new data when playing
|
||||
Splatoon 2 online.
|
||||
- Download all personal SplatNet 2 and SplatNet 3 data, including battle and Salmon Run results
|
||||
- Download island newspapers from and send messages and reactions using NookLink
|
||||
- Download all Nintendo Switch Parental Controls usage records
|
||||
|
||||
The API library and types are exported for use in JavaScript/TypeScript software. The app/commands properly cache access tokens and try to handle requests to appear as Nintendo's apps - if using nxapi as a library you will need to handle this yourself. [More information.](#usage-as-a-typescriptjavascript-library)
|
||||
|
||||
Discord presence | Additional data for Splatoon 3 | Friend notifications
|
||||
------------------------------------|-----------------------------------|-----------------------------------
|
||||
 | <img src="resources/discord-activity-splatoon3.png" alt="Screenshot showing Splatoon 3 as a Discord activity with SplatNet 3 presence information" width="308"> | 
|
||||
|
||||
#### Electron app
|
||||
|
||||
nxapi includes an Electron app, which can be downloaded [here](https://github.com/samuelthomas2774/nxapi/releases). The app can be used to:
|
||||
|
||||
- Login to a Nintendo Account, both for the Nintendo Switch Online app and Parental Controls app.
|
||||
- Login to a Nintendo Account, both for the Nintendo Switch Online app and Parental Controls app
|
||||
- This will open the Nintendo Account login page in the app, just like signing into Nintendo's own apps.
|
||||
- The Nintendo Account authorisation page can be opened in a browser by holding <kbd>Shift</kbd> while pressing add account.
|
||||
- Accounts are shared with the nxapi command line interface.
|
||||
- Share Nintendo Switch presence to Discord.
|
||||
- Share Nintendo Switch presence to Discord
|
||||
- Using a custom presence URL or a friend's presence is supported.
|
||||
- Using the authenticated user's presence is not supported, as this is no longer available from the API ([#1](https://github.com/samuelthomas2774/nxapi/issues/1)).
|
||||
- Showing notifications for friend presences.
|
||||
- Showing notifications for friend presences
|
||||
- Multiple users can be selected.
|
||||
- Access game-specific services.
|
||||
- Access game-specific services
|
||||
- These will be opened in the app.
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
The app includes the nxapi command line at `dist/bundle/cli-bundle.js`. Node.js must be installed separately to use this.
|
||||
The app includes the nxapi command line at `dist/bundle/cli-bundle.js`.
|
||||
|
||||
```sh
|
||||
# macOS
|
||||
node Nintendo\ Switch\ Online.app/Contents/Resources/app/dist/bundle/cli-bundle.js ...
|
||||
|
||||
# Windows
|
||||
node 'Nintendo Switch Online/resources/app/dist/bundle/cli-bundle.js' ...
|
||||
Nintendo\ Switch\ Online.app/Contents/bin/nxapi
|
||||
|
||||
# Linux, installed via dpkg
|
||||
node /opt/Nintendo\ Switch\ Online/resources/app/dist/bundle/cli-bundle.js ...
|
||||
# This is linked as /usr/bin/nxapi
|
||||
/opt/Nintendo\ Switch\ Online/bin/nxapi
|
||||
```
|
||||
|
||||
On Windows, Node.js must be installed separately.
|
||||
|
||||
```powershell
|
||||
# PowerShell
|
||||
node $env:LOCALAPPDATA\Programs\nxapi-app\resources\app\dist\bundle\cli-bundle.js ...
|
||||
|
||||
# Command Prompt
|
||||
node %localappdata%\Programs\nxapi-app\resources\app\dist\bundle\cli-bundle.js ...
|
||||
```
|
||||
|
||||
#### Do I need a Nintendo Switch Online membership?
|
||||
|
|
@ -83,10 +84,20 @@ No.
|
|||
|
||||
The only requirement to use this is that your Nintendo Account is linked to a Network Service Account, i.e. you've linked your Nintendo Account to a Nintendo Switch console at some point. It doesn't matter if your account is no longer linked to any console.
|
||||
|
||||
You will need to have had an online membership (free trial is ok) to use any game-specific services if you want to access those. SplatNet 2 can be used without an active membership, but NookLink and Smash World both require an active membership just to open them.
|
||||
You will need to have an online membership (free trial is ok) to use any game-specific services if you want to access those. SplatNet 2 can be used without an active membership, but NookLink and Smash World both require an active membership just to open them.
|
||||
|
||||
For Parental Controls data, you don't need to have linked your account to a console. You will need to use Nintendo's app to add a console to your account though, as this isn't supported in nxapi and the Parental Controls API is a bit useless without doing this.
|
||||
|
||||
#### The Electron app does not connect to Discord on Linux
|
||||
|
||||
The Electron app, Discord, or both, may be sandboxed depending on how they're installed.
|
||||
|
||||
The dpkg and AppImage nxapi packages are not sandboxed. The official dpkg Discord package and tar release are not sandboxed.
|
||||
|
||||
The snap packages of nxapi and Discord are sandboxed and cannot support Discord Rich Presence.
|
||||
|
||||
The Flatpak Discord package is sandboxed, but can be used by linking the IPC socket outside of the app directory: https://github.com/flathub/com.discordapp.Discord/wiki/Rich-Precense-(discord-rpc).
|
||||
|
||||
#### Will my Nintendo Switch console be banned for using this?
|
||||
|
||||
No.
|
||||
|
|
@ -95,13 +106,28 @@ No.
|
|||
|
||||
It's extremely unlikely:
|
||||
|
||||
- Other projects (e.g. splatnet2statink, splatoon2.ink) have used the same reverse engineered APIs for a long time (pretty much since they've existed) and no one has ever been banned for using them. splatnet2statink in monitoring mode updates every 5 minutes by default - monitoring commands (Discord presence, friend notifications and SplatNet 2 monitoring) in nxapi only update slightly more frequently (every 1 minute), so there's not much higher risk than using splatnet2statink.
|
||||
- Other projects (e.g. splatnet2statink, splatoon2.ink) have used the same reverse engineered APIs for a long time (pretty much since they've existed) and no one has ever been banned for using them. splatnet2statink in monitoring mode updates every 5 minutes by default - monitoring commands (Discord presence, friend notifications and SplatNet 2/SplatNet 3 monitoring) in nxapi only update slightly more frequently (every 1 minute), so there's not much higher risk than using splatnet2statink.
|
||||
- Unlike console bans, account bans would prevent you from accessing digital content or online services you've paid for. (If your console was banned you'd still be able to use it and you could just buy another one to access your account.)
|
||||
- Nintendo can't stop you watching their app's network activity, which is all the reverse engineering required to develop this.
|
||||
|
||||
For Discord Rich Presence, you can create an additional account, add your main account as a friend and use the `--friend-nsaid` option to avoid automating your main account. Once set up, you can remove the additional account from any console. You can also set up an API proxy server (with a HTTPS reverse proxy), authenticate using a separate account, and set up API proxy authentication tokens to allow up to 300 users (max. Nintendo Switch friends) to set up Discord Rich Presence (or, get their Nintendo Switch presence in a simple HTTP request to use for anything else) without any additional requests to Nintendo.
|
||||
A secondary account is required for Discord Rich Presence; you don't need to sign in to your main account.
|
||||
|
||||
#### Why is a token sent to one/two different non-Nintendo servers?
|
||||
> [!CAUTION]
|
||||
>
|
||||
> **Update 08/09/2023**
|
||||
>
|
||||
> Nintendo has banned a small number of users from accessing SplatNet 3. Nintendo has not sent any notification to affected users. This is only known to have affected users of one application unrelated to nxapi.
|
||||
>
|
||||
> SplatNet 3 returns `401 Unauthorized` (`ERROR_INVALID_GAME_WEB_TOKEN`... which causes the official app to retry repeatedly); there is no specific error message for banned users. No other Nintendo services are affected.
|
||||
>
|
||||
> If you only use nxapi for Discord Rich Presence, your main account is safe, because nxapi does not use it to fetch presence data. nxapi requires a secondary account to fetch your main account's presence data, so even if that account was banned you could just create another one without losing anything.
|
||||
>
|
||||
> More information:
|
||||
>
|
||||
> - https://tkgstrator.work/article/2023/09/announcement.html
|
||||
> - https://github.com/frozenpandaman/s3s/issues/146
|
||||
|
||||
#### Why is data sent to non-Nintendo servers?
|
||||
|
||||
It's required to generate some data to make Nintendo think you're using the real Nintendo Switch Online app, as currently it's too hard to do this locally. (This isn't required for Parental Controls data.) See the [Coral client authentication](#coral-client-authentication) section below for more information.
|
||||
|
||||
|
|
@ -137,6 +163,9 @@ npm install --global --registry https://gitlab.com/api/v4/packages/npm/ @samuelt
|
|||
|
||||
Node.js and npm must already be installed.
|
||||
|
||||
> [!NOTE]
|
||||
> When building from source nxapi will not have a nxapi-auth client identifier necessary to use the f-generation API. Register a test OAuth client at https://nxapi-auth.fancy.org.uk/oauth/clients with the scope `ca:gf ca:er ca:dr` and add the client ID to [the `.env` file used by nxapi](#environment-variables) as `NXAPI_AUTH_CLIENT_ID`. This will use the same client for the command line and Electron app. This is only necessary if you are using nxapi to access the Coral API directly, if you are not using the Coral API, or are using the `ZncProxyApi` class instead of `CoralApi`, nxapi doesn't need to use the f-generation API.
|
||||
|
||||
```sh
|
||||
# Don't download an archive, as nxapi detects the current git revision
|
||||
git clone https://gitlab.fancy.org.uk/samuel/nxapi.git
|
||||
|
|
@ -156,9 +185,9 @@ npx rollup --config
|
|||
# nxapi app or node bin/nxapi.js app to run the app
|
||||
|
||||
# Build Docker image
|
||||
docker build . --tag gitlab.fancy.org.uk:5005/samuel/nxapi
|
||||
docker build . --tag registry.fancy.org.uk/samuel/nxapi
|
||||
# # Run in Docker
|
||||
# docker run -it --rm -v ./data:/data gitlab.fancy.org.uk:5005/samuel/nxapi ...
|
||||
# docker run -it --rm -v ./data:/data registry.fancy.org.uk/samuel/nxapi ...
|
||||
```
|
||||
|
||||
### Usage
|
||||
|
|
@ -212,6 +241,18 @@ DEBUG=nxapi:api:* nxapi ...
|
|||
DEBUG=* nxapi ...
|
||||
```
|
||||
|
||||
By default all nxapi logs will be written to a platform-specific location:
|
||||
|
||||
Platform | Log path
|
||||
----------------|----------------
|
||||
macOS | `Library/Logs/nxapi-nodejs`
|
||||
Windows | `%localappdata%\nxapi-nodejs\Log`
|
||||
Linux | `$XDG_STATE_HOME/nxapi-nodejs` or `.local/state/nxapi-nodejs`
|
||||
|
||||
This only applies to the command line and Electron app and can be disabled by setting `NXAPI_DEBUG_FILE` to `0`. Each process writes to a new file. nxapi will automatically delete log files older than 14 days.
|
||||
|
||||
nxapi logs may contain sensitive information such as Nintendo Account access tokens.
|
||||
|
||||
#### Environment variables
|
||||
|
||||
Some options can be set using environment variables. These can be stored in a `.env` file in the data location. Environment variables will be read from the `.env` file in the default location, then the `.env` file in `NXAPI_DATA_PATH` location. `.env` files will not be read from the location set in the `--data-path` option.
|
||||
|
|
@ -233,7 +274,13 @@ Environment variable | Description
|
|||
`NXAPI_SKIP_UPDATE_CHECK` | Disables the update check in the nxapi command and the Electron app if set to `1`.
|
||||
`NXAPI_SPLATNET3_UPGRADE_QUERIES` | Sets when the SplatNet 3 client is allowed to upgrade persisted query IDs to newer versions. If `0` queries are never upgraded (not recommended). If `1` queries are upgraded if they do not contain potentially breaking changes (not recommended, as like `0` this allows older queries to be sent to the API). If `2` queries are upgraded, requests that would include breaking changes are rejected. If `3` all queries are upgraded, even if they contain potentially breaking changes (default).
|
||||
`NXAPI_SPLATNET3_STRICT` | Disables strict handling of errors from the SplatNet 3 GraphQL API if set to `0`. If set to `1` (default) requests will be rejected if the response includes any errors, even if the response includes a result.
|
||||
`NXAPI_ZNCA_API_CLIENT_ID` | nxapi-auth client identifier to use for the f-generation API instead of the default. For development, `NXAPI_AUTH_CLIENT_ID` can be used to set the default nxapi-auth client.
|
||||
`NXAPI_ZNCA_API_CLIENT_SECRET` | nxapi-auth client secret to use for the f-generation API if necessary for a non-default client.
|
||||
`NXAPI_ZNCA_API_CLIENT_ASSERTION` | nxapi-auth client assertion to use for the f-generation API if necessary for a non-default client. Setting `NXAPI_ZNCA_API_CLIENT_ID` is not necessary when using a client assertion, as the assertion contains the client identifier.
|
||||
`NXAPI_ZNCA_API_CLIENT_ASSERTION_TYPE` | Type of the client assertion if not `urn:ietf:params:oauth:client-assertion-type:jwt-bearer`.
|
||||
`NXAPI_ZNCA_API_AUTH_SCOPE` | nxapi-auth scope to use for the f-generation API. This should usually not need to be set. For development, `NXAPI_AUTH_SCOPE` can be used to set the default nxapi-auth scope.
|
||||
`DEBUG` | Used by the [debug](https://github.com/debug-js/debug) package. Sets which modules should have debug logging enabled. See [debug logs](#debug-logs).
|
||||
`NXAPI_DEBUG_FILE` | Disables writing debug logs to a file if set to `0`.
|
||||
|
||||
Other environment variables may also be used by Node.js, Electron or other packages nxapi depends on.
|
||||
|
||||
|
|
@ -254,13 +301,19 @@ When using nxapi as a TypeScript/JavaScript library, the `addUserAgent` function
|
|||
import { addUserAgent } from 'nxapi';
|
||||
|
||||
addUserAgent('your-script/1.0.0 (+https://github.com/...)');
|
||||
```
|
||||
|
||||
// This could also be read from a package.json file
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { resolve } from 'node:path';
|
||||
import { readFile } from 'node:fs/promises':
|
||||
const pkg = JSON.parse(await readFile(resolve(fileURLToPath(import.meta.url), '..', 'package.json'), 'utf-8'));
|
||||
addUserAgent(pkg.name + '/' + pkg.version + ' (+' + pkg.repository.url + ')');
|
||||
The `addUserAgentFromPackageJson` function can be used to add data from a package.json file.
|
||||
|
||||
```ts
|
||||
import { addUserAgentFromPackageJson } from 'nxapi';
|
||||
|
||||
await addUserAgentFromPackageJson(new URL('../package.json', import.meta.url));
|
||||
await addUserAgentFromPackageJson(path.resolve(fileURLToString(import.meta.url), '..', 'package.json'));
|
||||
// adds "test-package/0.1.0 (+https://github.com/ghost/example.git)"
|
||||
|
||||
await addUserAgentFromPackageJson(new URL('../package.json', import.meta.url), 'additional information');
|
||||
// adds "test-package/0.1.0 (+https://github.com/ghost/example.git; additional information)"
|
||||
```
|
||||
|
||||
### Usage as a TypeScript/JavaScript library
|
||||
|
|
@ -273,15 +326,11 @@ See [docs/lib](docs/lib/index.md) and [src/exports](src/exports).
|
|||
|
||||
### Coral client authentication
|
||||
|
||||
The [imink API](https://github.com/JoneWang/imink/wiki/imink-API-Documentation) is used by default to automate authenticating to the Nintendo Switch Online app's API and authenticating to web services. An access token (`id_token`) created by Nintendo must be sent to this API to generate some data that is required to authenticate the app. This API runs the Nintendo Switch Online app on an Android device to generate this data. The access token sent includes some information about the authenticated Nintendo Account and can be used to authenticate to the Nintendo Switch Online app and web services.
|
||||
[nxapi-znca-api.fancy.org.uk](https://github.com/samuelthomas2774/nxapi-znca-api) is used by default to automate authenticating to the Nintendo Switch Online app's API and authenticating to web services. An access token (`id_token`) created by Nintendo must be sent to this API to generate some data that is required to authenticate the app. This API runs the Nintendo Switch Online app on an Android device to generate this data. The access token sent includes some information about the authenticated Nintendo Account and can be used to authenticate to the Nintendo Switch Online app and web services.
|
||||
|
||||
Specifically, the tokens sent are JSON Web Tokens. The token sent to login to the app includes [this information and is valid for 15 minutes](https://gitlab.fancy.org.uk/samuel/nxapi/-/wikis/Nintendo-tokens#nintendo-account-id_token), and the token sent to login to web services includes [this information and is valid for two hours](https://gitlab.fancy.org.uk/samuel/nxapi/-/wikis/Nintendo-tokens#nintendo-switch-online-app-token).
|
||||
|
||||
Alternatively the [flapg API](https://twitter.com/NexusMine/status/1563728086322929665) can be used by setting the `NXAPI_ZNCA_API` environment variable to `flapg`. (`NXAPI_ZNCA_API=flapg nxapi nso ...`)
|
||||
|
||||
> Since v1.3.0 the default API to use will be fetched from my server and can be changed without an update to nxapi. To force the use of the imink API, set the `NXAPI_ZNCA_API` environment variable to `imink`.
|
||||
|
||||
nxapi also includes a custom server using Frida on an Android device/emulator that can be used instead of these.
|
||||
> Since v1.3.0 the default API to use will be fetched from my server and can be changed without an update to nxapi.
|
||||
|
||||
This is only required for Nintendo Switch Online app data. Nintendo Switch Parental Controls data can be fetched without sending an access token to a third-party API.
|
||||
|
||||
|
|
@ -291,12 +340,46 @@ The reason Nintendo added this is probably to try and stop people automating acc
|
|||
|
||||
[**See #10 if you can help with this.**](https://github.com/samuelthomas2774/nxapi/discussions/10)
|
||||
|
||||
#### nxapi-auth authentication
|
||||
|
||||
Since June 2025, [nxapi-znca-api.fancy.org.uk](https://github.com/samuelthomas2774/nxapi-znca-api) requires client authentication via nxapi-auth.
|
||||
|
||||
When using the Electron app or nxapi command installed from npm or the Docker image you don't need to do anything. If you build nxapi from source, or use it as a library, you will need to register a client at https://nxapi-auth.fancy.org.uk/oauth/clients.
|
||||
|
||||
> [!CAUTION]
|
||||
> This API may change.
|
||||
|
||||
```ts
|
||||
import { setClientAuthentication, ClientAssertionProviderInterface } from 'nxapi';
|
||||
|
||||
// setClientAuthentication accepts an object with a client id and optional secret, or
|
||||
// a function that returns a client assertion
|
||||
// `scope` is always required, even though it will usually always be `ca:gf ca:er ca:dr`
|
||||
|
||||
// Public client
|
||||
setClientAuthentication({ id: '...', scope: 'ca:gf ca:er ca:dr' });
|
||||
|
||||
// Confidential client, using client secret
|
||||
setClientAuthentication({ id: '...', secret: process.env.NXAPI_AUTH_CLIENT_SECRET, scope: 'ca:gf ca:er ca:dr' });
|
||||
|
||||
// Confidential client, using client assertion
|
||||
setClientAuthentication(new ExampleClientAssertionProvider());
|
||||
|
||||
class ExampleClientAssertionProvider implements ClientAssertionProviderInterface {
|
||||
scope = 'ca:gf ca:er ca:dr';
|
||||
|
||||
async create(aud: string, exp = 60) {
|
||||
return { assertion: '...', type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer' };
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Resources
|
||||
|
||||
- Nintendo Switch Online app API docs
|
||||
- https://github.com/ZekeSnider/NintendoSwitchRESTAPI
|
||||
- https://dev.to/mathewthe2/intro-to-nintendo-switch-rest-api-2cm7
|
||||
- nxapi includes TypeScript definitions of all API resources and JSON Web Token payloads at [src/api](src/api)
|
||||
- nxapi includes TypeScript definitions for all API resources and JSON Web Token payloads at [src/api](src/api)
|
||||
- Coral client authentication (`f` parameter)
|
||||
- https://github.com/samuelthomas2774/nxapi/discussions/10
|
||||
- ~~https://github.com/frozenpandaman/splatnet2statink/wiki/api-docs - splatnet2statink and flapg API docs~~
|
||||
|
|
@ -313,10 +396,11 @@ The reason Nintendo added this is probably to try and stop people automating acc
|
|||
- https://github.com/Quark064/NSO-Discord-Integration
|
||||
- https://github.com/AAGaming00/acnhrp - doesn't use Coral, instead attempts to send a message in Animal Crossing: New Horizons every 10 seconds to check if the user is playing that game online
|
||||
- Other projects using Coral/web services
|
||||
- (Due to frequent breaking changes to Nintendo's API many of these do not work. In particular anything not updated since [23/08/2022](https://github.com/samuelthomas2774/nxapi/discussions/10#discussioncomment-3464443) will not be able to authenticate to Nintendo's API.)
|
||||
- https://github.com/frozenpandaman/splatnet2statink
|
||||
- https://github.com/subnode/LoungeDesktop
|
||||
- https://github.com/dqn/gonso
|
||||
- https://github.com/clovervidia/splatnet-datagrabber
|
||||
- https://github.com/mizuyoukanao/ACNH_Chat_Client
|
||||
- https://github.com/dqn/acnh
|
||||
- ... plus many more - [search GitHub for https://elifessler.com/s2s/api/gen2](https://github.com/search?q=https%3A%2F%2Felifessler.com%2Fs2s%2Fapi%2Fgen2&type=code)
|
||||
- ... plus many more - [search GitHub for znc.srv.nintendo.net](https://github.com/search?q=znc.srv.nintendo.net&type=code)
|
||||
|
|
|
|||
|
|
@ -1,7 +1,3 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
import createDebug from 'debug';
|
||||
|
||||
createDebug.log = console.warn.bind(console);
|
||||
|
||||
import('../dist/cli.js').then(cli => cli.main.call(null));
|
||||
import('../dist/cli-entry.js');
|
||||
|
|
|
|||
|
|
@ -1,41 +0,0 @@
|
|||
FROM node:17 as build
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ADD package.json /app
|
||||
ADD package-lock.json /app
|
||||
|
||||
RUN npm install
|
||||
|
||||
COPY src /app/src
|
||||
COPY bin /app/bin
|
||||
ADD tsconfig.json /app
|
||||
|
||||
RUN npx tsc
|
||||
|
||||
RUN ln -s /app/bin/nxapi.js /usr/local/bin/nxapi
|
||||
ENV NXAPI_DATA_PATH=/data
|
||||
ENV NODE_ENV=development
|
||||
|
||||
COPY data-api/public /public
|
||||
WORKDIR /public
|
||||
|
||||
RUN mkdir -p data && \
|
||||
echo "Exporting Discord title configuration as JSON" && \
|
||||
DEBUG=* nxapi util export-discord-titles --format json > data/discord-titles.json && \
|
||||
echo "Exporting Discord title configuration as JSON without Discord activity configuration" && \
|
||||
DEBUG=* nxapi util export-discord-titles --format json --exclude-discord-configuration > data/discord-titles-compact.json && \
|
||||
# echo "Exporting Discord title configuration as JSON with Nintendo eShop contents" && \
|
||||
# DEBUG=* nxapi util export-discord-titles --format json --include-title-contents > data/discord-titles-with-contents.json && \
|
||||
echo "Exporting Discord title configuration as JSON with Discord applications" && \
|
||||
DEBUG=* nxapi util export-discord-titles --format json --group-discord-clients > data/discord-clients.json && \
|
||||
# echo "Exporting Discord title configuration as JSON with Discord applications and Nintendo eShop contents" && \
|
||||
# DEBUG=* nxapi util export-discord-titles --format json --group-discord-clients --include-title-contents > data/discord-clients-with-contents.json && \
|
||||
echo "Exporting Discord title configuration as CSV" && \
|
||||
DEBUG=* nxapi util export-discord-titles --format csv > data/discord-titles.csv && \
|
||||
echo "Exporting Discord title configuration as CSV without Discord activity configuration" && \
|
||||
DEBUG=* nxapi util export-discord-titles --format csv --exclude-discord-configuration > data/discord-titles-compact.csv
|
||||
|
||||
FROM nginx:alpine
|
||||
|
||||
COPY --from=build /public /usr/share/nginx/html
|
||||
|
|
@ -1,13 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en-GB">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta http-equiv="Refresh" content="0;url=https://gitlab.fancy.org.uk/samuel/nxapi" />
|
||||
<title>nxapi</title>
|
||||
</head>
|
||||
<body>
|
||||
<script>location.href = 'https://gitlab.fancy.org.uk/samuel/nxapi';</script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -40,18 +40,18 @@ services:
|
|||
|
||||
presence-server:
|
||||
build: .
|
||||
command: presence-server --listen \[::]:80 --splatnet3
|
||||
command: presence-server --listen \[::]:80 --splatnet3 --splatnet3-fest-votes
|
||||
restart: unless-stopped
|
||||
profiles:
|
||||
- presence-server
|
||||
labels:
|
||||
traefik.enable: true
|
||||
traefik.http.routers.nxapi-presence.entrypoints: websecure
|
||||
traefik.http.routers.nxapi-presence.rule: Host(`${TRAEFIK_HOST:-nxapi.ta.fancy.org.uk}`) && (Path(`/api/presence`) || PathPrefix(`/api/presence/`))
|
||||
traefik.http.routers.nxapi-presence.rule: Host(`${TRAEFIK_HOST:-nxapi.ta.fancy.org.uk}`) && (Path(`/api/presence`) || PathPrefix(`/api/presence/`) || PathPrefix(`/api/splatnet3/resources/`))
|
||||
traefik.http.routers.nxapi-presence.tls: true
|
||||
traefik.http.services.nxapi-presence.loadbalancer.server.port: 80
|
||||
environment:
|
||||
DEBUG: '*,-express:*'
|
||||
DEBUG: '*,-express:*,-send'
|
||||
ZNC_PROXY_URL: http://znc-proxy/api/znc
|
||||
NXAPI_PRESENCE_SERVER_USER: ${NXAPI_PRESENCE_SERVER_USER:-}
|
||||
NXAPI_PRESENCE_SERVER_SPLATNET3_PROXY_URL: http://presence-splatnet3-proxy/api/splatnet3-presence
|
||||
|
|
@ -60,7 +60,7 @@ services:
|
|||
|
||||
presence-splatnet3-proxy:
|
||||
build: .
|
||||
command: presence-server --listen \[::]:80 --splatnet3 --splatnet3-proxy
|
||||
command: presence-server --listen \[::]:80 --splatnet3 --splatnet3-proxy --splatnet3-record-fest-votes
|
||||
restart: unless-stopped
|
||||
profiles:
|
||||
- presence-server
|
||||
|
|
|
|||
37
docs/cli.md
37
docs/cli.md
|
|
@ -664,9 +664,46 @@ curl http://[::1]:12345/api/presence/0123456789abcdef
|
|||
# Fetch presence data for a specific user including Splatoon 3 presence using curl
|
||||
curl http://[::1]:12345/api/presence/0123456789abcdef?include-splatoon3=1
|
||||
|
||||
# Fetch Splatoon 3 fest voting history for a specific user using curl
|
||||
curl http://[::1]:12345/api/presence/0123456789abcdef/splatoon3-fest-votes
|
||||
# Fetch Splatoon 3 fest voting history including all prevotes for a specific user using curl
|
||||
curl http://[::1]:12345/api/presence/0123456789abcdef/splatoon3-fest-votes?include-all=1
|
||||
|
||||
# Watch for presence events
|
||||
curl --no-buffer http://[::1]:12345/api/presence/0123456789abcdef/events
|
||||
curl --no-buffer http://[::1]:12345/api/presence/0123456789abcdef/events?include-splatoon3=1
|
||||
|
||||
# Save a user's current picture
|
||||
curl -L http://[::1]:12345/api/presence/0123456789abcdef/image > image.jpeg
|
||||
|
||||
# Show the Nintendo eShop page for a user's current title
|
||||
# http://[::1]:12345/api/presence/0123456789abcdef/title/redirect
|
||||
# Redirect to a friend code URL if not playing
|
||||
# http://[::1]:12345/api/presence/0123456789abcdef/title/redirect?friend-code=0000-0000-0000&friend-code-hash=0000000000
|
||||
# Redirect to another URL if not playing
|
||||
# http://[::1]:12345/api/presence/0123456789abcdef/title/redirect?fallback-url=https://example.com
|
||||
# Signal to the browser to cancel navigation if not playing
|
||||
# http://[::1]:12345/api/presence/0123456789abcdef/title/redirect?fallback-prevent-navigation=1
|
||||
|
||||
# Generate an SVG showing a user's presence
|
||||
curl http://[::1]:12345/api/presence/0123456789abcdef/embed > embed.svg
|
||||
# Generate a PNG/JPEG/WEBP showing a user's presence
|
||||
curl http://[::1]:12345/api/presence/0123456789abcdef/embed.png > embed.png
|
||||
curl http://[::1]:12345/api/presence/0123456789abcdef/embed.jpeg > embed.jpeg
|
||||
curl http://[::1]:12345/api/presence/0123456789abcdef/embed.webp > embed.webp
|
||||
# ... using a specific theme
|
||||
curl http://[::1]:12345/api/presence/0123456789abcdef/embed?theme=light > embed.svg
|
||||
curl http://[::1]:12345/api/presence/0123456789abcdef/embed?theme=dark > embed.svg
|
||||
# ... including a friend code
|
||||
curl http://[::1]:12345/api/presence/0123456789abcdef/embed?friend-code=0000-0000-0000 > embed.svg
|
||||
# ... without a background and border
|
||||
curl http://[::1]:12345/api/presence/0123456789abcdef/embed?transparent=1 > embed.svg
|
||||
# ... with a custom width (500 to 1500, or 440 to 1440 with transparency)
|
||||
curl http://[::1]:12345/api/presence/0123456789abcdef/embed?width=800 > embed.svg
|
||||
# ... with Splatoon 3 presence
|
||||
curl http://[::1]:12345/api/presence/0123456789abcdef/embed?include-splatoon3=1 > embed.svg
|
||||
# ... with Splatoon 3 Splatfest team
|
||||
curl 'http://[::1]:12345/api/presence/0123456789abcdef/embed?include-splatoon3=1&show-splatoon3-fest-team=1' > embed.svg
|
||||
```
|
||||
|
||||
Example EventStream use:
|
||||
|
|
|
|||
|
|
@ -151,6 +151,10 @@ try {
|
|||
|
||||
This function is used to set the user agent string to use for non-Nintendo API requests. Any project using nxapi (including as a dependency of another project) must call this function with an appropriate user agent string segment. See [user agent strings](../../README.md#user-agent-strings).
|
||||
|
||||
#### `addUserAgentFromPackageJson`
|
||||
|
||||
This function is used to set the user agent string to use for non-Nintendo API requests using data from a package.json file. A string, URL object or the package.json data can be provided, as well as optional additional data. If a string/URL is provided this will return a Promise that will be resolved once the user agent is updated. See [user agent strings](../../README.md#user-agent-strings).
|
||||
|
||||
#### `version`
|
||||
|
||||
nxapi's version number.
|
||||
|
|
|
|||
11659
package-lock.json
generated
11659
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
123
package.json
123
package.json
|
|
@ -1,9 +1,9 @@
|
|||
{
|
||||
"name": "nxapi",
|
||||
"version": "1.6.0",
|
||||
"version": "1.6.1",
|
||||
"description": "Nintendo Switch app APIs",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"author": "Samuel Elliott <samuel+nxapi@fancy.org.uk>",
|
||||
"author": "Ellie <ellie+nxapi@fancy.org.uk>",
|
||||
"main": "dist/index.js",
|
||||
"type": "module",
|
||||
"repository": {
|
||||
|
|
@ -22,6 +22,7 @@
|
|||
],
|
||||
"exports": {
|
||||
".": "./dist/exports/index.js",
|
||||
"./nintendo-account": "./dist/exports/nintendo-account.js",
|
||||
"./coral": "./dist/exports/coral.js",
|
||||
"./moon": "./dist/exports/moon.js",
|
||||
"./splatnet2": "./dist/exports/splatnet2.js",
|
||||
|
|
@ -35,63 +36,65 @@
|
|||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"body-parser": "^1.20.1",
|
||||
"@samuelthomas2774/saltpack": "^0.4.0",
|
||||
"body-parser": "^1.20.2",
|
||||
"cli-table": "^0.3.11",
|
||||
"debug": "^4.3.4",
|
||||
"discord-rpc": "^4.0.1",
|
||||
"dotenv": "^16.0.3",
|
||||
"dotenv-expand": "^9.0.0",
|
||||
"dotenv": "^16.4.5",
|
||||
"dotenv-expand": "^11.0.6",
|
||||
"env-paths": "^3.0.0",
|
||||
"eventsource": "^2.0.2",
|
||||
"express": "^4.18.2",
|
||||
"mkdirp": "^1.0.4",
|
||||
"node-fetch": "^3.3.0",
|
||||
"express": "^4.19.2",
|
||||
"murmurhash": "^2.0.1",
|
||||
"node-notifier": "^10.0.1",
|
||||
"node-persist": "^3.1.0",
|
||||
"read": "^1.0.7",
|
||||
"splatnet3-types": "^0.2.20221212221842",
|
||||
"supports-color": "^8.1.1",
|
||||
"tslib": "^2.4.1",
|
||||
"uuid": "^8.3.2",
|
||||
"yargs": "^17.6.2"
|
||||
"node-persist": "^3.1.3",
|
||||
"read": "^3.0.1",
|
||||
"sharp": "^0.33.3",
|
||||
"splatnet3-types": "^0.2.20231119210145",
|
||||
"supports-color": "^9.4.0",
|
||||
"tar": "^7.4.3",
|
||||
"tslib": "^2.6.2",
|
||||
"tweetnacl": "^1.0.3",
|
||||
"undici": "^6.15.0",
|
||||
"yargs": "^17.7.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rollup/plugin-alias": "^3.1.9",
|
||||
"@rollup/plugin-commonjs": "^22.0.2",
|
||||
"@rollup/plugin-html": "^0.2.4",
|
||||
"@rollup/plugin-json": "^4.1.0",
|
||||
"@rollup/plugin-node-resolve": "^14.1.0",
|
||||
"@rollup/plugin-replace": "^4.0.0",
|
||||
"@rollup/plugin-typescript": "^8.5.0",
|
||||
"@types/body-parser": "^1.19.2",
|
||||
"@types/cli-table": "^0.3.1",
|
||||
"@types/debug": "^4.1.7",
|
||||
"@types/discord-rpc": "^4.0.3",
|
||||
"@types/eventsource": "^1.1.10",
|
||||
"@types/express": "^4.17.14",
|
||||
"@types/mkdirp": "^1.0.2",
|
||||
"@types/node": "^18.11.9",
|
||||
"@types/node-notifier": "^8.0.2",
|
||||
"@types/node-persist": "^3.1.3",
|
||||
"@types/react": "^17.0.45",
|
||||
"@types/react-native": "^0.67.7",
|
||||
"@types/read": "^0.0.29",
|
||||
"@types/uuid": "^8.3.4",
|
||||
"@types/yargs": "^17.0.14",
|
||||
"electron": "^21.3.1",
|
||||
"electron-builder": "^23.6.0",
|
||||
"react": "^17.0.2",
|
||||
"react-dom": "^17.0.2",
|
||||
"react-native-web": "^0.17.7",
|
||||
"rollup": "^2.79.1",
|
||||
"rollup-plugin-polyfill-node": "^0.10.2",
|
||||
"ts-json-schema-generator": "^1.1.2",
|
||||
"typescript": "^4.9.3"
|
||||
"@rollup/plugin-alias": "^5.1.1",
|
||||
"@rollup/plugin-commonjs": "^28.0.3",
|
||||
"@rollup/plugin-html": "^2.0.0",
|
||||
"@rollup/plugin-json": "^6.1.0",
|
||||
"@rollup/plugin-node-resolve": "^16.0.1",
|
||||
"@rollup/plugin-replace": "^6.0.2",
|
||||
"@types/body-parser": "^1.19.5",
|
||||
"@types/cli-table": "^0.3.4",
|
||||
"@types/debug": "^4.1.12",
|
||||
"@types/discord-rpc": "^4.0.8",
|
||||
"@types/eventsource": "^1.1.15",
|
||||
"@types/express": "^4.17.21",
|
||||
"@types/mime-types": "^2.1.4",
|
||||
"@types/node": "^20.17.30",
|
||||
"@types/node-notifier": "^8.0.5",
|
||||
"@types/node-persist": "^3.1.8",
|
||||
"@types/react": "^19.1.2",
|
||||
"@types/react-native": "^0.73.0",
|
||||
"@types/yargs": "^17.0.32",
|
||||
"electron": "^30.0.1",
|
||||
"electron-builder": "^24.13.3",
|
||||
"i18next": "^22.4.6",
|
||||
"mime-types": "^2.1.35",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0",
|
||||
"react-i18next": "^12.1.1",
|
||||
"react-native-web": "^0.20.0",
|
||||
"rollup": "^4.39.0",
|
||||
"rollup-plugin-polyfill-node": "^0.13.0",
|
||||
"ts-json-schema-generator": "^2.1.1",
|
||||
"typescript": "^5.4.5"
|
||||
},
|
||||
"build": {
|
||||
"appId": "uk.org.fancy.nxapi.app",
|
||||
"productName": "Nintendo Switch Online",
|
||||
"copyright": "Copyright © 2022 Samuel Elliott",
|
||||
"copyright": "Copyright © 2023 Ellie",
|
||||
"npmRebuild": false,
|
||||
"files": [
|
||||
"dist/app/bundle",
|
||||
|
|
@ -99,7 +102,9 @@
|
|||
"!dist/app/package",
|
||||
"!**/node_modules/**/*",
|
||||
"resources/app",
|
||||
"resources/common"
|
||||
"resources/common",
|
||||
"!resources/common/remote-config.json",
|
||||
"resources/cli"
|
||||
],
|
||||
"asar": false,
|
||||
"extraMetadata": {
|
||||
|
|
@ -132,8 +137,28 @@
|
|||
]
|
||||
}
|
||||
],
|
||||
"publish": [],
|
||||
"mac": {
|
||||
"extraFiles": [
|
||||
{
|
||||
"from": "resources/build/app/cli-macos.sh",
|
||||
"to": "bin/nxapi"
|
||||
}
|
||||
],
|
||||
"identity": null
|
||||
},
|
||||
"linux": {
|
||||
"category": "Utility",
|
||||
"extraFiles": [
|
||||
{
|
||||
"from": "resources/build/app/cli-linux.sh",
|
||||
"to": "nxapi"
|
||||
}
|
||||
]
|
||||
},
|
||||
"deb": {
|
||||
"afterInstall": "resources/build/app/deb/postinst",
|
||||
"afterRemove": "resources/build/app/deb/postrm"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
8
resources/build/app/cli-linux.sh
Executable file
8
resources/build/app/cli-linux.sh
Executable file
|
|
@ -0,0 +1,8 @@
|
|||
#!/bin/bash
|
||||
|
||||
# Run as /opt/Nintendo Switch Online/nxapi
|
||||
|
||||
APP_BUNDLE_PATH="$(dirname "$0")"
|
||||
export ELECTRON_RUN_AS_NODE=1
|
||||
|
||||
exec "$APP_BUNDLE_PATH/nxapi-app" "$APP_BUNDLE_PATH/resources/app/dist/bundle/cli-bundle.js" $@
|
||||
8
resources/build/app/cli-macos.sh
Executable file
8
resources/build/app/cli-macos.sh
Executable file
|
|
@ -0,0 +1,8 @@
|
|||
#!/bin/sh
|
||||
|
||||
# Run as Nintendo Switch Online.app/Contents/bin/nxapi
|
||||
|
||||
APP_BUNDLE_PATH="$(dirname "$0")/../.."
|
||||
export ELECTRON_RUN_AS_NODE=1
|
||||
|
||||
exec "$APP_BUNDLE_PATH/Contents/MacOS/Nintendo Switch Online" "$APP_BUNDLE_PATH/Contents/Resources/app/dist/bundle/cli-bundle.js" $@
|
||||
12
resources/build/app/deb/postinst
Executable file
12
resources/build/app/deb/postinst
Executable file
|
|
@ -0,0 +1,12 @@
|
|||
#!/bin/bash
|
||||
|
||||
ln -sf '/opt/Nintendo Switch Online/nxapi' '/usr/bin/nxapi'
|
||||
|
||||
# Link to the binary
|
||||
ln -sf '/opt/Nintendo Switch Online/nxapi-app' '/usr/bin/nxapi-app'
|
||||
|
||||
# SUID chrome-sandbox for Electron 5+
|
||||
chmod 4755 '/opt/Nintendo Switch Online/chrome-sandbox' || true
|
||||
|
||||
update-mime-database /usr/share/mime || true
|
||||
update-desktop-database /usr/share/applications || true
|
||||
6
resources/build/app/deb/postrm
Executable file
6
resources/build/app/deb/postrm
Executable file
|
|
@ -0,0 +1,6 @@
|
|||
#!/bin/bash
|
||||
|
||||
rm -f '/usr/bin/nxapi'
|
||||
|
||||
# Delete the link to the binary
|
||||
rm -f '/usr/bin/nxapi-app'
|
||||
|
|
@ -11,8 +11,8 @@ const git = (...args) => execFile('git', args, options).then(({stdout}) => stdou
|
|||
const pkg = JSON.parse(await fs.readFile(new URL('../../package.json', import.meta.url), 'utf-8'));
|
||||
|
||||
const [revision, branch_str, changed_files_str, tags_str, commit_count_str] = await Promise.all([
|
||||
git('rev-parse', 'HEAD'),
|
||||
git('rev-parse', '--abbrev-ref', 'HEAD'),
|
||||
process.env.CI_COMMIT_SHA || git('rev-parse', 'HEAD'),
|
||||
process.env.CI_COMMIT_BRANCH || git('rev-parse', '--abbrev-ref', 'HEAD'),
|
||||
git('diff', '--name-only', 'HEAD'),
|
||||
git('log', '--tags', '--no-walk', '--pretty=%D'),
|
||||
git('rev-list', '--count', 'HEAD'),
|
||||
|
|
|
|||
|
|
@ -10,8 +10,8 @@ const git = (...args) => execFile('git', args, options).then(({stdout}) => stdou
|
|||
const pkg = JSON.parse(await fs.readFile(new URL('../../package.json', import.meta.url), 'utf-8'));
|
||||
|
||||
const [revision, branch, changed_files] = await Promise.all([
|
||||
git('rev-parse', 'HEAD'),
|
||||
git('rev-parse', '--abbrev-ref', 'HEAD'),
|
||||
process.env.CI_COMMIT_SHA || git('rev-parse', 'HEAD'),
|
||||
process.env.CI_COMMIT_BRANCH || git('rev-parse', '--abbrev-ref', 'HEAD'),
|
||||
git('diff', '--name-only', 'HEAD'),
|
||||
]);
|
||||
|
||||
|
|
@ -42,4 +42,28 @@ pkg.__nxapi_git = pkg.__nxapi_git ?? {
|
|||
changed_files: changed_files.length ? changed_files.split('\n') : [],
|
||||
};
|
||||
|
||||
pkg.__nxapi_ci = pkg.__nxapi_ci ?? (process.env.GITLAB_CI ? {
|
||||
type: 'gitlab',
|
||||
server: process.env.CI_SERVER_URL,
|
||||
project: {
|
||||
id: process.env.CI_PROJECT_ID,
|
||||
path: process.env.CI_PROJECT_PATH,
|
||||
url: process.env.CI_PROJECT_URL,
|
||||
},
|
||||
pipeline: {
|
||||
id: process.env.CI_PIPELINE_ID,
|
||||
iid: process.env.CI_PIPELINE_IID,
|
||||
url: process.env.CI_PIPELINE_URL,
|
||||
},
|
||||
} : process.env.CI ? null : undefined);
|
||||
|
||||
pkg.__nxapi_auth = process.env.NXAPI_AUTH_CLI_CLIENT_ID || process.env.NXAPI_AUTH_APP_CLIENT_ID ? {
|
||||
cli: process.env.NXAPI_AUTH_CLI_CLIENT_ID ? {
|
||||
client_id: process.env.NXAPI_AUTH_CLI_CLIENT_ID,
|
||||
} : undefined,
|
||||
app: process.env.NXAPI_AUTH_APP_CLIENT_ID ? {
|
||||
client_id: process.env.NXAPI_AUTH_APP_CLIENT_ID,
|
||||
} : undefined,
|
||||
} : undefined;
|
||||
|
||||
await fs.writeFile(new URL('../../package.json', import.meta.url), JSON.stringify(pkg, null, 4) + '\n', 'utf-8');
|
||||
|
|
|
|||
BIN
resources/cli/fonts/opensans-normal-400.ttf
Normal file
BIN
resources/cli/fonts/opensans-normal-400.ttf
Normal file
Binary file not shown.
BIN
resources/cli/fonts/opensans-normal-500.ttf
Normal file
BIN
resources/cli/fonts/opensans-normal-500.ttf
Normal file
Binary file not shown.
|
|
@ -1,24 +1,28 @@
|
|||
{
|
||||
"require_version": [],
|
||||
"log_encryption_key": "E2Sii_7drCzK-68RsEoArmopiAIlZD_6TMA2F_UAAU0",
|
||||
"coral": {
|
||||
"znca_version": "2.4.0"
|
||||
"znca_version": "2.12.0"
|
||||
},
|
||||
"coral_auth": {
|
||||
"default": "imink",
|
||||
"default": [
|
||||
"nxapi",
|
||||
"https:\/\/nxapi-znca-api.fancy.org.uk\/api\/znca"
|
||||
],
|
||||
"splatnet2statink": null,
|
||||
"flapg": {},
|
||||
"flapg": null,
|
||||
"imink": {}
|
||||
},
|
||||
"moon": {
|
||||
"znma_version": "1.17.0",
|
||||
"znma_build": "261"
|
||||
"znma_version": "1.18.0",
|
||||
"znma_build": "275"
|
||||
},
|
||||
"coral_gws_nooklink": {
|
||||
"blanco_version": "2.1.1"
|
||||
},
|
||||
"coral_gws_splatnet3": {
|
||||
"app_ver": "2.0.0-bd36a652",
|
||||
"version": "2.0.0",
|
||||
"revision": "bd36a652913aa26b132b84df921e07b20f4a414d"
|
||||
"app_ver": "4.0.0-091d4283",
|
||||
"version": "4.0.0",
|
||||
"revision": "091d428399dc86fd3a7fc43d64bd33b8bd1e875d"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,4 +2,9 @@
|
|||
|
||||
mkdir -p /data/android
|
||||
|
||||
# Logs will be captured by Docker if enabled
|
||||
# This is set here so that running another process with `docker exec` (which
|
||||
# doesn't capture logs) will still write to a file by default
|
||||
export NXAPI_DEBUG_FILE=0
|
||||
|
||||
exec /app/bin/nxapi.js --data-path /data "$@"
|
||||
|
|
|
|||
|
|
@ -2,8 +2,8 @@ import * as path from 'path';
|
|||
import { fileURLToPath } from 'url';
|
||||
import * as fs from 'fs';
|
||||
import * as child_process from 'child_process';
|
||||
import { Module } from 'module';
|
||||
|
||||
import typescript from '@rollup/plugin-typescript';
|
||||
import commonjs from '@rollup/plugin-commonjs';
|
||||
import alias from '@rollup/plugin-alias';
|
||||
import replace from '@rollup/plugin-replace';
|
||||
|
|
@ -18,6 +18,14 @@ const default_remote_config =
|
|||
JSON.parse(fs.readFileSync(path.join(dir, 'resources', 'common', 'remote-config.json'), 'utf-8'));
|
||||
|
||||
const git = (() => {
|
||||
if (process.env.GITLAB_CI && process.env.CI_COMMIT_SHA) {
|
||||
return {
|
||||
revision: process.env.CI_COMMIT_SHA,
|
||||
branch: process.env.CI_COMMIT_BRANCH || null,
|
||||
changed_files: [],
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
fs.statSync(path.join(dir, '.git'));
|
||||
} catch (err) {
|
||||
|
|
@ -34,7 +42,7 @@ const git = (() => {
|
|||
branch: branch && branch !== 'HEAD' ? branch : null,
|
||||
changed_files: changed_files.length ? changed_files.split('\n') : [],
|
||||
};
|
||||
})();;
|
||||
})();
|
||||
|
||||
// If CI_COMMIT_TAG is set this is a tagged version for release
|
||||
const release = process.env.NODE_ENV === 'production' ? process.env.CI_COMMIT_TAG || null : null;
|
||||
|
|
@ -43,12 +51,14 @@ const release = process.env.NODE_ENV === 'production' ? process.env.CI_COMMIT_TA
|
|||
* @type {import('@rollup/plugin-replace').RollupReplaceOptions}
|
||||
*/
|
||||
const replace_options = {
|
||||
include: ['src/util/product.ts'],
|
||||
include: ['dist/util/product.js'],
|
||||
values: {
|
||||
'globalThis.__NXAPI_BUNDLE_PKG__': JSON.stringify(pkg),
|
||||
'globalThis.__NXAPI_BUNDLE_GIT__': JSON.stringify(git),
|
||||
'globalThis.__NXAPI_BUNDLE_RELEASE__': JSON.stringify(release),
|
||||
'globalThis.__NXAPI_BUNDLE_DEFAULT_REMOTE_CONFIG__': JSON.stringify(default_remote_config),
|
||||
'globalThis.__NXAPI_BUNDLE_NXAPI_AUTH_CLI_CLIENT_ID__': JSON.stringify(process.env.NXAPI_AUTH_CLI_CLIENT_ID),
|
||||
'globalThis.__NXAPI_BUNDLE_NXAPI_AUTH_APP_CLIENT_ID__': JSON.stringify(process.env.NXAPI_AUTH_APP_CLIENT_ID),
|
||||
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV ?? 'development'),
|
||||
},
|
||||
preventAssignment: true,
|
||||
|
|
@ -58,20 +68,21 @@ const replace_options = {
|
|||
* @type {import('rollup').RollupOptions['watch']}
|
||||
*/
|
||||
const watch = {
|
||||
include: 'src/**',
|
||||
include: 'dist/**',
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {import('rollup').RollupOptions}
|
||||
*/
|
||||
const main = {
|
||||
input: ['src/cli-entry.ts', 'src/app/main/index.ts'],
|
||||
input: ['dist/cli-entry.js', 'dist/app/app-init.js', 'dist/app/main/index.js'],
|
||||
output: {
|
||||
dir: 'dist/bundle',
|
||||
format: 'es',
|
||||
sourcemap: true,
|
||||
entryFileNames: chunk => {
|
||||
if (chunk.name === 'cli-entry') return 'cli-bundle.js';
|
||||
if (chunk.name === 'app-init') return 'app-init-bundle.js';
|
||||
if (chunk.name === 'index') return 'app-main-bundle.js';
|
||||
return 'entry-' + chunk.name + '.js';
|
||||
},
|
||||
|
|
@ -79,19 +90,18 @@ const main = {
|
|||
},
|
||||
plugins: [
|
||||
replace(replace_options),
|
||||
typescript({
|
||||
outDir: 'dist/bundle/ts',
|
||||
noEmit: true,
|
||||
declaration: false,
|
||||
}),
|
||||
commonjs({
|
||||
// the ".ts" extension is required
|
||||
extensions: ['.js', '.jsx', '.ts', '.tsx'],
|
||||
esmExternals: true,
|
||||
// events and stream modify module.exports
|
||||
requireReturnsDefault: 'preferred',
|
||||
}),
|
||||
json(),
|
||||
alias({
|
||||
entries: [
|
||||
{find: 'string_decoder/', replacement: 'node:string_decoder'},
|
||||
...Module.builtinModules.map(m => ({find: m, replacement: 'node:' + m})),
|
||||
],
|
||||
}),
|
||||
nodeResolve({
|
||||
exportConditions: ['node'],
|
||||
browser: false,
|
||||
|
|
@ -99,6 +109,7 @@ const main = {
|
|||
}),
|
||||
],
|
||||
external: [
|
||||
'electron',
|
||||
'node-notifier',
|
||||
'register-scheme',
|
||||
'bindings',
|
||||
|
|
@ -110,29 +121,27 @@ const main = {
|
|||
* @type {import('rollup').RollupOptions}
|
||||
*/
|
||||
const app_entry = {
|
||||
input: 'src/app/app-entry.cts',
|
||||
input: 'dist/app/app-entry.cjs',
|
||||
output: {
|
||||
file: 'dist/bundle/app-entry.cjs',
|
||||
format: 'iife',
|
||||
inlineDynamicImports: true,
|
||||
sourcemap: true,
|
||||
globals: {
|
||||
'electron': 'require("electron")',
|
||||
},
|
||||
},
|
||||
plugins: [
|
||||
replace(replace_options),
|
||||
replace({
|
||||
include: ['src/app/app-entry.cts'],
|
||||
include: ['dist/app/app-entry.cjs'],
|
||||
values: {
|
||||
'__NXAPI_BUNDLE_APP_MAIN__': JSON.stringify('./app-main-bundle.js'),
|
||||
'__NXAPI_BUNDLE_APP_INIT__': JSON.stringify('./app-init-bundle.js'),
|
||||
},
|
||||
preventAssignment: true,
|
||||
}),
|
||||
typescript({
|
||||
noEmit: true,
|
||||
declaration: false,
|
||||
}),
|
||||
commonjs({
|
||||
// the ".ts" extension is required
|
||||
extensions: ['.js', '.jsx', '.ts', '.tsx'],
|
||||
esmExternals: true,
|
||||
// events and stream modify module.exports
|
||||
requireReturnsDefault: 'preferred',
|
||||
|
|
@ -146,7 +155,10 @@ const app_entry = {
|
|||
],
|
||||
external: [
|
||||
'electron',
|
||||
path.resolve(__dirname, 'src/app/app-main-bundle.js'),
|
||||
path.resolve(dir, 'dist/app/app-main-bundle.js'),
|
||||
path.resolve(dir, 'dist/app/app-init-bundle.js'),
|
||||
path.resolve(dir, 'dist/app/app-init.js'),
|
||||
path.resolve(dir, 'dist/app/main/index.js'),
|
||||
],
|
||||
watch,
|
||||
};
|
||||
|
|
@ -155,7 +167,7 @@ const app_entry = {
|
|||
* @type {import('rollup').RollupOptions}
|
||||
*/
|
||||
const app_preload = {
|
||||
input: 'src/app/preload/index.ts',
|
||||
input: 'dist/app/preload/index.js',
|
||||
output: {
|
||||
file: 'dist/app/bundle/preload.cjs',
|
||||
format: 'cjs',
|
||||
|
|
@ -163,13 +175,7 @@ const app_preload = {
|
|||
},
|
||||
plugins: [
|
||||
replace(replace_options),
|
||||
typescript({
|
||||
noEmit: true,
|
||||
declaration: false,
|
||||
}),
|
||||
commonjs({
|
||||
// the ".ts" extension is required
|
||||
extensions: ['.js', '.jsx', '.ts', '.tsx'],
|
||||
esmExternals: true,
|
||||
}),
|
||||
nodeResolve({
|
||||
|
|
@ -187,20 +193,14 @@ const app_preload = {
|
|||
* @type {import('rollup').RollupOptions}
|
||||
*/
|
||||
const app_preload_webservice = {
|
||||
input: 'src/app/preload-webservice/index.ts',
|
||||
input: 'dist/app/preload-webservice/index.js',
|
||||
output: {
|
||||
file: 'dist/app/bundle/preload-webservice.cjs',
|
||||
format: 'cjs',
|
||||
},
|
||||
plugins: [
|
||||
replace(replace_options),
|
||||
typescript({
|
||||
noEmit: true,
|
||||
declaration: false,
|
||||
}),
|
||||
commonjs({
|
||||
// the ".ts" extension is required
|
||||
extensions: ['.js', '.jsx', '.ts', '.tsx'],
|
||||
esmExternals: true,
|
||||
}),
|
||||
nodeResolve({
|
||||
|
|
@ -218,7 +218,7 @@ const app_preload_webservice = {
|
|||
* @type {import('rollup').RollupOptions}
|
||||
*/
|
||||
const app_browser = {
|
||||
input: 'src/app/browser/index.ts',
|
||||
input: 'dist/app/browser/index.js',
|
||||
output: {
|
||||
dir: 'dist/app/bundle',
|
||||
format: 'es',
|
||||
|
|
@ -238,14 +238,7 @@ const app_browser = {
|
|||
title: 'nxapi',
|
||||
}),
|
||||
replace(replace_options),
|
||||
typescript({
|
||||
outDir: 'dist/app/bundle/ts',
|
||||
noEmit: true,
|
||||
declaration: false,
|
||||
}),
|
||||
commonjs({
|
||||
// the ".ts" extension is required
|
||||
extensions: ['.js', '.jsx', '.ts', '.tsx'],
|
||||
esmExternals: true,
|
||||
}),
|
||||
nodePolyfill(),
|
||||
|
|
@ -254,7 +247,8 @@ const app_browser = {
|
|||
// react-native-web has an ESM and CommonJS build. By default the ESM build is
|
||||
// used when resolving react-native-web. For some reason this causes both versions
|
||||
// to be included in the bundle, so here we explicitly use the CommonJS build.
|
||||
{find: 'react-native', replacement: path.resolve(__dirname, 'node_modules', 'react-native-web', 'dist', 'cjs', 'index.js')},
|
||||
{find: 'react-native', replacement: path.resolve(dir, 'node_modules', 'react-native-web', 'dist', 'cjs', 'index.js')},
|
||||
{find: 'react-native-web', replacement: path.resolve(dir, 'node_modules', 'react-native-web', 'dist', 'cjs', 'index.js')},
|
||||
|
||||
// rollup-plugin-polyfill-node doesn't support node: module identifiers
|
||||
{find: /^node:(.+)/, replacement: '$1'},
|
||||
|
|
@ -268,10 +262,12 @@ const app_browser = {
|
|||
watch,
|
||||
};
|
||||
|
||||
const skip = process.env.BUNDLE_SKIP?.split(',') ?? [];
|
||||
|
||||
export default [
|
||||
main,
|
||||
app_entry,
|
||||
app_preload,
|
||||
app_preload_webservice,
|
||||
app_browser,
|
||||
];
|
||||
!skip?.includes('main') && main,
|
||||
!skip?.includes('app-entry') && app_entry,
|
||||
!skip?.includes('app-preload') && app_preload,
|
||||
!skip?.includes('app-preload-webservice') && app_preload_webservice,
|
||||
!skip?.includes('app-browser') && app_browser,
|
||||
].filter(c => c);
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ export interface CoralSuccessResponse<T = unknown> {
|
|||
correlationId: string;
|
||||
}
|
||||
|
||||
export interface CoralErrorResponse {
|
||||
export interface CoralError {
|
||||
status: CoralStatus | number;
|
||||
errorMessage: string;
|
||||
correlationId: string;
|
||||
|
|
@ -53,7 +53,7 @@ export enum CoralStatus {
|
|||
// UNKNOWN = -1,
|
||||
}
|
||||
|
||||
export type CoralResponse<T = unknown> = CoralSuccessResponse<T> | CoralErrorResponse;
|
||||
export type CoralResponse<T = unknown> = CoralSuccessResponse<T> | CoralError;
|
||||
|
||||
export interface AccountLoginParameter {
|
||||
naIdToken: string;
|
||||
|
|
@ -67,7 +67,7 @@ export interface AccountLoginParameter {
|
|||
|
||||
/** /v3/Account/Login */
|
||||
export interface AccountLogin {
|
||||
user: CurrentUser;
|
||||
user: CurrentUser<true>;
|
||||
webApiServerCredential: {
|
||||
accessToken: string;
|
||||
expiresIn: number;
|
||||
|
|
@ -81,6 +81,18 @@ export interface AccountLogin {
|
|||
/** /v3/Account/GetToken, /v3/Extension/Account/GetToken */
|
||||
export type AccountToken = AccountLogin;
|
||||
|
||||
/** /v4/Account/Login */
|
||||
export interface AccountLogin_4 {
|
||||
user: CurrentUser<false>;
|
||||
webApiServerCredential: {
|
||||
accessToken: string;
|
||||
expiresIn: number;
|
||||
};
|
||||
}
|
||||
|
||||
/** /v4/Account/GetToken, /v4/Extension/Account/GetToken */
|
||||
export type AccountToken_4 = AccountLogin_4;
|
||||
|
||||
export interface AccountTokenParameter {
|
||||
naIdToken: string;
|
||||
naBirthday: string;
|
||||
|
|
@ -103,23 +115,112 @@ export interface Announcement {
|
|||
linkText?: string;
|
||||
}
|
||||
|
||||
/** /v4/Announcement/List */
|
||||
export type Announcements_4 = Announcement_4[];
|
||||
|
||||
export interface AnnouncementBase_4 {
|
||||
id: string;
|
||||
type: AnnouncementType;
|
||||
title: string;
|
||||
deliversAt: number;
|
||||
imageUri: string;
|
||||
image2Uri?: string;
|
||||
hasRead: boolean;
|
||||
}
|
||||
|
||||
export enum AnnouncementType {
|
||||
OPERATION = 'OPERATION',
|
||||
FRIEND_REQUEST = 'FRIEND_REQUEST',
|
||||
}
|
||||
|
||||
export type Announcement_4 = AnnouncementOperation | AnnouncementFriendRequest;
|
||||
|
||||
export interface AnnouncementOperation extends AnnouncementBase_4 {
|
||||
type: AnnouncementType.OPERATION;
|
||||
operation: AnnouncementOperationContents;
|
||||
}
|
||||
export interface AnnouncementOperationContents {
|
||||
contents: string;
|
||||
}
|
||||
export interface AnnouncementFriendRequest extends AnnouncementBase_4 {
|
||||
type: AnnouncementType.FRIEND_REQUEST;
|
||||
friendRequest: AnnouncementFriendRequestContents;
|
||||
}
|
||||
export interface AnnouncementFriendRequestContents {
|
||||
nsaId: string;
|
||||
friendRequestId: string;
|
||||
}
|
||||
|
||||
/** /v3/Friend/List */
|
||||
export interface Friends {
|
||||
friends: Friend[];
|
||||
}
|
||||
|
||||
/** /v4/Friend/List */
|
||||
export interface Friends_4 {
|
||||
friends: Friend_4[];
|
||||
extractFriendsIds: string[];
|
||||
}
|
||||
|
||||
export interface Friend {
|
||||
id: number;
|
||||
nsaId: string;
|
||||
imageUri: string;
|
||||
image2Uri: string;
|
||||
name: string;
|
||||
isFriend: boolean;
|
||||
isFavoriteFriend: boolean;
|
||||
isServiceUser: boolean;
|
||||
isNew: boolean;
|
||||
friendCreatedAt: number;
|
||||
presence: Presence;
|
||||
route: FriendRoute;
|
||||
presence: PresenceOnline | PresenceOffline;
|
||||
}
|
||||
|
||||
/** /v4/Friend/Show */
|
||||
export interface Friend_4 extends Friend {
|
||||
isOnlineNotificationEnabled: boolean;
|
||||
presence: PresenceOnline_4 | PresenceOffline;
|
||||
}
|
||||
|
||||
export interface FriendRoute {
|
||||
appName: string;
|
||||
/** In-game player name */
|
||||
userName: string;
|
||||
shopUri: string;
|
||||
imageUri: string;
|
||||
// if not IN_APP/NINTENDO_ACCOUNT all other properties are empty strings
|
||||
channel: FriendRouteChannel;
|
||||
}
|
||||
|
||||
export enum FriendRouteChannel {
|
||||
/** Added from friend code lookup on a Switch console or using coral */
|
||||
FRIEND_CODE = 'FRIEND_CODE',
|
||||
/** Added from search for local users */
|
||||
NX_FACED = 'NX_FACED',
|
||||
/**
|
||||
* Added from users you've played with
|
||||
* Shows the application details (appName, shopUri, imageUri) and in-game name (userName)
|
||||
*/
|
||||
IN_APP = 'IN_APP',
|
||||
/**
|
||||
* Added from friend suggestions for smart device game friends linked to the same Nintendo Account
|
||||
* Shows the client name (FriendRoute.appName)
|
||||
*/
|
||||
NINTENDO_ACCOUNT = 'NINTENDO_ACCOUNT',
|
||||
'3DS' = '3DS',
|
||||
NNID = 'NNID',
|
||||
TWITTER = 'TWITTER',
|
||||
FACEBOOK = 'FACEBOOK',
|
||||
WECHAT = 'WECHAT',
|
||||
/** Added from GameChat */
|
||||
CAMPUS = 'CAMPUS',
|
||||
}
|
||||
|
||||
export type CreateFriendRequestChannel =
|
||||
FriendRouteChannel.FRIEND_CODE |
|
||||
FriendRouteChannel.CAMPUS;
|
||||
|
||||
export interface Presence {
|
||||
state: PresenceState;
|
||||
/**
|
||||
|
|
@ -128,7 +229,19 @@ export interface Presence {
|
|||
*/
|
||||
updatedAt: number;
|
||||
logoutAt: number;
|
||||
game: Game | {};
|
||||
game: PresenceGame | {};
|
||||
}
|
||||
|
||||
export interface PresenceOnline extends Presence {
|
||||
state: PresenceState.ONLINE | PresenceState.PLAYING;
|
||||
game: PresenceGame;
|
||||
}
|
||||
export interface PresenceOnline_4 extends PresenceOnline {
|
||||
platform: PresencePlatform;
|
||||
}
|
||||
export interface PresenceOffline extends Presence {
|
||||
state: PresenceState.OFFLINE | PresenceState.INACTIVE;
|
||||
game: {};
|
||||
}
|
||||
|
||||
export enum PresenceState {
|
||||
|
|
@ -138,14 +251,17 @@ export enum PresenceState {
|
|||
INACTIVE = 'INACTIVE',
|
||||
/** The user is selected in an application */
|
||||
ONLINE = 'ONLINE',
|
||||
/**
|
||||
* The user is selected in an application and playing online.
|
||||
* (Is this set by Nintendo's servers if the user is in a session on Nintendo's servers, or by the application
|
||||
* running on the console?)
|
||||
*/
|
||||
/** The user is selected in an application and playing online */
|
||||
PLAYING = 'PLAYING',
|
||||
}
|
||||
|
||||
export enum PresencePlatform {
|
||||
/** Nintendo Switch */
|
||||
NX = 1,
|
||||
/** Nintendo Switch 2 */
|
||||
OUNCE = 2,
|
||||
}
|
||||
|
||||
export interface Game {
|
||||
name: string;
|
||||
imageUri: string;
|
||||
|
|
@ -153,6 +269,9 @@ export interface Game {
|
|||
totalPlayTime: number;
|
||||
/** 0 if never played before */
|
||||
firstPlayedAt: number;
|
||||
}
|
||||
|
||||
export interface PresenceGame extends Game {
|
||||
sysDescription: string;
|
||||
}
|
||||
|
||||
|
|
@ -167,13 +286,18 @@ export interface FriendCodeUser {
|
|||
id: number;
|
||||
nsaId: string;
|
||||
imageUri: string;
|
||||
image2Uri: string;
|
||||
name: string;
|
||||
isBlocking: boolean;
|
||||
extras: {};
|
||||
}
|
||||
|
||||
/** /v1/Game/ListWebServices */
|
||||
export type WebServices = WebService[];
|
||||
|
||||
/** /v4/GameWebService/List */
|
||||
export type WebServices_4 = WebService_4[];
|
||||
|
||||
export interface WebService {
|
||||
id: number;
|
||||
uri: string;
|
||||
|
|
@ -183,6 +307,12 @@ export interface WebService {
|
|||
imageUri: string;
|
||||
}
|
||||
|
||||
export interface WebService_4 extends WebService {
|
||||
startDate: number;
|
||||
isNotificationSupported: boolean;
|
||||
isNotificationAllowed: boolean;
|
||||
}
|
||||
|
||||
export interface WebServiceAttribute {
|
||||
attrValue: string;
|
||||
attrKey: string;
|
||||
|
|
@ -196,7 +326,7 @@ export interface WebServiceTokenParameter {
|
|||
f: string;
|
||||
}
|
||||
|
||||
/** /v2/Game/GetWebServiceToken, /v2/Extension/Game/GetWebServiceToken */
|
||||
/** /v2/Game/GetWebServiceToken, /v2/Extension/Game/GetWebServiceToken, /v4/Game/GetWebServiceToken */
|
||||
export interface WebServiceToken {
|
||||
accessToken: string;
|
||||
expiresIn: number;
|
||||
|
|
@ -240,38 +370,52 @@ export interface User {
|
|||
id: number;
|
||||
nsaId: string;
|
||||
imageUri: string;
|
||||
image2Uri: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
/** /v3/User/ShowSelf */
|
||||
export interface CurrentUser {
|
||||
/** /v4/User/ShowSelf */
|
||||
export interface CurrentUser<WithNintendoAccount extends boolean = true> {
|
||||
id: number;
|
||||
nsaId: string;
|
||||
imageUri: string;
|
||||
image2Uri: string;
|
||||
name: string;
|
||||
supportId: string;
|
||||
isChildRestricted: boolean;
|
||||
etag: string;
|
||||
links: {
|
||||
nintendoAccount: {
|
||||
membership: {
|
||||
active: {
|
||||
active: boolean;
|
||||
} | boolean;
|
||||
};
|
||||
};
|
||||
friendCode: {
|
||||
regenerable: boolean;
|
||||
regenerableAt: number;
|
||||
id: string;
|
||||
};
|
||||
links: (boolean extends WithNintendoAccount ? {
|
||||
nintendoAccount?: CurrentUserNintendoAccountLink;
|
||||
} : true extends WithNintendoAccount ? {
|
||||
nintendoAccount: CurrentUserNintendoAccountLink;
|
||||
} : {}) & {
|
||||
friendCode: CurrentUserFriendCodeLink;
|
||||
};
|
||||
permissions: {
|
||||
playLog: PlayLogPermissions;
|
||||
presence: PresencePermissions;
|
||||
friendRequestReception: boolean;
|
||||
};
|
||||
presence: Presence;
|
||||
presence: PresenceOnline_4 | PresenceOffline;
|
||||
}
|
||||
|
||||
export interface CurrentUserNintendoAccountLink {
|
||||
membership: {
|
||||
active: boolean;
|
||||
};
|
||||
}
|
||||
export interface CurrentUserFriendCodeLink {
|
||||
regenerable: boolean;
|
||||
regenerableAt: number;
|
||||
id: string;
|
||||
}
|
||||
|
||||
export enum PlayLogPermissions {
|
||||
EVERYONE = 'EVERYONE',
|
||||
FRIENDS = 'FRIENDS',
|
||||
FAVORITE_FRIENDS = 'FAVORITE_FRIENDS',
|
||||
SELF = 'SELF',
|
||||
}
|
||||
export enum PresencePermissions {
|
||||
FRIENDS = 'FRIENDS',
|
||||
FAVORITE_FRIENDS = 'FAVORITE_FRIENDS',
|
||||
|
|
@ -282,7 +426,9 @@ export enum PresencePermissions {
|
|||
export interface CurrentUserPermissions {
|
||||
etag: string;
|
||||
permissions: {
|
||||
playLog: PlayLogPermissions;
|
||||
presence: PresencePermissions;
|
||||
friendRequestReception: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -295,3 +441,226 @@ export interface UpdateCurrentUserPermissionsParameter {
|
|||
};
|
||||
etag: string;
|
||||
}
|
||||
|
||||
/** /v4/User/PlayLog/Show */
|
||||
export type UserPlayLog = Game[];
|
||||
|
||||
/** /v3/FriendRequest/Received/List, /v4/FriendRequest/Received/List */
|
||||
export interface ReceivedFriendRequests {
|
||||
friendRequests: ReceivedFriendRequest[];
|
||||
}
|
||||
|
||||
export interface ReceivedFriendRequest {
|
||||
/**
|
||||
* 16 hex digits, similar to NSA IDs, but this is not the sender's NSA ID.
|
||||
* Matches the sender's SentFriendRequest.id.
|
||||
*/
|
||||
id: string;
|
||||
route: FriendRoute;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
sender: FriendRequestSender;
|
||||
hasRead: boolean;
|
||||
}
|
||||
|
||||
export type FriendRequestSender = User;
|
||||
|
||||
/** /v3/FriendRequest/Sent/List */
|
||||
export interface SentFriendRequests {
|
||||
friendRequests: SentFriendRequest[];
|
||||
}
|
||||
|
||||
export interface SentFriendRequest {
|
||||
/**
|
||||
* 16 hex digits, similar to NSA IDs, but this is not the recipient's NSA ID.
|
||||
* Matches the recipient's ReceivedFriendRequest.id.
|
||||
*/
|
||||
id: string;
|
||||
route: FriendRoute;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
receiver: FriendRequestReceiver;
|
||||
}
|
||||
|
||||
export type FriendRequestReceiver = User;
|
||||
|
||||
/** /v3/User/Block/List */
|
||||
export interface BlockingUsers {
|
||||
blockingUsers: BlockedUser[];
|
||||
}
|
||||
|
||||
export interface BlockedUser {
|
||||
nsaId: string;
|
||||
name: string;
|
||||
imageUri: string;
|
||||
image2Uri: string;
|
||||
blockedAt: number;
|
||||
}
|
||||
|
||||
/** /v4/Media/List */
|
||||
export interface ListMedia {
|
||||
media: Media[];
|
||||
}
|
||||
|
||||
export interface MediaBase {
|
||||
id: string;
|
||||
type: MediaType;
|
||||
applicationId: string;
|
||||
platformId: MediaPlatform;
|
||||
contentUri: string;
|
||||
contentLength: number;
|
||||
/** 320x180 JPEG image */
|
||||
thumbnailUri: string;
|
||||
/** For system titles, this is an empty string */
|
||||
appName: string;
|
||||
orientation: number;
|
||||
acdIndex: number;
|
||||
extraData: string;
|
||||
capturedAt: number;
|
||||
expiresAt: number;
|
||||
uploadedAt: number;
|
||||
}
|
||||
|
||||
export type Media = MediaImage | MediaVideo;
|
||||
|
||||
export interface MediaImage extends MediaBase {
|
||||
type: MediaType.IMAGE;
|
||||
}
|
||||
export interface MediaVideo extends MediaBase {
|
||||
type: MediaType.VIDEO;
|
||||
/** Video duration (ms) */
|
||||
videoDuration: number;
|
||||
}
|
||||
|
||||
export enum MediaType {
|
||||
IMAGE = 'image',
|
||||
VIDEO = 'video',
|
||||
}
|
||||
export enum MediaPlatform {
|
||||
NINTENDO_SWITCH_2 = 1,
|
||||
}
|
||||
|
||||
export interface ListMediaParameter {
|
||||
count: 100;
|
||||
}
|
||||
|
||||
/** /v5/Hashtag/List */
|
||||
export interface ListHashtag {
|
||||
/** Plain text to prefill share dialog text, e.g. "#NintendoSwitch2 #MarioKartWorld" */
|
||||
tags: string;
|
||||
}
|
||||
|
||||
export interface ListHashtagParameter {
|
||||
applications: ListHashtagParameterApplication[];
|
||||
}
|
||||
export interface ListHashtagParameterApplication {
|
||||
platformId: MediaPlatform;
|
||||
acdIndex: number;
|
||||
extraData: string;
|
||||
applicationId: string;
|
||||
}
|
||||
|
||||
/** /v5/Chat/List */
|
||||
export type ListChat = {} & unknown;
|
||||
|
||||
/** /v5/PushNotification/Settings/List */
|
||||
export interface ListPushNotificationSettings {
|
||||
playInvitation: PushNotificationPlayInvitationScope;
|
||||
chatInvitation: boolean;
|
||||
friendRequest: boolean;
|
||||
}
|
||||
|
||||
export enum PushNotificationPlayInvitationScope {
|
||||
FRIENDS = 'FRIENDS',
|
||||
FAVORITE_FRIENDS = 'FAVORITE_FRIENDS',
|
||||
NONE = 'NONE',
|
||||
}
|
||||
|
||||
/** /v5/PushNotification/Settings/Update */
|
||||
export type UpdatePushNotificationSettingsParameter = UpdatePushNotificationSettingsParameterItem[];
|
||||
|
||||
export type UpdatePushNotificationSettingsParameterItem =
|
||||
UpdatePushNotificationSettingsParameterFriendRequest |
|
||||
UpdatePushNotificationSettingsParameterChatInvitation |
|
||||
UpdatePushNotificationSettingsParameterPlayInvitation |
|
||||
UpdatePushNotificationSettingsParameterGameWebService |
|
||||
UpdatePushNotificationSettingsParameterFriendOnline;
|
||||
|
||||
export interface UpdatePushNotificationSettingsParameterFriendRequest {
|
||||
value: boolean;
|
||||
type: 'friendRequest';
|
||||
}
|
||||
export interface UpdatePushNotificationSettingsParameterChatInvitation {
|
||||
type: 'chatInvitation';
|
||||
value: boolean;
|
||||
}
|
||||
export interface UpdatePushNotificationSettingsParameterPlayInvitation {
|
||||
type: 'playInvitation';
|
||||
scope: PushNotificationPlayInvitationScope;
|
||||
}
|
||||
export interface UpdatePushNotificationSettingsParameterGameWebService {
|
||||
value: boolean;
|
||||
gwsId: number;
|
||||
type: 'gws';
|
||||
}
|
||||
export interface UpdatePushNotificationSettingsParameterFriendOnline {
|
||||
/** NSA ID */
|
||||
friendId: string;
|
||||
type: 'friendOnline';
|
||||
value: boolean;
|
||||
}
|
||||
|
||||
/** /v4/NA/User/LoginFactor/Show */
|
||||
export interface ShowUserLogin {
|
||||
/** Coral user ID */
|
||||
userId: number;
|
||||
/** Nintendo Account email */
|
||||
email?: string;
|
||||
/** Nintendo Account sign-in ID */
|
||||
loginId?: string;
|
||||
}
|
||||
|
||||
/** /v1/Support/SendOpinion */
|
||||
export interface SendOpinionParameter {
|
||||
message: string;
|
||||
category: FeedbackTopic;
|
||||
}
|
||||
export enum FeedbackTopic {
|
||||
ABOUT_GAME_SPECIFIC_SERVICES = 4,
|
||||
FRIEND_FEATURES = 9,
|
||||
THE_ALBUM_FEATURE = 10,
|
||||
FEATURES_YOUD_LIKE_TO_SEE = 6,
|
||||
APP_PROBLEMS = 8,
|
||||
OTHER = 0,
|
||||
}
|
||||
|
||||
//
|
||||
// Unsupported API calls:
|
||||
//
|
||||
// - /v1/Support/SendOpinion
|
||||
// - /v1/Support/ReportUser
|
||||
// - /v3/Extension/Account/GetToken
|
||||
// - /v2/Extension/Game/GetWebServiceToken
|
||||
//
|
||||
// Needs request/response data/types:
|
||||
//
|
||||
// - /v1/Notification/RegisterDevice
|
||||
// - /v1/Notification/UnregisterDevice
|
||||
// - /v4/Announcement/Delete
|
||||
// - /v4/Announcement/FriendRequestAccepted/Delete
|
||||
// - /v4/Announcement/GameWebService/Delete
|
||||
// - /v1/Event/Notify/ActivatedUsers
|
||||
// - /v4/Friend/IsNew/Delete
|
||||
// - /v3/Voip/GetChannelId
|
||||
// - /v1/Voip/GetConfig
|
||||
// - /v3/Voip/Join
|
||||
// - /v1/Voip/Leave
|
||||
// - /v1/Voip/Mute
|
||||
// - /v5/Chat/Show
|
||||
// - /v5/Chat/List
|
||||
// - /v5/Chat/Member/Show
|
||||
// - /v5/Chat/FriendCandidate/List
|
||||
// - /v1/Support/ReportUser
|
||||
//
|
||||
// Also, announcement types other than OPERATION and FRIEND_REQUEST
|
||||
//
|
||||
|
|
|
|||
1038
src/api/coral.ts
1038
src/api/coral.ts
File diff suppressed because it is too large
Load Diff
766
src/api/f.ts
766
src/api/f.ts
|
|
@ -1,22 +1,47 @@
|
|||
import process from 'node:process';
|
||||
import fetch from 'node-fetch';
|
||||
import createDebug from 'debug';
|
||||
import { v4 as uuidgen } from 'uuid';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { fetch, Headers } from 'undici';
|
||||
import { defineResponse, ErrorResponse } from './util.js';
|
||||
import createDebug from '../util/debug.js';
|
||||
import { timeoutSignal } from '../util/misc.js';
|
||||
import { getUserAgent } from '../util/useragent.js';
|
||||
import { client_assertion_provider, client_auth_provider, ClientAssertionProviderInterface } from '../util/nxapi-auth.js';
|
||||
import { ZNCA_API_COMPATIBILITY_VERSION } from './coral.js';
|
||||
import { AccountLoginParameter, AccountTokenParameter, WebServiceTokenParameter } from './coral-types.js';
|
||||
|
||||
const debugS2s = createDebug('nxapi:api:s2s');
|
||||
const debugFlapg = createDebug('nxapi:api:flapg');
|
||||
const debugImink = createDebug('nxapi:api:imink');
|
||||
const debugZncaApi = createDebug('nxapi:api:znca-api');
|
||||
const debugZncaAuth = createDebug('nxapi:api:znca-auth');
|
||||
|
||||
export abstract class ZncaApi {
|
||||
constructor(
|
||||
public useragent?: string
|
||||
) {}
|
||||
|
||||
abstract genf(token: string, hash_method: HashMethod): Promise<FResult>;
|
||||
abstract genf(
|
||||
token: string, hash_method: HashMethod,
|
||||
user?: {na_id: string; coral_user_id?: string;},
|
||||
encrypt_request?: EncryptRequestOptions,
|
||||
): Promise<FResult>;
|
||||
|
||||
encryptRequest?(url: string, token: string | null, data: string): Promise<EncryptRequestResult>;
|
||||
decryptResponse?(data: Uint8Array): Promise<DecryptResponseResult>;
|
||||
|
||||
supportsEncryption(): this is RequestEncryptionProvider {
|
||||
return !!this.encryptRequest && !!this.decryptResponse;
|
||||
}
|
||||
}
|
||||
|
||||
export interface RequestEncryptionProvider {
|
||||
encryptRequest(url: string, token: string | null, data: string): Promise<EncryptRequestResult>;
|
||||
decryptResponse(data: Uint8Array): Promise<DecryptResponseResult>;
|
||||
}
|
||||
export interface EncryptRequestResult {
|
||||
data: Uint8Array;
|
||||
}
|
||||
export interface DecryptResponseResult {
|
||||
data: string;
|
||||
}
|
||||
|
||||
export enum HashMethod {
|
||||
|
|
@ -28,49 +53,6 @@ export enum HashMethod {
|
|||
// flapg
|
||||
//
|
||||
|
||||
/** @deprecated The flapg API no longer requires client authentication */
|
||||
export async function getLoginHash(token: string, timestamp: string | number, useragent?: string) {
|
||||
const { default: { coral_auth: { splatnet2statink: config } } } = await import('../common/remote-config.js');
|
||||
if (!config) throw new Error('Remote configuration prevents splatnet2statink API use');
|
||||
|
||||
debugS2s('Getting login hash');
|
||||
|
||||
const [signal, cancel] = timeoutSignal();
|
||||
const response = await fetch('https://elifessler.com/s2s/api/gen2', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'User-Agent': getUserAgent(useragent),
|
||||
},
|
||||
body: new URLSearchParams({
|
||||
naIdToken: token,
|
||||
timestamp: '' + timestamp,
|
||||
}).toString(),
|
||||
signal,
|
||||
}).finally(cancel);
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw new ErrorResponse('[s2s] Non-200 status code', response, await response.text());
|
||||
}
|
||||
|
||||
const data = await response.json() as LoginHashApiResponse | LoginHashApiError;
|
||||
|
||||
if ('error' in data) {
|
||||
throw new ErrorResponse('[s2s] ' + data.error, response, data);
|
||||
}
|
||||
|
||||
debugS2s('Got login hash "%s"', data.hash, data);
|
||||
|
||||
return data.hash;
|
||||
}
|
||||
|
||||
export interface LoginHashApiResponse {
|
||||
hash: string;
|
||||
}
|
||||
export interface LoginHashApiError {
|
||||
error: string;
|
||||
}
|
||||
|
||||
export async function flapg(
|
||||
hash_method: HashMethod, token: string,
|
||||
timestamp?: string | number, request_id?: string,
|
||||
|
|
@ -102,7 +84,7 @@ export async function flapg(
|
|||
}).finally(cancel);
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw new ErrorResponse<FlapgApiError>('[flapg] Non-200 status code', response, await response.text());
|
||||
throw await ErrorResponse.fromResponse(response, '[flapg] Non-200 status code');
|
||||
}
|
||||
|
||||
const data = await response.json() as FlapgApiResponse;
|
||||
|
|
@ -131,13 +113,8 @@ export type FlapgApiResponse = IminkFResponse;
|
|||
export type FlapgApiError = IminkFError;
|
||||
|
||||
export class ZncaApiFlapg extends ZncaApi {
|
||||
/** @deprecated */
|
||||
async getLoginHash(id_token: string, timestamp: string) {
|
||||
return getLoginHash(id_token, timestamp, this.useragent);
|
||||
}
|
||||
|
||||
async genf(token: string, hash_method: HashMethod) {
|
||||
const request_id = uuidgen();
|
||||
const request_id = randomUUID();
|
||||
|
||||
const result = await flapg(hash_method, token, undefined, request_id, this.useragent);
|
||||
|
||||
|
|
@ -158,7 +135,8 @@ export class ZncaApiFlapg extends ZncaApi {
|
|||
export async function iminkf(
|
||||
hash_method: HashMethod, token: string,
|
||||
timestamp?: number, request_id?: string,
|
||||
useragent?: string
|
||||
user?: {na_id: string; coral_user_id?: string;},
|
||||
useragent?: string,
|
||||
) {
|
||||
const { default: { coral_auth: { imink: config } } } = await import('../common/remote-config.js');
|
||||
if (!config) throw new Error('Remote configuration prevents imink API use');
|
||||
|
|
@ -172,6 +150,7 @@ export async function iminkf(
|
|||
token,
|
||||
timestamp: typeof timestamp === 'number' ? '' + timestamp : undefined,
|
||||
request_id,
|
||||
...user,
|
||||
};
|
||||
|
||||
const [signal, cancel] = timeoutSignal();
|
||||
|
|
@ -186,13 +165,13 @@ export async function iminkf(
|
|||
}).finally(cancel);
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw new ErrorResponse<IminkFError>('[imink] Non-200 status code', response, await response.text());
|
||||
throw await ErrorResponse.fromResponse(response, '[imink] Non-200 status code');
|
||||
}
|
||||
|
||||
const data = await response.json() as IminkFResponse | IminkFError;
|
||||
|
||||
if ('error' in data) {
|
||||
throw new ErrorResponse<IminkFError>('[imink] ' + data.reason, response, data);
|
||||
throw new ErrorResponse('[imink] ' + data.reason, response, data);
|
||||
}
|
||||
|
||||
debugImink('Got f parameter "%s"', data.f);
|
||||
|
|
@ -217,16 +196,17 @@ export interface IminkFError {
|
|||
}
|
||||
|
||||
export class ZncaApiImink extends ZncaApi {
|
||||
async genf(token: string, hash_method: HashMethod) {
|
||||
const request_id = uuidgen();
|
||||
async genf(token: string, hash_method: HashMethod, user?: {na_id: string; coral_user_id?: string;}) {
|
||||
const request_id = randomUUID();
|
||||
|
||||
const result = await iminkf(hash_method, token, undefined, request_id, this.useragent);
|
||||
const result = await iminkf(hash_method, token, undefined, request_id, user, this.useragent);
|
||||
|
||||
return {
|
||||
provider: 'imink' as const,
|
||||
hash_method, token, request_id,
|
||||
timestamp: result.timestamp,
|
||||
f: result.f,
|
||||
user,
|
||||
result,
|
||||
};
|
||||
}
|
||||
|
|
@ -236,92 +216,606 @@ export class ZncaApiImink extends ZncaApi {
|
|||
// nxapi znca API server
|
||||
//
|
||||
|
||||
export async function genf(
|
||||
url: string, hash_method: HashMethod,
|
||||
token: string, timestamp?: number, request_id?: string,
|
||||
useragent?: string
|
||||
) {
|
||||
debugZncaApi('Getting f parameter', {
|
||||
url, hash_method, token, timestamp, request_id,
|
||||
});
|
||||
|
||||
const req: AndroidZncaFRequest = {
|
||||
hash_method: '' + hash_method as `${HashMethod}`,
|
||||
token,
|
||||
timestamp,
|
||||
request_id,
|
||||
};
|
||||
|
||||
const [signal, cancel] = timeoutSignal();
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'User-Agent': getUserAgent(useragent),
|
||||
},
|
||||
body: JSON.stringify(req),
|
||||
signal,
|
||||
}).finally(cancel);
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw new ErrorResponse<AndroidZncaFError>('[znca-api] Non-200 status code', response, await response.text());
|
||||
}
|
||||
|
||||
const data = await response.json() as AndroidZncaFResponse | AndroidZncaFError;
|
||||
|
||||
if ('error' in data) {
|
||||
debugZncaApi('Error getting f parameter "%s"', data.error);
|
||||
throw new ErrorResponse<AndroidZncaFError>('[znca-api] ' + data.error_message ?? data.error, response, data);
|
||||
}
|
||||
|
||||
debugZncaApi('Got f parameter', data, response.headers);
|
||||
|
||||
return defineResponse(data, response);
|
||||
}
|
||||
|
||||
export interface AndroidZncaFRequest {
|
||||
hash_method: '1' | '2';
|
||||
token: string;
|
||||
timestamp?: string | number;
|
||||
request_id?: string;
|
||||
encrypt_token_request?: EncryptRequestOptions;
|
||||
}
|
||||
export interface AndroidZncaFResponse {
|
||||
f: string;
|
||||
timestamp?: number;
|
||||
request_id?: string;
|
||||
|
||||
encrypted_token_request?: string;
|
||||
|
||||
warnings?: {error: string; error_message: string}[];
|
||||
}
|
||||
|
||||
export interface AndroidZncaEncryptRequestRequest {
|
||||
url: string;
|
||||
token: string | null;
|
||||
data: string;
|
||||
}
|
||||
|
||||
export interface AndroidZncaDecryptResponseRequest {
|
||||
data: string;
|
||||
request_nsa_assertion?: boolean;
|
||||
}
|
||||
export interface AndroidZncaDecryptResponseResponse {
|
||||
data: string;
|
||||
nsa_assertion?: string | null;
|
||||
}
|
||||
|
||||
export interface AndroidZncaFError {
|
||||
error: string;
|
||||
error_message?: string;
|
||||
|
||||
errors?: {error: string; error_message: string}[];
|
||||
warnings?: {error: string; error_message: string}[];
|
||||
}
|
||||
|
||||
export class ZncaApiNxapi extends ZncaApi {
|
||||
constructor(readonly url: string, useragent?: string) {
|
||||
export interface TokenResponse {
|
||||
access_token: string;
|
||||
token_type: 'Bearer';
|
||||
expires_in: number;
|
||||
scope?: string;
|
||||
refresh_token?: string;
|
||||
}
|
||||
|
||||
interface ProtectedResourceMetadata {
|
||||
resource: string;
|
||||
authorization_servers?: string[];
|
||||
jwks_uri?: string;
|
||||
scopes_supported?: string[];
|
||||
bearer_methods_supported?: string[];
|
||||
resource_signing_alg_values_supported?: string[];
|
||||
resource_name?: string;
|
||||
resource_documentation?: string;
|
||||
resource_policy_uri?: string;
|
||||
resource_tos_uri?: string;
|
||||
}
|
||||
|
||||
interface AuthorisationServerMetadata {
|
||||
issuer: string;
|
||||
authorization_endpoint?: string;
|
||||
token_endpoint?: string;
|
||||
jwks_uri?: string;
|
||||
registration_endpoint?: string;
|
||||
scopes_supported?: string[];
|
||||
response_types_supported: string[];
|
||||
response_modes_supported?: string[];
|
||||
grant_types_supported?: string[];
|
||||
token_endpoint_auth_methods_supported?: string[];
|
||||
token_endpoint_auth_signing_alg_values_supported?: string[];
|
||||
service_documentation?: string;
|
||||
ui_locales_supported?: string[];
|
||||
op_policy_uri?: string;
|
||||
op_tos_uri?: string;
|
||||
revocation_endpoint?: string;
|
||||
revocation_endpoint_auth_methods_supported?: string[];
|
||||
revocation_endpoint_auth_signing_alg_values_supported?: string[];
|
||||
introspection_endpoint?: string;
|
||||
introspection_endpoint_auth_methods_supported?: string[];
|
||||
introspection_endpoint_auth_signing_alg_values_supported?: string[];
|
||||
code_challenge_methods_supported?: string[];
|
||||
}
|
||||
|
||||
export interface TokenData {
|
||||
token: string;
|
||||
expires_at: number;
|
||||
refresh_token: string | null;
|
||||
result: TokenResponse;
|
||||
}
|
||||
export interface ResourceData {
|
||||
token_endpoint: string;
|
||||
client_assertion_aud: string;
|
||||
|
||||
resource_metadata: ProtectedResourceMetadata;
|
||||
authorisation_server_metadata: AuthorisationServerMetadata;
|
||||
}
|
||||
|
||||
export const NsaAssertionSymbol = Symbol('NsaAssertion');
|
||||
|
||||
export class ZncaApiNxapi extends ZncaApi implements RequestEncryptionProvider {
|
||||
readonly url: URL;
|
||||
readonly auth: NxapiZncaAuth | null;
|
||||
|
||||
last_nsa_assertion: string | null = null
|
||||
onReceiveNsaAssertion: ((nsa_assertion: string) => void) | null = null;
|
||||
|
||||
headers = new Headers();
|
||||
|
||||
constructor(
|
||||
url: URL | string,
|
||||
auth: NxapiZncaAuth | null,
|
||||
readonly app?: {platform?: string; version?: string;},
|
||||
useragent?: string,
|
||||
) {
|
||||
super(useragent);
|
||||
|
||||
if (typeof url === 'string') {
|
||||
url = new URL(url);
|
||||
|
||||
if (!url.pathname.endsWith('/')) url.pathname += '/';
|
||||
}
|
||||
|
||||
this.url = url;
|
||||
this.auth = auth;
|
||||
|
||||
this.headers.set('User-Agent', getUserAgent(useragent));
|
||||
this.headers.append('X-znca-Client-Version', ZNCA_API_COMPATIBILITY_VERSION);
|
||||
}
|
||||
|
||||
async genf(token: string, hash_method: HashMethod) {
|
||||
const request_id = uuidgen();
|
||||
static create(
|
||||
url: string,
|
||||
app?: {platform?: string; version?: string;},
|
||||
useragent?: string,
|
||||
) {
|
||||
const auth = NxapiZncaAuth.create(url, useragent);
|
||||
|
||||
const result = await genf(this.url + '/f', hash_method, token, undefined, request_id, this.useragent);
|
||||
return new ZncaApiNxapi(url, auth, app, useragent);
|
||||
}
|
||||
|
||||
async genf(
|
||||
token: string, hash_method: HashMethod, user?: {na_id: string; coral_user_id?: string},
|
||||
encrypt_token_request?: EncryptRequestOptions,
|
||||
/** @internal */ _attempt = 0,
|
||||
): Promise<FResult> {
|
||||
if (this.auth && !this.auth.has_valid_token) await this.auth.authenticate();
|
||||
|
||||
const url = new URL('f', this.url);
|
||||
|
||||
debugZncaApi('Getting f parameter', {
|
||||
url: url.href, hash_method, token, timestamp: undefined, request_id: undefined, user,
|
||||
znca_platform: this.app?.platform, znca_version: this.app?.version,
|
||||
encrypt_token_request,
|
||||
});
|
||||
|
||||
const req: AndroidZncaFRequest = {
|
||||
hash_method: '' + hash_method as `${HashMethod}`,
|
||||
token,
|
||||
...user,
|
||||
encrypt_token_request,
|
||||
};
|
||||
|
||||
const headers = new Headers(this.headers);
|
||||
headers.set('Content-Type', 'application/json');
|
||||
headers.set('Accept', 'application/json');
|
||||
if (this.app?.platform) headers.append('X-znca-Platform', this.app.platform);
|
||||
if (this.app?.version) headers.append('X-znca-Version', this.app.version);
|
||||
if (this.auth?.token) headers.append('Authorization', 'Bearer ' + this.auth.token.token);
|
||||
|
||||
const [signal, cancel] = timeoutSignal();
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(req),
|
||||
signal,
|
||||
}).finally(cancel);
|
||||
|
||||
if (response.status !== 200) {
|
||||
const err = await ErrorResponse.fromResponse<AndroidZncaFError>(response, '[znca-api] Non-200 status code');
|
||||
|
||||
if (this.auth && err.data?.error === 'invalid_token' && !_attempt) {
|
||||
this.auth.token = null;
|
||||
|
||||
return this.genf(token, hash_method, user, encrypt_token_request, _attempt + 1);
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
|
||||
const data = await response.json() as AndroidZncaFResponse | AndroidZncaFError;
|
||||
|
||||
if ('error' in data) {
|
||||
debugZncaApi('Error getting f parameter "%s"', data.error);
|
||||
throw new ErrorResponse<AndroidZncaFError>('[znca-api] ' + (data.error_message ?? data.error), response, data);
|
||||
}
|
||||
|
||||
debugZncaApi('Got f parameter', data, response.headers);
|
||||
|
||||
const result = defineResponse(data, response);
|
||||
|
||||
return {
|
||||
provider: 'nxapi' as const,
|
||||
url: this.url + '/f',
|
||||
hash_method, token, request_id,
|
||||
url: url.href,
|
||||
hash_method, token,
|
||||
timestamp: result.timestamp!, // will be included as not sent in request
|
||||
request_id: result.request_id!,
|
||||
f: result.f,
|
||||
user,
|
||||
result,
|
||||
encrypt_request_result: result.encrypted_token_request ? Buffer.from(result.encrypted_token_request, 'base64') : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
async encryptRequest(
|
||||
url: string, token: string | null, data: string,
|
||||
/** @internal */ _attempt = 0,
|
||||
): Promise<EncryptRequestResult> {
|
||||
if (this.auth && !this.auth.has_valid_token) await this.auth.authenticate();
|
||||
|
||||
debugZncaApi('encrypting request', { url, data });
|
||||
|
||||
const req: AndroidZncaEncryptRequestRequest = {
|
||||
url,
|
||||
token,
|
||||
data,
|
||||
};
|
||||
|
||||
const headers = new Headers(this.headers);
|
||||
headers.set('Content-Type', 'application/json');
|
||||
headers.set('Accept', 'application/octet-stream');
|
||||
if (this.app?.platform) headers.append('X-znca-Platform', this.app.platform);
|
||||
if (this.app?.version) headers.append('X-znca-Version', this.app.version);
|
||||
if (this.auth?.token) headers.append('Authorization', 'Bearer ' + this.auth.token.token);
|
||||
|
||||
const [signal, cancel] = timeoutSignal();
|
||||
const response = await fetch(new URL('encrypt-request', this.url), {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(req),
|
||||
signal,
|
||||
}).finally(cancel);
|
||||
|
||||
if (response.status !== 200) {
|
||||
const err = await ErrorResponse.fromResponse<AndroidZncaFError>(response, '[znca-api] Non-200 status code');
|
||||
|
||||
if (this.auth && err.data?.error === 'invalid_token' && !_attempt) {
|
||||
this.auth.token = null;
|
||||
|
||||
return this.encryptRequest(url, token, data, _attempt + 1);
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
|
||||
const encrypted_data = new Uint8Array(await response.arrayBuffer());
|
||||
|
||||
const result = defineResponse(encrypted_data, response);
|
||||
|
||||
return {
|
||||
data: result,
|
||||
};
|
||||
}
|
||||
|
||||
async decryptResponse(
|
||||
data: Uint8Array,
|
||||
request_nsa_assertion = false,
|
||||
/** @internal */ _attempt = 0,
|
||||
): Promise<DecryptResponseResult> {
|
||||
if (this.auth && !this.auth.has_valid_token) await this.auth.authenticate();
|
||||
|
||||
// debugZncaApi('decrypting response', data);
|
||||
|
||||
const req: AndroidZncaDecryptResponseRequest = {
|
||||
data: Buffer.from(data).toString('base64'),
|
||||
};
|
||||
|
||||
if (request_nsa_assertion) {
|
||||
req.request_nsa_assertion = true;
|
||||
}
|
||||
|
||||
const headers = new Headers(this.headers);
|
||||
headers.set('Content-Type', 'application/json');
|
||||
headers.set('Accept', request_nsa_assertion ? 'application/json' : 'text/plain');
|
||||
if (this.app?.platform) headers.append('X-znca-Platform', this.app.platform);
|
||||
if (this.app?.version) headers.append('X-znca-Version', this.app.version);
|
||||
if (this.auth?.token) headers.append('Authorization', 'Bearer ' + this.auth.token.token);
|
||||
|
||||
const [signal, cancel] = timeoutSignal();
|
||||
const response = await fetch(new URL('decrypt-response', this.url), {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(req),
|
||||
signal,
|
||||
}).finally(cancel);
|
||||
|
||||
if (response.status !== 200) {
|
||||
const err = await ErrorResponse.fromResponse<AndroidZncaFError>(response, '[znca-api] Non-200 status code');
|
||||
|
||||
if (this.auth && err.data?.error === 'invalid_token' && !_attempt) {
|
||||
this.auth.token = null;
|
||||
|
||||
return this.decryptResponse(data, request_nsa_assertion, _attempt + 1);
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
|
||||
const result = request_nsa_assertion ? await response.json() as AndroidZncaDecryptResponseResponse : {
|
||||
data: await response.text(),
|
||||
};
|
||||
|
||||
if (result.nsa_assertion) {
|
||||
this.last_nsa_assertion = result.nsa_assertion;
|
||||
this.onReceiveNsaAssertion?.call(null, result.nsa_assertion);
|
||||
}
|
||||
|
||||
return {
|
||||
data: result.data,
|
||||
|
||||
// @ts-expect-error
|
||||
[NsaAssertionSymbol]: result.nsa_assertion ?? null,
|
||||
|
||||
response,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function f(token: string, hash_method: HashMethod | `${HashMethod}`, useragent?: string): Promise<FResult> {
|
||||
if (typeof hash_method === 'string') hash_method = parseInt(hash_method);
|
||||
export class NxapiZncaAuth {
|
||||
client_assertion_provider: ClientAssertionProviderInterface | null = null;
|
||||
client_credentials:
|
||||
{ assertion: string; assertion_type: string; } |
|
||||
{ id: string; secret: string; } |
|
||||
{ id: string; } |
|
||||
null = null;
|
||||
|
||||
const provider = getPreferredZncaApiFromEnvironment(useragent) ?? await getDefaultZncaApi(useragent);
|
||||
request_scope = 'ca:gf ca:er ca:dr';
|
||||
|
||||
return provider.genf(token, hash_method);
|
||||
token: TokenData | null = null;
|
||||
refresh_token: string | null = null;
|
||||
|
||||
protected_resource: ResourceData | null = null;
|
||||
|
||||
headers = new Headers();
|
||||
|
||||
constructor(
|
||||
readonly resource: string,
|
||||
useragent?: string,
|
||||
) {
|
||||
this.headers.set('User-Agent', getUserAgent(useragent));
|
||||
}
|
||||
|
||||
static create(url: string, useragent?: string) {
|
||||
const resource = new URL(url).origin;
|
||||
|
||||
const auth = new NxapiZncaAuth(resource, useragent);
|
||||
let scope: string | null = null;
|
||||
|
||||
if (process.env.NXAPI_ZNCA_API_CLIENT_ID && process.env.NXAPI_ZNCA_API_CLIENT_SECRET) {
|
||||
auth.client_credentials = {
|
||||
id: process.env.NXAPI_ZNCA_API_CLIENT_ID,
|
||||
secret: process.env.NXAPI_ZNCA_API_CLIENT_SECRET,
|
||||
};
|
||||
} else if (process.env.NXAPI_ZNCA_API_CLIENT_ASSERTION) {
|
||||
auth.client_credentials = {
|
||||
assertion: process.env.NXAPI_ZNCA_API_CLIENT_ASSERTION,
|
||||
assertion_type: process.env.NXAPI_ZNCA_API_CLIENT_ASSERTION_TYPE ??
|
||||
'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
|
||||
};
|
||||
} else if (process.env.NXAPI_ZNCA_API_CLIENT_ID) {
|
||||
auth.client_credentials = {
|
||||
id: process.env.NXAPI_ZNCA_API_CLIENT_ID,
|
||||
};
|
||||
} else if (client_auth_provider && 'secret' in client_auth_provider) {
|
||||
auth.client_credentials = {
|
||||
id: client_auth_provider.id,
|
||||
secret: client_auth_provider.secret,
|
||||
};
|
||||
scope = client_auth_provider.scope;
|
||||
} else if (client_auth_provider && 'id' in client_auth_provider) {
|
||||
auth.client_credentials = {
|
||||
id: client_auth_provider.id,
|
||||
};
|
||||
scope = client_auth_provider.scope;
|
||||
} else if (client_auth_provider && 'create' in client_auth_provider) {
|
||||
auth.client_assertion_provider = client_auth_provider;
|
||||
} else if (client_assertion_provider) {
|
||||
auth.client_assertion_provider = client_assertion_provider;
|
||||
} else {
|
||||
debugZncaAuth('client authentication not configured');
|
||||
}
|
||||
|
||||
if (scope) {
|
||||
auth.request_scope = scope;
|
||||
} else if (process.env.NXAPI_ZNCA_API_AUTH_SCOPE) {
|
||||
auth.request_scope = process.env.NXAPI_ZNCA_API_AUTH_SCOPE;
|
||||
}
|
||||
|
||||
return auth;
|
||||
}
|
||||
|
||||
private _authenticate: Promise<void> | null = null;
|
||||
|
||||
authenticate() {
|
||||
return this._authenticate ?? (this._authenticate = this.getAccessToken()
|
||||
.then(result => {
|
||||
this.token = {
|
||||
token: result.access_token,
|
||||
expires_at: Date.now() + (result.expires_in * 1000),
|
||||
refresh_token: result.refresh_token ?? this.refresh_token ?? null,
|
||||
result,
|
||||
};
|
||||
if (result.refresh_token) {
|
||||
this.refresh_token = result.refresh_token;
|
||||
}
|
||||
})
|
||||
.finally(() => this._authenticate = null));
|
||||
}
|
||||
|
||||
get has_valid_token() {
|
||||
return !!this.token && this.token.expires_at > Date.now();
|
||||
}
|
||||
|
||||
get has_nsa_assertion_scope() {
|
||||
return this.token?.result.scope ? !!this.token.result.scope.match(/\bca:na\b/) :
|
||||
this.client_assertion_provider && !this.client_credentials ?
|
||||
!!this.client_assertion_provider.scope.match(/\bca:na\b/) :
|
||||
this.client_credentials ? !!this.request_scope.match(/\bca:na\b/) : false;
|
||||
}
|
||||
|
||||
async getAccessToken(): Promise<TokenResponse> {
|
||||
const resource = this.protected_resource ?? (this.protected_resource = await this.getProtectedResource());
|
||||
const refresh_token = this.refresh_token;
|
||||
|
||||
debugZncaAuth('fetching nxapi-znca-api token');
|
||||
|
||||
const headers = new Headers(this.headers);
|
||||
headers.set('Accept', 'application/json');
|
||||
|
||||
const body = new URLSearchParams();
|
||||
|
||||
if (refresh_token) {
|
||||
body.append('grant_type', 'refresh_token');
|
||||
body.append('refresh_token', refresh_token);
|
||||
} else {
|
||||
body.append('grant_type', 'client_credentials');
|
||||
body.append('scope', this.request_scope);
|
||||
}
|
||||
|
||||
if (this.client_credentials && 'secret' in this.client_credentials) {
|
||||
body.append('client_id', this.client_credentials.id);
|
||||
body.append('client_secret', this.client_credentials.secret);
|
||||
} else if (this.client_credentials && 'assertion' in this.client_credentials) {
|
||||
body.append('client_assertion_type', this.client_credentials.assertion_type);
|
||||
body.append('client_assertion', this.client_credentials.assertion);
|
||||
} else if (this.client_credentials && 'id' in this.client_credentials) {
|
||||
body.append('client_id', this.client_credentials.id);
|
||||
} else if (this.client_assertion_provider) {
|
||||
const { assertion, type } = await this.client_assertion_provider.create(resource.client_assertion_aud);
|
||||
|
||||
body.append('client_assertion_type', type);
|
||||
body.append('client_assertion', assertion);
|
||||
body.set('scope', this.client_assertion_provider.scope);
|
||||
} else {
|
||||
if (resource.resource_metadata.resource_documentation) {
|
||||
throw new TypeError('Client authentication not configured\n\n' +
|
||||
'See resource documentation at ' + resource.resource_metadata.resource_documentation);
|
||||
}
|
||||
|
||||
throw new TypeError('Client authentication not configured');
|
||||
}
|
||||
|
||||
const [signal, cancel] = timeoutSignal();
|
||||
const response = await fetch(resource.token_endpoint, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body,
|
||||
signal,
|
||||
}).finally(cancel);
|
||||
|
||||
if (response.status !== 200) {
|
||||
const err = await ErrorResponse.fromResponse<AndroidZncaFError>(response, '[znca-api] Non-200 status code');
|
||||
|
||||
if (refresh_token && err.data?.error === 'invalid_grant') {
|
||||
this.refresh_token = null;
|
||||
|
||||
return this.getAccessToken();
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
|
||||
const data = await response.json() as TokenResponse;
|
||||
|
||||
const result = defineResponse(data, response);
|
||||
|
||||
debugZncaAuth('token', result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async getProtectedResource() {
|
||||
const resource_metadata = await this.getProtectedResourceMetadata(this.resource);
|
||||
|
||||
if (!resource_metadata.authorization_servers?.length) {
|
||||
throw new TypeError('Unable to find authorisation server');
|
||||
}
|
||||
if (resource_metadata.authorization_servers.length > 1) {
|
||||
debugZncaAuth('multiple authorisation servers returned for %s, using first', this.resource);
|
||||
}
|
||||
|
||||
const authorisation_server = resource_metadata.authorization_servers[0];
|
||||
|
||||
const authorisation_server_metadata = await this.getAuthorisationServerMetadata(authorisation_server);
|
||||
|
||||
if (!authorisation_server_metadata.token_endpoint) {
|
||||
throw new TypeError('Unable to find authorisation server token endpoint');
|
||||
}
|
||||
|
||||
return {
|
||||
token_endpoint: authorisation_server_metadata.token_endpoint,
|
||||
client_assertion_aud: authorisation_server_metadata.issuer,
|
||||
|
||||
resource_metadata,
|
||||
authorisation_server_metadata,
|
||||
};
|
||||
}
|
||||
|
||||
async getProtectedResourceMetadata(resource: URL | string) {
|
||||
if (typeof resource === 'string') resource = new URL(resource);
|
||||
|
||||
if (resource.search) debugZncaAuth('resource identifier contains search parameters');
|
||||
if (resource.hash) throw new TypeError('Resource identifier contains fragment');
|
||||
|
||||
debugZncaAuth('fetching protected resource metadata for %s', this.getIssuerFromUrl(resource));
|
||||
|
||||
const metadata_url = new URL(resource);
|
||||
|
||||
metadata_url.pathname = '/.well-known/oauth-protected-resource' +
|
||||
(metadata_url.pathname === '/' ? '' : metadata_url.pathname);
|
||||
|
||||
const headers = new Headers(this.headers);
|
||||
headers.set('Accept', 'application/json');
|
||||
|
||||
const [signal, cancel] = timeoutSignal();
|
||||
const response = await fetch(metadata_url, {
|
||||
headers,
|
||||
signal,
|
||||
}).finally(cancel);
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw await ErrorResponse.fromResponse<AndroidZncaFError>(response, '[znca-api] Non-200 status code');
|
||||
}
|
||||
|
||||
const data = await response.json() as ProtectedResourceMetadata;
|
||||
|
||||
const result = defineResponse(data, response);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async getAuthorisationServerMetadata(issuer: URL | string) {
|
||||
if (typeof issuer === 'string') issuer = new URL(issuer);
|
||||
|
||||
if (issuer.search) debugZncaAuth('issuer identifier contains search parameters');
|
||||
if (issuer.hash) throw new TypeError('Issuer identifier contains fragment');
|
||||
|
||||
debugZncaAuth('fetching authorisation server metadata for %s', this.getIssuerFromUrl(issuer));
|
||||
|
||||
const metadata_url = new URL(issuer);
|
||||
|
||||
metadata_url.pathname = '/.well-known/oauth-authorization-server' +
|
||||
(metadata_url.pathname === '/' ? '' : metadata_url.pathname);
|
||||
|
||||
const headers = new Headers(this.headers);
|
||||
headers.set('Accept', 'application/json');
|
||||
|
||||
const [signal, cancel] = timeoutSignal();
|
||||
const response = await fetch(metadata_url, {
|
||||
headers,
|
||||
signal,
|
||||
}).finally(cancel);
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw await ErrorResponse.fromResponse<AndroidZncaFError>(response, '[znca-api] Non-200 status code');
|
||||
}
|
||||
|
||||
const data = await response.json() as AuthorisationServerMetadata;
|
||||
|
||||
const result = defineResponse(data, response);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
getIssuerFromUrl(issuer: URL) {
|
||||
if (issuer.search || issuer.hash) return issuer.href;
|
||||
if (issuer.pathname !== '/') return issuer.href;
|
||||
return issuer.origin;
|
||||
}
|
||||
}
|
||||
|
||||
export type FResult = {
|
||||
|
|
@ -331,7 +825,9 @@ export type FResult = {
|
|||
timestamp: number;
|
||||
request_id: string;
|
||||
f: string;
|
||||
user?: {na_id: string; coral_user_id?: string;};
|
||||
result: unknown;
|
||||
encrypt_request_result?: Uint8Array;
|
||||
} & ({
|
||||
provider: 'flapg';
|
||||
result: FlapgApiResponse;
|
||||
|
|
@ -344,37 +840,61 @@ export type FResult = {
|
|||
result: AndroidZncaFResponse;
|
||||
});
|
||||
|
||||
export function getPreferredZncaApiFromEnvironment(useragent?: string): ZncaApi | null {
|
||||
interface ZncaApiOptions {
|
||||
useragent?: string;
|
||||
platform?: string;
|
||||
version?: string;
|
||||
user?: {na_id: string; coral_user_id?: string;};
|
||||
encrypt_request?: EncryptRequestOptions;
|
||||
}
|
||||
interface EncryptRequestOptions {
|
||||
url: string;
|
||||
parameter: AccountLoginParameter | AccountTokenParameter | WebServiceTokenParameter;
|
||||
}
|
||||
|
||||
export async function createZncaApi(options?: ZncaApiOptions) {
|
||||
return getPreferredZncaApiFromEnvironment(options) ?? await getDefaultZncaApi(options);
|
||||
}
|
||||
|
||||
export function getPreferredZncaApiFromEnvironment(options?: ZncaApiOptions): ZncaApi | null;
|
||||
export function getPreferredZncaApiFromEnvironment(useragent?: string): ZncaApi | null;
|
||||
export function getPreferredZncaApiFromEnvironment(options?: ZncaApiOptions | string): ZncaApi | null {
|
||||
if (typeof options === 'string') options = {useragent: options};
|
||||
|
||||
if (process.env.NXAPI_ZNCA_API) {
|
||||
if (process.env.NXAPI_ZNCA_API === 'flapg') {
|
||||
return new ZncaApiFlapg(useragent);
|
||||
return new ZncaApiFlapg(options?.useragent);
|
||||
}
|
||||
if (process.env.NXAPI_ZNCA_API === 'imink') {
|
||||
return new ZncaApiImink(useragent);
|
||||
return new ZncaApiImink(options?.useragent);
|
||||
}
|
||||
|
||||
throw new Error('Unknown znca API provider');
|
||||
}
|
||||
|
||||
if (process.env.ZNCA_API_URL) {
|
||||
return new ZncaApiNxapi(process.env.ZNCA_API_URL, useragent);
|
||||
return ZncaApiNxapi.create(process.env.ZNCA_API_URL, options, options?.useragent);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function getDefaultZncaApi(useragent?: string) {
|
||||
export async function getDefaultZncaApi(options?: ZncaApiOptions): Promise<ZncaApi>;
|
||||
export async function getDefaultZncaApi(useragent?: string): Promise<ZncaApi>;
|
||||
export async function getDefaultZncaApi(options?: ZncaApiOptions | string) {
|
||||
if (typeof options === 'string') options = {useragent: options};
|
||||
|
||||
const { default: { coral_auth: { default: provider } } } = await import('../common/remote-config.js');
|
||||
|
||||
if (provider === 'flapg') {
|
||||
return new ZncaApiFlapg(useragent);
|
||||
return new ZncaApiFlapg(options?.useragent);
|
||||
}
|
||||
if (provider === 'imink') {
|
||||
return new ZncaApiImink(useragent);
|
||||
return new ZncaApiImink(options?.useragent);
|
||||
}
|
||||
|
||||
if (provider[0] === 'nxapi') {
|
||||
return new ZncaApiNxapi(provider[1], useragent);
|
||||
return ZncaApiNxapi.create(provider[1], options, options?.useragent);
|
||||
}
|
||||
|
||||
throw new Error('Invalid znca API provider');
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import fetch, { Response } from 'node-fetch';
|
||||
import createDebug from 'debug';
|
||||
import { getNintendoAccountToken, getNintendoAccountUser, NintendoAccountToken, NintendoAccountUser } from './na.js';
|
||||
import { fetch, Response } from 'undici';
|
||||
import { generateAuthData, getNintendoAccountToken, getNintendoAccountUser, NintendoAccountSessionAuthorisation, NintendoAccountToken, NintendoAccountUser } from './na.js';
|
||||
import { defineResponse, ErrorResponse, HasResponse } from './util.js';
|
||||
import { DailySummaries, Devices, MonthlySummaries, MonthlySummary, MoonError, ParentalControlSettingState, SmartDevices, User } from './moon-types.js';
|
||||
import createDebug from '../util/debug.js';
|
||||
import { timeoutSignal } from '../util/misc.js';
|
||||
|
||||
const debug = createDebug('nxapi:api:moon');
|
||||
|
|
@ -10,15 +10,16 @@ const debug = createDebug('nxapi:api:moon');
|
|||
const MOON_URL = 'https://api-lp1.pctl.srv.nintendo.net/moon';
|
||||
export const ZNMA_CLIENT_ID = '54789befb391a838';
|
||||
|
||||
const ZNMA_VERSION = '1.17.0';
|
||||
export const ZNMA_VERSION = '1.17.0';
|
||||
const ZNMA_BUILD = '261';
|
||||
const ZNMA_USER_AGENT = 'moon_ANDROID/' + ZNMA_VERSION + ' (com.nintendo.znma; build:' + ZNMA_BUILD +
|
||||
'; ANDROID 26)';
|
||||
|
||||
export default class MoonApi {
|
||||
onTokenExpired: ((data: MoonError, res: Response) => Promise<MoonAuthData | PartialMoonAuthData | void>) | null = null;
|
||||
onTokenExpired: ((data?: MoonError, res?: Response) => Promise<MoonAuthData | PartialMoonAuthData | void>) | null = null;
|
||||
/** @internal */
|
||||
_renewToken: Promise<void> | null = null;
|
||||
protected _token_expired = false;
|
||||
|
||||
protected constructor(
|
||||
public token: string,
|
||||
|
|
@ -31,8 +32,18 @@ export default class MoonApi {
|
|||
async fetch<T extends object>(
|
||||
url: string, method = 'GET', body?: string, headers?: object,
|
||||
/** @internal */ _autoRenewToken = true,
|
||||
/** @internal */ _attempt = 0
|
||||
/** @internal */ _attempt = 0,
|
||||
): Promise<HasResponse<T, Response>> {
|
||||
if (this._token_expired && _autoRenewToken && !this._renewToken) {
|
||||
if (!this.onTokenExpired || _attempt) throw new Error('Token expired');
|
||||
|
||||
this._renewToken = this.onTokenExpired.call(null).then(data => {
|
||||
if (data) this.setTokenWithSavedToken(data);
|
||||
}).finally(() => {
|
||||
this._renewToken = null;
|
||||
});
|
||||
}
|
||||
|
||||
if (this._renewToken && _autoRenewToken) {
|
||||
await this._renewToken;
|
||||
}
|
||||
|
|
@ -62,6 +73,7 @@ export default class MoonApi {
|
|||
debug('fetch %s %s, response %s', method, url, response.status);
|
||||
|
||||
if (response.status === 401 && _autoRenewToken && !_attempt && this.onTokenExpired) {
|
||||
this._token_expired = true;
|
||||
const data = await response.json() as MoonError;
|
||||
|
||||
// _renewToken will be awaited when calling fetch
|
||||
|
|
@ -74,13 +86,13 @@ export default class MoonApi {
|
|||
}
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw new ErrorResponse('[moon] Non-200 status code', response, await response.text());
|
||||
throw await MoonErrorResponse.fromResponse(response, '[moon] Non-200 status code');
|
||||
}
|
||||
|
||||
const data = await response.json() as T | MoonError;
|
||||
|
||||
if ('errorCode' in data) {
|
||||
throw new ErrorResponse('[moon] ' + data.title, response, data);
|
||||
throw new MoonErrorResponse('[moon] ' + data.title, response, data);
|
||||
}
|
||||
|
||||
return defineResponse(data, response);
|
||||
|
|
@ -123,6 +135,7 @@ export default class MoonApi {
|
|||
private setTokenWithSavedToken(data: MoonAuthData | PartialMoonAuthData) {
|
||||
this.token = data.nintendoAccountToken.access_token!;
|
||||
if ('user' in data) this.naId = data.user.id;
|
||||
this._token_expired = false;
|
||||
}
|
||||
|
||||
static async createWithSessionToken(token: string) {
|
||||
|
|
@ -152,7 +165,7 @@ export default class MoonApi {
|
|||
const nintendoAccountToken = await getNintendoAccountToken(token, ZNMA_CLIENT_ID);
|
||||
|
||||
// Nintendo Account user data
|
||||
const user = await getNintendoAccountUser(nintendoAccountToken);
|
||||
const user = await getNintendoAccountUser<never>(nintendoAccountToken);
|
||||
|
||||
return {
|
||||
nintendoAccountToken,
|
||||
|
|
@ -164,9 +177,52 @@ export default class MoonApi {
|
|||
}
|
||||
}
|
||||
|
||||
export class MoonErrorResponse extends ErrorResponse<MoonError> {}
|
||||
|
||||
const na_client_settings = {
|
||||
client_id: ZNMA_CLIENT_ID,
|
||||
scope: [
|
||||
'openid',
|
||||
'user',
|
||||
'user.mii',
|
||||
'moonUser:administration',
|
||||
'moonDevice:create',
|
||||
'moonOwnedDevice:administration',
|
||||
'moonParentalControlSetting',
|
||||
'moonParentalControlSetting:update',
|
||||
'moonParentalControlSettingState',
|
||||
'moonPairingState',
|
||||
'moonSmartDevice:administration',
|
||||
'moonDailySummary',
|
||||
'moonMonthlySummary',
|
||||
].join(' '),
|
||||
};
|
||||
|
||||
export type NintendoAccountUserMoon = NintendoAccountUser;
|
||||
|
||||
export class NintendoAccountSessionAuthorisationMoon extends NintendoAccountSessionAuthorisation {
|
||||
protected constructor(
|
||||
authorise_url: string,
|
||||
state: string,
|
||||
verifier: string,
|
||||
redirect_uri?: string,
|
||||
) {
|
||||
const { client_id, scope } = na_client_settings;
|
||||
|
||||
super(client_id, scope, authorise_url, state, verifier, redirect_uri);
|
||||
}
|
||||
|
||||
static create(/** @internal */ redirect_uri?: string) {
|
||||
const { client_id, scope } = na_client_settings;
|
||||
const auth_data = generateAuthData(client_id, scope, redirect_uri);
|
||||
|
||||
return new this(auth_data.url, auth_data.state, auth_data.verifier, redirect_uri);
|
||||
}
|
||||
}
|
||||
|
||||
export interface MoonAuthData {
|
||||
nintendoAccountToken: NintendoAccountToken;
|
||||
user: NintendoAccountUser;
|
||||
user: NintendoAccountUserMoon;
|
||||
znma_version: string;
|
||||
znma_build: string;
|
||||
znma_useragent: string;
|
||||
|
|
|
|||
331
src/api/na.ts
331
src/api/na.ts
|
|
@ -1,11 +1,131 @@
|
|||
import fetch from 'node-fetch';
|
||||
import createDebug from 'debug';
|
||||
import { defineResponse, ErrorResponse } from './util.js';
|
||||
import * as crypto from 'node:crypto';
|
||||
import { fetch, Response } from 'undici';
|
||||
import { defineResponse, ErrorResponse, HasResponse } from './util.js';
|
||||
import createDebug from '../util/debug.js';
|
||||
import { JwtPayload } from '../util/jwt.js';
|
||||
import { timeoutSignal } from '../util/misc.js';
|
||||
import { ErrorDescription, ErrorDescriptionSymbol, HasErrorDescription } from '../util/errors.js';
|
||||
|
||||
const debug = createDebug('nxapi:api:na');
|
||||
|
||||
export class NintendoAccountSessionAuthorisation {
|
||||
readonly scope: string;
|
||||
|
||||
result: NintendoAccountSessionAuthorisationResult | null = null;
|
||||
|
||||
protected constructor(
|
||||
readonly client_id: string,
|
||||
scope: string | string[],
|
||||
readonly authorise_url: string,
|
||||
readonly state: string,
|
||||
readonly verifier: string,
|
||||
readonly redirect_uri = 'npf' + client_id + '://auth',
|
||||
) {
|
||||
this.scope = typeof scope === 'string' ? scope : scope.join(' ');
|
||||
|
||||
Object.defineProperty(this, 'result', {enumerable: false});
|
||||
}
|
||||
|
||||
async getSessionToken(code: string, state?: string): Promise<HasResponse<NintendoAccountSessionToken, Response>>
|
||||
async getSessionToken(params: URLSearchParams): Promise<HasResponse<NintendoAccountSessionToken, Response>>
|
||||
async getSessionToken(code: string | URLSearchParams | null, state?: string | null) {
|
||||
if (this.result) {
|
||||
throw new Error('NintendoAccountSessionAuthorisation already completed');
|
||||
}
|
||||
|
||||
let result_state = state;
|
||||
|
||||
if (code instanceof URLSearchParams) {
|
||||
const result_state = code.get('state');
|
||||
|
||||
if (result_state !== this.state) {
|
||||
throw new TypeError('Invalid state');
|
||||
}
|
||||
|
||||
if (code.has('error')) {
|
||||
throw NintendoAccountSessionAuthorisationError.fromSearchParams(code);
|
||||
}
|
||||
|
||||
code = code.get('session_token_code');
|
||||
state = undefined;
|
||||
}
|
||||
|
||||
if (typeof state !== 'undefined' && state !== this.state) {
|
||||
throw new TypeError('Invalid state');
|
||||
}
|
||||
|
||||
if (typeof code !== 'string' || !code) {
|
||||
throw new TypeError('Invalid code');
|
||||
}
|
||||
|
||||
Object.defineProperty(this, 'result', {value: {state: result_state, code}, writable: false});
|
||||
|
||||
return getNintendoAccountSessionToken(code, this.verifier, this.client_id);
|
||||
}
|
||||
|
||||
static create(
|
||||
client_id: string,
|
||||
scope: string | string[],
|
||||
/** @internal */ redirect_uri = 'npf' + client_id + '://auth',
|
||||
) {
|
||||
if (typeof scope !== 'string') scope = scope.join(' ');
|
||||
|
||||
const auth_data = generateAuthData(client_id, scope, redirect_uri);
|
||||
|
||||
return new NintendoAccountSessionAuthorisation(client_id, scope,
|
||||
auth_data.url, auth_data.state, auth_data.verifier, redirect_uri);
|
||||
}
|
||||
}
|
||||
|
||||
interface NintendoAccountSessionAuthorisationResult {
|
||||
state: string | null | undefined;
|
||||
code: string;
|
||||
}
|
||||
|
||||
export class NintendoAccountSessionAuthorisationError extends Error {
|
||||
constructor(readonly code: string, message?: string) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
static fromSearchParams(qs: URLSearchParams) {
|
||||
const code = qs.get('error') ?? 'unknown_error';
|
||||
const message = qs.get('error_description') ?? code;
|
||||
|
||||
return new NintendoAccountSessionAuthorisationError(code, message);
|
||||
}
|
||||
}
|
||||
|
||||
export function generateAuthData(
|
||||
client_id: string,
|
||||
scope: string | string[],
|
||||
redirect_uri = 'npf' + client_id + '://auth',
|
||||
) {
|
||||
const state = crypto.randomBytes(36).toString('base64url');
|
||||
const verifier = crypto.randomBytes(32).toString('base64url');
|
||||
const challenge = crypto.createHash('sha256').update(verifier).digest().toString('base64url');
|
||||
|
||||
const params = {
|
||||
state,
|
||||
redirect_uri,
|
||||
client_id,
|
||||
scope: typeof scope === 'string' ? scope : scope.join(' '),
|
||||
response_type: 'session_token_code',
|
||||
session_token_code_challenge: challenge,
|
||||
session_token_code_challenge_method: 'S256',
|
||||
theme: 'login_form',
|
||||
};
|
||||
|
||||
const url = 'https://accounts.nintendo.com/connect/1.0.0/authorize?' +
|
||||
new URLSearchParams(params).toString();
|
||||
|
||||
return {
|
||||
url,
|
||||
state,
|
||||
verifier,
|
||||
challenge,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getNintendoAccountSessionToken(code: string, verifier: string, client_id: string) {
|
||||
debug('Getting Nintendo Account session token');
|
||||
|
||||
|
|
@ -14,8 +134,7 @@ export async function getNintendoAccountSessionToken(code: string, verifier: str
|
|||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'X-Platform': 'Android',
|
||||
'X-ProductVersion': '2.0.0',
|
||||
'Accept': 'application/json',
|
||||
'User-Agent': 'NASDKAPI; Android',
|
||||
},
|
||||
body: new URLSearchParams({
|
||||
|
|
@ -27,16 +146,16 @@ export async function getNintendoAccountSessionToken(code: string, verifier: str
|
|||
}).finally(cancel);
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw new ErrorResponse('[na] Non-200 status code', response, await response.text());
|
||||
throw await NintendoAccountAuthErrorResponse.fromResponse(response, '[na] Non-200 status code');
|
||||
}
|
||||
|
||||
const token = await response.json() as NintendoAccountSessionToken | NintendoAccountAuthError | NintendoAccountError;
|
||||
|
||||
if ('errorCode' in token) {
|
||||
throw new ErrorResponse<NintendoAccountError>('[na] ' + token.detail, response, token);
|
||||
}
|
||||
if ('error' in token) {
|
||||
throw new ErrorResponse<NintendoAccountAuthError>('[na] ' + token.error_description ?? token.error, response, token);
|
||||
throw new NintendoAccountAuthErrorResponse('[na] ' + (token.error_description ?? token.error), response, token);
|
||||
}
|
||||
if ('errorCode' in token) {
|
||||
throw new NintendoAccountErrorResponse('[na] ' + token.detail, response, token);
|
||||
}
|
||||
|
||||
debug('Got Nintendo Account session token', token);
|
||||
|
|
@ -64,16 +183,17 @@ export async function getNintendoAccountToken(token: string, client_id: string)
|
|||
}).finally(cancel);
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw new ErrorResponse('[na] Non-200 status code', response, await response.text());
|
||||
throw await NintendoAccountAuthErrorResponse.fromResponse(response, '[na] Non-200 status code');
|
||||
}
|
||||
|
||||
const nintendoAccountToken = await response.json() as NintendoAccountToken | NintendoAccountAuthError | NintendoAccountError;
|
||||
|
||||
if ('errorCode' in nintendoAccountToken) {
|
||||
throw new ErrorResponse<NintendoAccountError>('[na] ' + nintendoAccountToken.detail, response, nintendoAccountToken);
|
||||
}
|
||||
if ('error' in nintendoAccountToken) {
|
||||
throw new ErrorResponse<NintendoAccountAuthError>('[na] ' + nintendoAccountToken.error_description ?? nintendoAccountToken.error, response, nintendoAccountToken);
|
||||
throw new NintendoAccountAuthErrorResponse('[na] ' + (nintendoAccountToken.error_description ??
|
||||
nintendoAccountToken.error), response, nintendoAccountToken);
|
||||
}
|
||||
if ('errorCode' in nintendoAccountToken) {
|
||||
throw new NintendoAccountErrorResponse('[na] ' + nintendoAccountToken.detail, response, nintendoAccountToken);
|
||||
}
|
||||
|
||||
debug('Got Nintendo Account token', nintendoAccountToken);
|
||||
|
|
@ -81,7 +201,7 @@ export async function getNintendoAccountToken(token: string, client_id: string)
|
|||
return defineResponse(nintendoAccountToken, response);
|
||||
}
|
||||
|
||||
export async function getNintendoAccountUser(token: NintendoAccountToken) {
|
||||
export async function getNintendoAccountUser<S extends NintendoAccountScope>(token: NintendoAccountToken) {
|
||||
debug('Getting Nintendo Account user info');
|
||||
|
||||
const [signal, cancel] = timeoutSignal();
|
||||
|
|
@ -97,13 +217,13 @@ export async function getNintendoAccountUser(token: NintendoAccountToken) {
|
|||
}).finally(cancel);
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw new ErrorResponse('[na] Non-200 status code', response, await response.text());
|
||||
throw await NintendoAccountErrorResponse.fromResponse(response, '[na] Non-200 status code');
|
||||
}
|
||||
|
||||
const user = await response.json() as NintendoAccountUser | NintendoAccountError;
|
||||
const user = await response.json() as NintendoAccountUser<S> | NintendoAccountError;
|
||||
|
||||
if ('errorCode' in user) {
|
||||
throw new ErrorResponse<NintendoAccountError>('[na] ' + user.detail, response, user);
|
||||
throw new NintendoAccountErrorResponse('[na] ' + user.detail, response, user);
|
||||
}
|
||||
|
||||
debug('Got Nintendo Account user info', user);
|
||||
|
|
@ -116,11 +236,11 @@ export interface NintendoAccountSessionToken {
|
|||
code: string;
|
||||
}
|
||||
export interface NintendoAccountSessionTokenJwtPayload extends JwtPayload {
|
||||
jti: string;
|
||||
jti: number;
|
||||
typ: 'session_token';
|
||||
iss: 'https://accounts.nintendo.com';
|
||||
/** Unknown - scopes the token is valid for? */
|
||||
'st:scp': number[];
|
||||
'st:scp': NintendoAccountJwtScope[];
|
||||
/** Subject (Nintendo Account ID) */
|
||||
sub: string;
|
||||
exp: number;
|
||||
|
|
@ -130,7 +250,7 @@ export interface NintendoAccountSessionTokenJwtPayload extends JwtPayload {
|
|||
}
|
||||
|
||||
export interface NintendoAccountToken {
|
||||
scope: string[];
|
||||
scope: NintendoAccountScope[];
|
||||
token_type: 'Bearer';
|
||||
id_token: string;
|
||||
access_token?: string;
|
||||
|
|
@ -145,7 +265,7 @@ export interface NintendoAccountIdTokenJwtPayload extends JwtPayload {
|
|||
aud: string;
|
||||
iss: 'https://accounts.nintendo.com';
|
||||
jti: string;
|
||||
at_hash: string; // ??
|
||||
at_hash: string;
|
||||
typ: 'id_token';
|
||||
country: string;
|
||||
}
|
||||
|
|
@ -157,7 +277,7 @@ export interface NintendoAccountAccessTokenJwtPayload extends JwtPayload {
|
|||
sub: string;
|
||||
iat: number;
|
||||
'ac:grt': number; // ??
|
||||
'ac:scp': number[]; // ??
|
||||
'ac:scp': NintendoAccountJwtScope[];
|
||||
exp: number;
|
||||
/** Audience (client ID) */
|
||||
aud: string;
|
||||
|
|
@ -196,10 +316,12 @@ export enum NintendoAccountScope {
|
|||
}
|
||||
export enum NintendoAccountJwtScope {
|
||||
'openid' = 0,
|
||||
'offline' = 1,
|
||||
'user' = 8,
|
||||
'user.birthday' = 9,
|
||||
'user.mii' = 17,
|
||||
'user.screenName' = 23,
|
||||
'user.links.nintendoNetwork.id' = 31,
|
||||
'moonUser:administration' = 320,
|
||||
'moonDevice:create' = 321,
|
||||
'moonOwnedDevice:administration' = 325,
|
||||
|
|
@ -224,76 +346,123 @@ export enum NintendoAccountJwtScope {
|
|||
// 'pointWallet' = -1,
|
||||
// 'userNotificationMessage:anyClients' = -1,
|
||||
// 'userNotificationMessage:anyClients:write' = -1,
|
||||
|
||||
// 1, 31
|
||||
// 'offline' = -1,
|
||||
// 'user.links.nintendoNetwork.id' = -1,
|
||||
}
|
||||
|
||||
export interface NintendoAccountUser {
|
||||
emailOptedIn: boolean;
|
||||
language: string;
|
||||
country: string;
|
||||
timezone: {
|
||||
name: string;
|
||||
id: string;
|
||||
utcOffsetSeconds: number;
|
||||
utcOffset: string;
|
||||
};
|
||||
region: null;
|
||||
export interface NintendoAccountUser<S extends NintendoAccountScope = never> {
|
||||
id: string;
|
||||
nickname: string;
|
||||
clientFriendsOptedIn: boolean;
|
||||
mii: Mii | null;
|
||||
iconUri: string;
|
||||
/** requires scope user.screenName */
|
||||
screenName: NintendoAccountScope.USER_SCREENNAME extends S ? string : undefined;
|
||||
/** requires scope user.birthday */
|
||||
birthday: NintendoAccountScope.USER_BIRTHDAY extends S ? string : undefined;
|
||||
isChild: boolean;
|
||||
eachEmailOptedIn: {
|
||||
survey: {
|
||||
updatedAt: number;
|
||||
optedIn: boolean;
|
||||
};
|
||||
deals: {
|
||||
updatedAt: number;
|
||||
optedIn: boolean;
|
||||
};
|
||||
};
|
||||
gender: NintendoAccountGender;
|
||||
/** requires scope user.email */
|
||||
email: NintendoAccountScope.USER_EMAIL extends S ? string : undefined;
|
||||
emailVerified: boolean;
|
||||
phoneNumberEnabled: boolean;
|
||||
/** requires scope user.links[].id/user.links.*.id */
|
||||
links:
|
||||
NintendoAccountScope.USER_LINKS extends S ?
|
||||
Partial<Record<NintendoAccountLinkType, NintendoAccountLink | null>> | null :
|
||||
Partial<Record<NintendoAccountLinkTypes<S>, NintendoAccountLink | null>> | null | undefined;
|
||||
country: string;
|
||||
region: null;
|
||||
language: string;
|
||||
timezone: NintendoAccountTimezone;
|
||||
/** requires scope user.mii */
|
||||
mii: NintendoAccountScope.USER_MII extends S ? Mii | null : undefined;
|
||||
/** requires scope user.mii */
|
||||
candidateMiis: NintendoAccountScope.USER_MII extends S ? unknown[] : undefined;
|
||||
emailOptedIn: boolean;
|
||||
emailOptedInUpdatedAt: number;
|
||||
eachEmailOptedIn: Record<NintendoAccountEmailType, NintendoAccountEmailOptedIn>;
|
||||
clientFriendsOptedIn: boolean;
|
||||
clientFriendsOptedInUpdatedAt: number;
|
||||
analyticsOptedIn: boolean;
|
||||
analyticsOptedInUpdatedAt: number;
|
||||
analyticsPermissions: Record<NintendoAccountAnalyticsType, NintendoAccountAnalyticsPermission>;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
candidateMiis: unknown[];
|
||||
}
|
||||
|
||||
enum NintendoAccountGender {
|
||||
UNKNOWN = 'unknown',
|
||||
FEMALE = 'female',
|
||||
MALE = 'male',
|
||||
}
|
||||
|
||||
enum NintendoAccountLinkType {
|
||||
NINTENDO_NETWORK = 'nintendoNetwork',
|
||||
APPLE = 'apple',
|
||||
GOOGLE = 'google',
|
||||
}
|
||||
interface NintendoAccountLink {
|
||||
id: string;
|
||||
createdAt: number;
|
||||
emailVerified: boolean;
|
||||
analyticsPermissions: {
|
||||
internalAnalysis: {
|
||||
updatedAt: number;
|
||||
permitted: boolean;
|
||||
};
|
||||
targetMarketing: {
|
||||
updatedAt: number;
|
||||
permitted: boolean;
|
||||
};
|
||||
};
|
||||
emailOptedInUpdatedAt: number;
|
||||
birthday: string;
|
||||
screenName: string;
|
||||
gender: string;
|
||||
analyticsOptedInUpdatedAt: number;
|
||||
analyticsOptedIn: boolean;
|
||||
clientFriendsOptedInUpdatedAt: number;
|
||||
}
|
||||
|
||||
type NintendoAccountLinkScope = {
|
||||
[NintendoAccountScope.USER_LINKS_NNID]: NintendoAccountLinkType.NINTENDO_NETWORK;
|
||||
};
|
||||
type NintendoAccountLinkTypes<S extends NintendoAccountScope = NintendoAccountScope.USER_LINKS> =
|
||||
S extends keyof NintendoAccountLinkScope ? NintendoAccountLinkScope[S] : never;
|
||||
|
||||
interface NintendoAccountTimezone {
|
||||
id: string;
|
||||
name: string;
|
||||
utcOffset: string;
|
||||
utcOffsetSeconds: number;
|
||||
}
|
||||
|
||||
enum NintendoAccountEmailType {
|
||||
SURVEY = 'survey',
|
||||
DEALS = 'deals',
|
||||
}
|
||||
interface NintendoAccountEmailOptedIn {
|
||||
optedIn: boolean;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
enum NintendoAccountAnalyticsType {
|
||||
INTERNAL_ANALYSIS = 'internalAnalysis',
|
||||
TARGET_MARKETING = 'targetMarketing',
|
||||
}
|
||||
interface NintendoAccountAnalyticsPermission {
|
||||
updatedAt: number;
|
||||
permitted: boolean;
|
||||
}
|
||||
|
||||
export interface Mii {
|
||||
favoriteColor: string;
|
||||
id: string;
|
||||
updatedAt: number;
|
||||
clientId: '1cfe3a55ed8924d9';
|
||||
type: 'profile';
|
||||
favoriteColor: MiiColour;
|
||||
coreData: {
|
||||
'4': string;
|
||||
};
|
||||
clientId: '1cfe3a55ed8924d9';
|
||||
imageUriTemplate: string;
|
||||
storeData: {
|
||||
'3': string;
|
||||
};
|
||||
imageUriTemplate: string;
|
||||
imageOrigin: string;
|
||||
etag: string;
|
||||
type: 'profile';
|
||||
updatedAt: number;
|
||||
}
|
||||
export enum MiiColour {
|
||||
RED = 'red',
|
||||
ORANGE = 'orange',
|
||||
YELLOW = 'yellow',
|
||||
YELLOWGREEN = 'yellowgreen',
|
||||
GREEN = 'green',
|
||||
BLUE = 'blue',
|
||||
SKYBLUE = 'skyblue',
|
||||
PINK = 'pink',
|
||||
PURPLE = 'purple',
|
||||
BROWN = 'brown',
|
||||
WHITE = 'white',
|
||||
BLACK = 'black',
|
||||
}
|
||||
|
||||
export interface NintendoAccountAuthError {
|
||||
|
|
@ -309,3 +478,15 @@ export interface NintendoAccountError {
|
|||
status: number;
|
||||
type: string;
|
||||
}
|
||||
|
||||
export class NintendoAccountAuthErrorResponse extends ErrorResponse<NintendoAccountAuthError> implements HasErrorDescription {
|
||||
get [ErrorDescriptionSymbol]() {
|
||||
if (this.data?.error === 'invalid_grant') {
|
||||
return new ErrorDescription('na.invalid_grant', 'Your Nintendo Account session token has expired or was revoked.\n\nYou need to sign in again.');
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export class NintendoAccountErrorResponse extends ErrorResponse<NintendoAccountError> {}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,9 @@
|
|||
import fetch, { Response } from 'node-fetch';
|
||||
import createDebug from 'debug';
|
||||
import { fetch, FormData, Response } from 'undici';
|
||||
import { WebServiceToken } from './coral-types.js';
|
||||
import { NintendoAccountUser } from './na.js';
|
||||
import { defineResponse, ErrorResponse, HasResponse } from './util.js';
|
||||
import CoralApi from './coral.js';
|
||||
import { CoralApiInterface, NintendoAccountUserCoral } from './coral.js';
|
||||
import { WebServiceError, Users, AuthToken, UserProfile, Newspapers, Newspaper, Emoticons, Reaction, IslandProfile } from './nooklink-types.js';
|
||||
import createDebug from '../util/debug.js';
|
||||
import { timeoutSignal } from '../util/misc.js';
|
||||
|
||||
const debug = createDebug('nxapi:api:nooklink');
|
||||
|
|
@ -17,9 +16,10 @@ const NOOKLINK_URL = NOOKLINK_WEBSERVICE_URL + '/api';
|
|||
const BLANCO_VERSION = '2.1.1';
|
||||
|
||||
export default class NooklinkApi {
|
||||
onTokenExpired: ((data: WebServiceError, res: Response) => Promise<NooklinkAuthData | void>) | null = null;
|
||||
onTokenExpired: ((data?: WebServiceError, res?: Response) => Promise<NooklinkAuthData | void>) | null = null;
|
||||
/** @internal */
|
||||
_renewToken: Promise<void> | null = null;
|
||||
protected _token_expired = false;
|
||||
|
||||
protected constructor(
|
||||
public gtoken: string,
|
||||
|
|
@ -30,8 +30,18 @@ export default class NooklinkApi {
|
|||
async fetch<T extends object>(
|
||||
url: string, method = 'GET', body?: string | FormData, headers?: object,
|
||||
/** @internal */ _autoRenewToken = true,
|
||||
/** @internal */ _attempt = 0
|
||||
/** @internal */ _attempt = 0,
|
||||
): Promise<HasResponse<T, Response>> {
|
||||
if (this._token_expired && _autoRenewToken && !this._renewToken) {
|
||||
if (!this.onTokenExpired || _attempt) throw new Error('Token expired');
|
||||
|
||||
this._renewToken = this.onTokenExpired.call(null).then(data => {
|
||||
if (data) this.setTokenWithSavedToken(data);
|
||||
}).finally(() => {
|
||||
this._renewToken = null;
|
||||
});
|
||||
}
|
||||
|
||||
if (this._renewToken && _autoRenewToken) {
|
||||
await this._renewToken;
|
||||
}
|
||||
|
|
@ -57,6 +67,7 @@ export default class NooklinkApi {
|
|||
debug('fetch %s %s, response %s', method, url, response.status);
|
||||
|
||||
if (response.status === 401 && _autoRenewToken && !_attempt && this.onTokenExpired) {
|
||||
this._token_expired = true;
|
||||
const data = await response.json() as WebServiceError;
|
||||
|
||||
// _renewToken will be awaited when calling fetch
|
||||
|
|
@ -68,14 +79,14 @@ export default class NooklinkApi {
|
|||
return this.fetch(url, method, body, headers, _autoRenewToken, _attempt + 1);
|
||||
}
|
||||
|
||||
if (response.status !== 200 && response.status !== 201) {
|
||||
throw new ErrorResponse('[nooklink] Non-200/201 status code', response, await response.text());
|
||||
if (!response.ok) {
|
||||
throw await NooklinkErrorResponse.fromResponse(response, '[nooklink] Non-2xx status code');
|
||||
}
|
||||
|
||||
const data = await response.json() as T | WebServiceError;
|
||||
|
||||
if ('code' in data) {
|
||||
throw new ErrorResponse<WebServiceError>('[nooklink] Error ' + data.code, response, data);
|
||||
throw new NooklinkErrorResponse('[nooklink] Error ' + data.code, response, data);
|
||||
}
|
||||
|
||||
return defineResponse(data, response);
|
||||
|
|
@ -95,13 +106,13 @@ export default class NooklinkApi {
|
|||
return NooklinkUserApi._createWithNooklinkApi(this, user_id);
|
||||
}
|
||||
|
||||
async renewTokenWithCoral(nso: CoralApi, user: NintendoAccountUser) {
|
||||
const data = await NooklinkApi.loginWithCoral(nso, user);
|
||||
async renewTokenWithCoral(coral: CoralApiInterface, user: NintendoAccountUserCoral) {
|
||||
const data = await NooklinkApi.loginWithCoral(coral, user);
|
||||
this.setTokenWithSavedToken(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
async renewTokenWithWebServiceToken(webserviceToken: WebServiceToken, user: NintendoAccountUser) {
|
||||
async renewTokenWithWebServiceToken(webserviceToken: WebServiceToken, user: NintendoAccountUserCoral) {
|
||||
const data = await NooklinkApi.loginWithWebServiceToken(webserviceToken, user);
|
||||
this.setTokenWithSavedToken(data);
|
||||
return data;
|
||||
|
|
@ -109,10 +120,11 @@ export default class NooklinkApi {
|
|||
|
||||
private setTokenWithSavedToken(data: NooklinkAuthData) {
|
||||
this.gtoken = data.gtoken;
|
||||
this._token_expired = false;
|
||||
}
|
||||
|
||||
static async createWithCoral(nso: CoralApi, user: NintendoAccountUser) {
|
||||
const data = await this.loginWithCoral(nso, user);
|
||||
static async createWithCoral(coral: CoralApiInterface, user: NintendoAccountUserCoral) {
|
||||
const data = await this.loginWithCoral(coral, user);
|
||||
return {nooklink: this.createWithSavedToken(data), data};
|
||||
}
|
||||
|
||||
|
|
@ -120,17 +132,17 @@ export default class NooklinkApi {
|
|||
return new this(data.gtoken, data.useragent);
|
||||
}
|
||||
|
||||
static async loginWithCoral(nso: CoralApi, user: NintendoAccountUser) {
|
||||
static async loginWithCoral(coral: CoralApiInterface, user: NintendoAccountUserCoral) {
|
||||
const { default: { coral_gws_nooklink: config } } = await import('../common/remote-config.js');
|
||||
if (!config) throw new Error('Remote configuration prevents NookLink authentication');
|
||||
|
||||
const webserviceToken = await nso.getWebServiceToken(NOOKLINK_WEBSERVICE_ID);
|
||||
const webserviceToken = await coral.getWebServiceToken(NOOKLINK_WEBSERVICE_ID);
|
||||
|
||||
return this.loginWithWebServiceToken(webserviceToken, user);
|
||||
}
|
||||
|
||||
static async loginWithWebServiceToken(
|
||||
webserviceToken: WebServiceToken, user: NintendoAccountUser
|
||||
webserviceToken: WebServiceToken, user: NintendoAccountUserCoral
|
||||
): Promise<NooklinkAuthData> {
|
||||
const { default: { coral_gws_nooklink: config } } = await import('../common/remote-config.js');
|
||||
if (!config) throw new Error('Remote configuration prevents NookLink authentication');
|
||||
|
|
@ -147,6 +159,7 @@ export default class NooklinkApi {
|
|||
headers: {
|
||||
'Upgrade-Insecure-Requests': '1',
|
||||
'User-Agent': NOOKLINK_WEBSERVICE_USERAGENT,
|
||||
'x-appplatform': 'android',
|
||||
'x-appcolorscheme': 'DARK',
|
||||
'x-gamewebtoken': webserviceToken.accessToken,
|
||||
'dnt': '1',
|
||||
|
|
@ -159,17 +172,17 @@ export default class NooklinkApi {
|
|||
|
||||
debug('fetch %s %s, response %s', 'GET', url, response.status);
|
||||
|
||||
const body = await response.text();
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw new ErrorResponse('[nooklink] Non-200 status code', response, body);
|
||||
throw await NooklinkErrorResponse.fromResponse(response, '[nooklink] Non-200 status code');
|
||||
}
|
||||
|
||||
const body = await response.text();
|
||||
|
||||
const cookies = response.headers.get('Set-Cookie');
|
||||
const match = cookies?.match(/\b_gtoken=([^;]*)(;(\s*((?!expires)[a-z]+=([^;]*));?)*(\s*(expires=([^;]*));?)?|$)/i);
|
||||
|
||||
if (!match) {
|
||||
throw new ErrorResponse('[nooklink] Response didn\'t include _gtoken cookie', response, body);
|
||||
throw new NooklinkErrorResponse('[nooklink] Response didn\'t include _gtoken cookie', response, body);
|
||||
}
|
||||
|
||||
const gtoken = decodeURIComponent(match[1]);
|
||||
|
|
@ -195,9 +208,10 @@ export default class NooklinkApi {
|
|||
}
|
||||
|
||||
export class NooklinkUserApi {
|
||||
onTokenExpired: ((data: WebServiceError, res: Response) => Promise<NooklinkUserAuthData | PartialNooklinkUserAuthData | void>) | null = null;
|
||||
onTokenExpired: ((data?: WebServiceError, res?: Response) => Promise<NooklinkUserAuthData | PartialNooklinkUserAuthData | void>) | null = null;
|
||||
/** @internal */
|
||||
_renewToken: Promise<void> | null = null;
|
||||
protected _token_expired = false;
|
||||
|
||||
protected constructor(
|
||||
public user_id: string,
|
||||
|
|
@ -211,8 +225,18 @@ export class NooklinkUserApi {
|
|||
async fetch<T extends object>(
|
||||
url: string, method = 'GET', body?: string | FormData, headers?: object,
|
||||
/** @internal */ _autoRenewToken = true,
|
||||
/** @internal */ _attempt = 0
|
||||
/** @internal */ _attempt = 0,
|
||||
): Promise<HasResponse<T, Response>> {
|
||||
if (this._token_expired && _autoRenewToken && !this._renewToken) {
|
||||
if (!this.onTokenExpired || _attempt) throw new Error('Token expired');
|
||||
|
||||
this._renewToken = this.onTokenExpired.call(null).then(data => {
|
||||
if (data) this.setTokenWithSavedToken(data);
|
||||
}).finally(() => {
|
||||
this._renewToken = null;
|
||||
});
|
||||
}
|
||||
|
||||
if (this._renewToken && _autoRenewToken) {
|
||||
await this._renewToken;
|
||||
}
|
||||
|
|
@ -239,6 +263,7 @@ export class NooklinkUserApi {
|
|||
debug('fetch %s %s, response %s', method, url, response.status);
|
||||
|
||||
if (response.status === 401 && _autoRenewToken && !_attempt && this.onTokenExpired) {
|
||||
this._token_expired = true;
|
||||
const data = await response.json() as WebServiceError;
|
||||
|
||||
// _renewToken will be awaited when calling fetch
|
||||
|
|
@ -250,14 +275,14 @@ export class NooklinkUserApi {
|
|||
return this.fetch(url, method, body, headers, _autoRenewToken, _attempt + 1);
|
||||
}
|
||||
|
||||
if (response.status !== 200 && response.status !== 201) {
|
||||
throw new ErrorResponse('[nooklink] Non-200/201 status code', response, await response.text());
|
||||
if (!response.ok) {
|
||||
throw new NooklinkErrorResponse('[nooklink] Non-2xx status code', response, await response.text());
|
||||
}
|
||||
|
||||
const data = await response.json() as T | WebServiceError;
|
||||
|
||||
if ('code' in data) {
|
||||
throw new ErrorResponse<WebServiceError>('[nooklink] Error ' + data.code, response, data);
|
||||
throw new NooklinkErrorResponse('[nooklink] Error ' + data.code, response, data);
|
||||
}
|
||||
|
||||
return defineResponse(data, response);
|
||||
|
|
@ -327,6 +352,7 @@ export class NooklinkUserApi {
|
|||
this.user_id = data.user_id;
|
||||
this.auth_token = data.token.token;
|
||||
this.gtoken = data.gtoken;
|
||||
this._token_expired = false;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
|
|
@ -365,6 +391,8 @@ export class NooklinkUserApi {
|
|||
}
|
||||
}
|
||||
|
||||
export class NooklinkErrorResponse extends ErrorResponse<WebServiceError> {}
|
||||
|
||||
export interface NooklinkAuthData {
|
||||
webserviceToken: WebServiceToken;
|
||||
url: string;
|
||||
|
|
|
|||
|
|
@ -1,11 +1,10 @@
|
|||
import fetch from 'node-fetch';
|
||||
import createDebug from 'debug';
|
||||
import { v4 as uuidgen } from 'uuid';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { Cookie, fetch, FormData, getSetCookies } from 'undici';
|
||||
import { WebServiceToken } from './coral-types.js';
|
||||
import { NintendoAccountUser } from './na.js';
|
||||
import { defineResponse, ErrorResponse } from './util.js';
|
||||
import CoralApi from './coral.js';
|
||||
import { CoralApiInterface, NintendoAccountUserCoral } from './coral.js';
|
||||
import { ActiveFestivals, CoopResult, CoopResults, CoopSchedules, HeroRecords, LeagueMatchRankings, NicknameAndIcons, PastFestivals, Records, Result, Results, Schedules, ShareResponse, ShopMerchandises, Stages, Timeline, WebServiceError, XPowerRankingRecords, XPowerRankingSummary } from './splatnet2-types.js';
|
||||
import createDebug from '../util/debug.js';
|
||||
import { timeoutSignal } from '../util/misc.js';
|
||||
import { toSeasonId, Rule as XPowerRankingRule, Season } from './splatnet2-xrank.js';
|
||||
|
||||
|
|
@ -25,6 +24,8 @@ export const updateIksmSessionLastUsed: {
|
|||
} = {};
|
||||
|
||||
export default class SplatNet2Api {
|
||||
protected _session_expired = false;
|
||||
|
||||
protected constructor(
|
||||
public iksm_session: string,
|
||||
public unique_id: string,
|
||||
|
|
@ -32,6 +33,10 @@ export default class SplatNet2Api {
|
|||
) {}
|
||||
|
||||
async fetch<T extends object>(url: string, method = 'GET', body?: string | FormData, headers?: object) {
|
||||
if (this._session_expired) {
|
||||
throw new Error('Session expired');
|
||||
}
|
||||
|
||||
const [signal, cancel] = timeoutSignal();
|
||||
const response = await fetch(SPLATNET2_URL + url, {
|
||||
method,
|
||||
|
|
@ -52,8 +57,12 @@ export default class SplatNet2Api {
|
|||
|
||||
debug('fetch %s %s, response %s', method, url, response.status);
|
||||
|
||||
if (response.status === 401) {
|
||||
this._session_expired = true;
|
||||
}
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw new ErrorResponse('[splatnet2] Non-200 status code', response, await response.text());
|
||||
throw await SplatNet2ErrorResponse.fromResponse(response, '[splatnet2] Non-200 status code');
|
||||
}
|
||||
|
||||
updateIksmSessionLastUsed.handler?.call(null, this.iksm_session);
|
||||
|
|
@ -61,7 +70,7 @@ export default class SplatNet2Api {
|
|||
const data = await response.json() as T | WebServiceError;
|
||||
|
||||
if ('code' in data) {
|
||||
throw new ErrorResponse<WebServiceError>('[splatnet2] ' + data.message, response, data);
|
||||
throw new SplatNet2ErrorResponse('[splatnet2] ' + data.message, response, data);
|
||||
}
|
||||
|
||||
return defineResponse(data, response);
|
||||
|
|
@ -183,7 +192,7 @@ export default class SplatNet2Api {
|
|||
}
|
||||
|
||||
async shareProfile(stage: string, colour: ShareColour) {
|
||||
const boundary = uuidgen();
|
||||
const boundary = randomUUID();
|
||||
|
||||
const data = `--${boundary}
|
||||
Content-Disposition: form-data; name="stage"
|
||||
|
|
@ -230,8 +239,8 @@ ${colour}
|
|||
});
|
||||
}
|
||||
|
||||
static async createWithCoral(nso: CoralApi, user: NintendoAccountUser) {
|
||||
const data = await this.loginWithCoral(nso, user);
|
||||
static async createWithCoral(coral: CoralApiInterface, user: NintendoAccountUserCoral) {
|
||||
const data = await this.loginWithCoral(coral, user);
|
||||
return {splatnet: this.createWithSavedToken(data), data};
|
||||
}
|
||||
|
||||
|
|
@ -259,14 +268,14 @@ ${colour}
|
|||
);
|
||||
}
|
||||
|
||||
static async loginWithCoral(nso: CoralApi, user: NintendoAccountUser) {
|
||||
const webserviceToken = await nso.getWebServiceToken(SPLATNET2_WEBSERVICE_ID);
|
||||
static async loginWithCoral(coral: CoralApiInterface, user: NintendoAccountUserCoral) {
|
||||
const webserviceToken = await coral.getWebServiceToken(SPLATNET2_WEBSERVICE_ID);
|
||||
|
||||
return this.loginWithWebServiceToken(webserviceToken, user);
|
||||
}
|
||||
|
||||
static async loginWithWebServiceToken(
|
||||
webserviceToken: WebServiceToken, user: NintendoAccountUser
|
||||
webserviceToken: WebServiceToken, user: NintendoAccountUserCoral
|
||||
): Promise<SplatNet2AuthData> {
|
||||
const url = new URL(SPLATNET2_WEBSERVICE_URL);
|
||||
url.search = new URLSearchParams({
|
||||
|
|
@ -280,6 +289,7 @@ ${colour}
|
|||
headers: {
|
||||
'Upgrade-Insecure-Requests': '1',
|
||||
'User-Agent': SPLATNET2_WEBSERVICE_USERAGENT,
|
||||
'x-appplatform': 'android',
|
||||
'x-appcolorscheme': 'DARK',
|
||||
'x-gamewebtoken': webserviceToken.accessToken,
|
||||
'dnt': '1',
|
||||
|
|
@ -292,27 +302,22 @@ ${colour}
|
|||
|
||||
debug('fetch %s %s, response %s', 'GET', url, response.status);
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw await SplatNet2ErrorResponse.fromResponse(response, '[splatnet2] Non-200 status code');
|
||||
}
|
||||
|
||||
const body = await response.text();
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw new ErrorResponse('[splatnet2] Non-200 status code', response, body);
|
||||
const cookies = getSetCookies(response.headers);
|
||||
const iksm_session = cookies.find(c => c.name === 'iksm_session');
|
||||
|
||||
if (!iksm_session) {
|
||||
throw new SplatNet2ErrorResponse('[splatnet2] Response didn\'t include iksm_session cookie', response, body);
|
||||
}
|
||||
|
||||
const cookies = response.headers.get('Set-Cookie');
|
||||
const match = cookies?.match(/\biksm_session=([^;]*)(;(\s*((?!expires)[a-z]+=([^;]*));?)*(\s*(expires=([^;]*));?)?|$)/i);
|
||||
const expires_at: number = (iksm_session.expires as Date)?.getTime() ?? Date.now() + 24 * 60 * 60 * 1000;
|
||||
|
||||
if (!match) {
|
||||
throw new ErrorResponse('[splatnet2] Response didn\'t include iksm_session cookie', response, body);
|
||||
}
|
||||
|
||||
const iksm_session = decodeURIComponent(match[1]);
|
||||
// Nintendo sets the expires field to an invalid timestamp - browsers don't care but Data.parse does
|
||||
const expires = decodeURIComponent(match[8] || '')
|
||||
.replace(/(\b)(\d{1,2})-([a-z]{3})-(\d{4})(\b)/gi, '$1$2 $3 $4$5');
|
||||
|
||||
debug('iksm_session %s, expires %s', iksm_session.replace(/^(.{6}).*/, '$1****'), expires);
|
||||
|
||||
const expires_at = expires ? Date.parse(expires) : Date.now() + 24 * 60 * 60 * 1000;
|
||||
debug('iksm_session %s, expires %s', iksm_session.value.replace(/^(.{6}).*/, '$1****'), iksm_session.expires);
|
||||
|
||||
const ml = body.match(/<html(?:\s+[a-z0-9-]+(?:=(?:"[^"]*"|[^\s>]*))?)*\s+lang=(?:"([^"]*)"|([^\s>]*))/i);
|
||||
const mr = body.match(/<html(?:\s+[a-z0-9-]+(?:=(?:"[^"]*"|[^\s>]*))?)*\s+data-region=(?:"([^"]*)"|([^\s>]*))/i);
|
||||
|
|
@ -320,10 +325,10 @@ ${colour}
|
|||
const mn = body.match(/<html(?:\s+[a-z0-9-]+(?:=(?:"[^"]*"|[^\s>]*))?)*\s+data-nsa-id=(?:"([^"]*)"|([^\s>]*))/i);
|
||||
const [language, region, user_id, nsa_id] = [ml, mr, mu, mn].map(m => m?.[1] || m?.[2] || null);
|
||||
|
||||
if (!language) throw new Error('[splatnet2] Invalid language in response');
|
||||
if (!region) throw new Error('[splatnet2] Invalid region in response');
|
||||
if (!user_id) throw new Error('[splatnet2] Invalid unique player ID in response');
|
||||
if (!nsa_id) throw new Error('[splatnet2] Invalid NSA ID in response');
|
||||
if (!language) throw new ErrorResponse('[splatnet2] Invalid language in response', response, body);
|
||||
if (!region) throw new ErrorResponse('[splatnet2] Invalid region in response', response, body);
|
||||
if (!user_id) throw new ErrorResponse('[splatnet2] Invalid unique player ID in response', response, body);
|
||||
if (!nsa_id) throw new ErrorResponse('[splatnet2] Invalid NSA ID in response', response, body);
|
||||
|
||||
debug('SplatNet 2 user', {
|
||||
language,
|
||||
|
|
@ -335,24 +340,26 @@ ${colour}
|
|||
return {
|
||||
webserviceToken,
|
||||
url: url.toString(),
|
||||
cookies: cookies!,
|
||||
cookies,
|
||||
body,
|
||||
language,
|
||||
region,
|
||||
user_id,
|
||||
nsa_id,
|
||||
|
||||
iksm_session,
|
||||
iksm_session: iksm_session.value,
|
||||
expires_at,
|
||||
useragent: SPLATNET2_WEBSERVICE_USERAGENT,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export class SplatNet2ErrorResponse extends ErrorResponse<WebServiceError> {}
|
||||
|
||||
export interface SplatNet2AuthData {
|
||||
webserviceToken: WebServiceToken;
|
||||
url: string;
|
||||
cookies: string;
|
||||
cookies: string | Cookie[];
|
||||
body: string;
|
||||
|
||||
language: string;
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
import createDebug from 'debug';
|
||||
import fetch, { Response } from 'node-fetch';
|
||||
import { BankaraBattleHistoriesRefetchResult, BankaraBattleHistoriesRefetchVariables, GraphQLRequest, GraphQLResponse, GraphQLSuccessResponse, KnownRequestId, LatestBattleHistoriesRefetchResult, LatestBattleHistoriesRefetchVariables, MyOutfitInput, PagerUpdateBattleHistoriesByVsModeResult, PagerUpdateBattleHistoriesByVsModeVariables, PrivateBattleHistoriesRefetchResult, PrivateBattleHistoriesRefetchVariables, RegularBattleHistoriesRefetchResult, RegularBattleHistoriesRefetchVariables, RequestId, ResultTypes, VariablesTypes, XBattleHistoriesRefetchResult, XBattleHistoriesRefetchVariables } from 'splatnet3-types/splatnet3';
|
||||
import { timeoutSignal } from '../util/misc.js';
|
||||
import { fetch, Response } from 'undici';
|
||||
import { BankaraBattleHistoriesRefetchResult, BankaraBattleHistoriesRefetchVariables, GraphQLError, GraphQLErrorResponse, GraphQLRequest, GraphQLResponse, GraphQLSuccessResponse, KnownRequestId, LatestBattleHistoriesRefetchResult, LatestBattleHistoriesRefetchVariables, MyOutfitInput, PagerUpdateBattleHistoriesByVsModeResult, PagerUpdateBattleHistoriesByVsModeVariables, PrivateBattleHistoriesRefetchResult, PrivateBattleHistoriesRefetchVariables, RegularBattleHistoriesRefetchResult, RegularBattleHistoriesRefetchVariables, RequestId, ResultTypes, VariablesTypes, XBattleHistoriesRefetchResult, XBattleHistoriesRefetchVariables } from 'splatnet3-types/splatnet3';
|
||||
import { WebServiceToken } from './coral-types.js';
|
||||
import CoralApi from './coral.js';
|
||||
import { CoralApiInterface, NintendoAccountUserCoral } from './coral.js';
|
||||
import { NintendoAccountUser } from './na.js';
|
||||
import { BulletToken } from './splatnet3-types.js';
|
||||
import { defineResponse, ErrorResponse, HasResponse, ResponseSymbol } from './util.js';
|
||||
import createDebug from '../util/debug.js';
|
||||
import { timeoutSignal } from '../util/misc.js';
|
||||
|
||||
const debug = createDebug('nxapi:api:splatnet3');
|
||||
const debugGraphQl = createDebug('nxapi:api:splatnet3:graphql');
|
||||
|
|
@ -17,7 +17,7 @@ export const SPLATNET3_WEBSERVICE_ID = 4834290508791808;
|
|||
export const SPLATNET3_WEBSERVICE_URL = 'https://api.lp1.av5ja.srv.nintendo.net';
|
||||
export const SPLATNET3_WEBSERVICE_USERAGENT = 'Mozilla/5.0 (Linux; Android 8.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/58.0.3029.125 Mobile Safari/537.36';
|
||||
|
||||
const languages = [
|
||||
export const languages = [
|
||||
'de-DE', 'en-GB', 'en-US', 'es-ES', 'es-MX', 'fr-CA',
|
||||
'fr-FR', 'it-IT', 'ja-JP', 'ko-KR', 'nl-NL', 'ru-RU',
|
||||
'zh-CN', 'zh-TW',
|
||||
|
|
@ -27,15 +27,25 @@ const SPLATNET3_URL = SPLATNET3_WEBSERVICE_URL + '/api';
|
|||
const SHOULD_RENEW_TOKEN_AT = 300; // 5 minutes in seconds
|
||||
const TOKEN_EXPIRES_IN = 2 * 60 * 60 * 1000; // 2 hours in milliseconds
|
||||
|
||||
export enum SplatNet3AuthErrorCode {
|
||||
USER_NOT_REGISTERED = 'USER_NOT_REGISTERED',
|
||||
ERROR_INVALID_PARAMETERS = 'ERROR_INVALID_PARAMETERS',
|
||||
ERROR_INVALID_GAME_WEB_TOKEN = 'ERROR_INVALID_GAME_WEB_TOKEN',
|
||||
ERROR_OBSOLETE_VERSION = 'ERROR_OBSOLETE_VERSION',
|
||||
ERROR_RATE_LIMIT = 'ERROR_RATE_LIMIT',
|
||||
ERROR_SERVER = 'ERROR_SERVER',
|
||||
ERROR_SERVER_MAINTENANCE = 'ERROR_SERVER_MAINTENANCE',
|
||||
}
|
||||
|
||||
const AUTH_ERROR_CODES = {
|
||||
204: 'USER_NOT_REGISTERED',
|
||||
400: 'ERROR_INVALID_PARAMETERS',
|
||||
401: 'ERROR_INVALID_GAME_WEB_TOKEN',
|
||||
403: 'ERROR_OBSOLETE_VERSION',
|
||||
429: 'ERROR_RATE_LIMIT',
|
||||
500: 'ERROR_SERVER',
|
||||
503: 'ERROR_SERVER_MAINTENANCE',
|
||||
599: 'ERROR_SERVER',
|
||||
204: SplatNet3AuthErrorCode.USER_NOT_REGISTERED,
|
||||
400: SplatNet3AuthErrorCode.ERROR_INVALID_PARAMETERS,
|
||||
401: SplatNet3AuthErrorCode.ERROR_INVALID_GAME_WEB_TOKEN,
|
||||
403: SplatNet3AuthErrorCode.ERROR_OBSOLETE_VERSION,
|
||||
429: SplatNet3AuthErrorCode.ERROR_RATE_LIMIT,
|
||||
500: SplatNet3AuthErrorCode.ERROR_SERVER,
|
||||
503: SplatNet3AuthErrorCode.ERROR_SERVER_MAINTENANCE,
|
||||
599: SplatNet3AuthErrorCode.ERROR_SERVER,
|
||||
} as const;
|
||||
|
||||
const REPLAY_CODE_REGEX = /^[A-Z0-9]{16}$/;
|
||||
|
|
@ -51,6 +61,16 @@ export interface PersistedQueryResultData {
|
|||
[VariablesSymbol]: {};
|
||||
}
|
||||
|
||||
export type NotNullPersistedQueryResult<
|
||||
T extends PersistedQueryResult<unknown> | unknown,
|
||||
K extends T extends PersistedQueryResult<infer Result> ? keyof Result : keyof T,
|
||||
> =
|
||||
T extends PersistedQueryResult<infer Result> ? PersistedQueryResult<{
|
||||
[FieldName in keyof Result]: FieldName extends K ? Exclude<Result[FieldName], null> : Result[FieldName];
|
||||
}> : PersistedQueryResult<{
|
||||
[FieldName in keyof T]: FieldName extends K ? Exclude<T[FieldName], null> : T[FieldName];
|
||||
}>;
|
||||
|
||||
enum MapQueriesMode {
|
||||
/** NXAPI_SPLATNET3_UPGRADE_QUERIES=0 - never upgrade persisted query IDs (not recommended) */
|
||||
NEVER,
|
||||
|
|
@ -64,9 +84,10 @@ enum MapQueriesMode {
|
|||
|
||||
export default class SplatNet3Api {
|
||||
onTokenShouldRenew: ((remaining: number, res: Response) => Promise<SplatNet3AuthData | void>) | null = null;
|
||||
onTokenExpired: ((res: Response) => Promise<SplatNet3AuthData | void>) | null = null;
|
||||
onTokenExpired: ((res?: Response) => Promise<SplatNet3AuthData | void>) | null = null;
|
||||
/** @internal */
|
||||
_renewToken: Promise<void> | null = null;
|
||||
protected _token_expired = false;
|
||||
|
||||
graphql_strict = process.env.NXAPI_SPLATNET3_STRICT !== '0';
|
||||
|
||||
|
|
@ -75,15 +96,26 @@ export default class SplatNet3Api {
|
|||
public version: string,
|
||||
public map_queries: Partial<Record<string, [/** new query ID */ string, /** unsafe */ boolean] | null>>,
|
||||
readonly map_queries_mode: MapQueriesMode,
|
||||
readonly na_country: string,
|
||||
public language: string,
|
||||
public useragent: string,
|
||||
) {}
|
||||
|
||||
async fetch<T = unknown>(
|
||||
url: string, method = 'GET', body?: string | FormData, headers?: object,
|
||||
url: string, method = 'GET', body?: string, headers?: object,
|
||||
/** @internal */ _log?: string,
|
||||
/** @internal */ _attempt = 0
|
||||
/** @internal */ _attempt = 0,
|
||||
): Promise<HasResponse<T, Response>> {
|
||||
if (this._token_expired && !this._renewToken) {
|
||||
if (!this.onTokenExpired || _attempt) throw new Error('Token expired');
|
||||
|
||||
this._renewToken = this.onTokenExpired.call(null).then(data => {
|
||||
if (data) this.setTokenWithSavedToken(data);
|
||||
}).finally(() => {
|
||||
this._renewToken = null;
|
||||
});
|
||||
}
|
||||
|
||||
if (this._renewToken) {
|
||||
await this._renewToken;
|
||||
}
|
||||
|
|
@ -110,6 +142,7 @@ export default class SplatNet3Api {
|
|||
response.status, version);
|
||||
|
||||
if (response.status === 401 && !_attempt && this.onTokenExpired) {
|
||||
this._token_expired = true;
|
||||
// _renewToken will be awaited when calling fetch
|
||||
this._renewToken = this._renewToken ?? this.onTokenExpired.call(null, response).then(data => {
|
||||
if (data) this.setTokenWithSavedToken(data);
|
||||
|
|
@ -120,7 +153,7 @@ export default class SplatNet3Api {
|
|||
}
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw new ErrorResponse('[splatnet3] Non-200 status code', response, await response.text());
|
||||
throw await SplatNet3ErrorResponse.fromResponse(response, '[splatnet3] Non-200 status code');
|
||||
}
|
||||
|
||||
const remaining = parseInt(response.headers.get('x-bullettoken-remaining') ?? '0');
|
||||
|
|
@ -166,9 +199,9 @@ export default class SplatNet3Api {
|
|||
const data = await this.fetch<GraphQLResponse<_Result>>('/graphql', 'POST', JSON.stringify(req), undefined,
|
||||
'graphql query ' + id);
|
||||
|
||||
if (!('data' in data) || (this.graphql_strict && data.errors?.length)) {
|
||||
throw new ErrorResponse('[splatnet3] GraphQL error: ' + data.errors!.map(e => e.message).join(', '),
|
||||
data[ResponseSymbol], data);
|
||||
if (data.errors && (!('data' in data) || this.graphql_strict)) {
|
||||
throw SplatNet3GraphQLErrorResponse.from(data[ResponseSymbol], data as GraphQLResponseWithErrors,
|
||||
id, variables);
|
||||
}
|
||||
|
||||
for (const error of data.errors ?? []) {
|
||||
|
|
@ -234,12 +267,16 @@ export default class SplatNet3Api {
|
|||
|
||||
/** / */
|
||||
async getHome() {
|
||||
return this.persistedQuery(RequestId.HomeQuery, {});
|
||||
return this.persistedQuery(RequestId.HomeQuery, {
|
||||
naCountry: this.na_country,
|
||||
});
|
||||
}
|
||||
|
||||
/** / -> /setting */
|
||||
async getSettings() {
|
||||
return this.persistedQuery(RequestId.SettingQuery, {});
|
||||
return this.persistedQuery(RequestId.SettingQuery, {
|
||||
naCountry: this.na_country,
|
||||
});
|
||||
}
|
||||
|
||||
/** / -> /photo_album */
|
||||
|
|
@ -350,10 +387,10 @@ export default class SplatNet3Api {
|
|||
});
|
||||
|
||||
if (!result.data.journey) {
|
||||
throw new ErrorResponse('[splatnet3] Journey not found', result[ResponseSymbol], result);
|
||||
throw SplatNet3GraphQLResourceNotFoundResponse.from('[splatnet3] Journey not found', result);
|
||||
}
|
||||
|
||||
return result;
|
||||
return result as NotNullPersistedQueryResult<typeof result, 'journey'>;
|
||||
}
|
||||
|
||||
/** / -> /challenge -> /challenge/{id} -> pull-to-refresh */
|
||||
|
|
@ -363,10 +400,10 @@ export default class SplatNet3Api {
|
|||
});
|
||||
|
||||
if (!result.data.journey) {
|
||||
throw new ErrorResponse('[splatnet3] Journey not found', result[ResponseSymbol], result);
|
||||
throw SplatNet3GraphQLResourceNotFoundResponse.from('[splatnet3] Journey not found', result);
|
||||
}
|
||||
|
||||
return result;
|
||||
return result as NotNullPersistedQueryResult<typeof result, 'journey'>;
|
||||
}
|
||||
|
||||
/** / -> /challenge -> /challenge/{id} -> /challenge/{id}/*s */
|
||||
|
|
@ -376,10 +413,10 @@ export default class SplatNet3Api {
|
|||
});
|
||||
|
||||
if (!result.data.journey) {
|
||||
throw new ErrorResponse('[splatnet3] Journey not found', result[ResponseSymbol], result);
|
||||
throw SplatNet3GraphQLResourceNotFoundResponse.from('[splatnet3] Journey not found', result);
|
||||
}
|
||||
|
||||
return result;
|
||||
return result as NotNullPersistedQueryResult<typeof result, 'journey'>;
|
||||
}
|
||||
|
||||
/** / -> /challenge -> /challenge/{id} -> /challenge/{id}/* -> pull-to-refresh */
|
||||
|
|
@ -389,10 +426,10 @@ export default class SplatNet3Api {
|
|||
});
|
||||
|
||||
if (!result.data.journey) {
|
||||
throw new ErrorResponse('[splatnet3] Journey not found', result[ResponseSymbol], result);
|
||||
throw SplatNet3GraphQLResourceNotFoundResponse.from('[splatnet3] Journey not found', result);
|
||||
}
|
||||
|
||||
return result;
|
||||
return result as NotNullPersistedQueryResult<typeof result, 'journey'>;
|
||||
}
|
||||
|
||||
/** / -> /challenge -> /challenge/{id} -> /challenge/{id}/* -> support */
|
||||
|
|
@ -423,10 +460,10 @@ export default class SplatNet3Api {
|
|||
});
|
||||
|
||||
if (!result.data.fest) {
|
||||
throw new ErrorResponse('[splatnet3] Fest not found', result[ResponseSymbol], result);
|
||||
throw SplatNet3GraphQLResourceNotFoundResponse.from('[splatnet3] Fest not found', result);
|
||||
}
|
||||
|
||||
return result;
|
||||
return result as NotNullPersistedQueryResult<typeof result, 'fest'>;
|
||||
}
|
||||
|
||||
/** / -> /fest_record -> /fest_record/{id} -> pull-to-refresh */
|
||||
|
|
@ -436,10 +473,10 @@ export default class SplatNet3Api {
|
|||
});
|
||||
|
||||
if (!result.data.fest) {
|
||||
throw new ErrorResponse('[splatnet3] Fest not found', result[ResponseSymbol], result);
|
||||
throw SplatNet3GraphQLResourceNotFoundResponse.from('[splatnet3] Fest not found', result);
|
||||
}
|
||||
|
||||
return result;
|
||||
return result as NotNullPersistedQueryResult<typeof result, 'fest'>;
|
||||
}
|
||||
|
||||
/** / -> /fest_record -> /fest_record/{id} - not closed -> /fest_record/voting_status/{id} */
|
||||
|
|
@ -449,10 +486,10 @@ export default class SplatNet3Api {
|
|||
});
|
||||
|
||||
if (!result.data.fest) {
|
||||
throw new ErrorResponse('[splatnet3] Fest not found', result[ResponseSymbol], result);
|
||||
throw SplatNet3GraphQLResourceNotFoundResponse.from('[splatnet3] Fest not found', result);
|
||||
}
|
||||
|
||||
return result;
|
||||
return result as NotNullPersistedQueryResult<typeof result, 'fest'>;
|
||||
}
|
||||
|
||||
/** / -> /fest_record -> /fest_record/{id} - not closed -> /fest_record/voting_status/{id} -> pull-to-refresh */
|
||||
|
|
@ -462,10 +499,10 @@ export default class SplatNet3Api {
|
|||
});
|
||||
|
||||
if (!result.data.fest) {
|
||||
throw new ErrorResponse('[splatnet3] Fest not found', result[ResponseSymbol], result);
|
||||
throw SplatNet3GraphQLResourceNotFoundResponse.from('[splatnet3] Fest not found', result);
|
||||
}
|
||||
|
||||
return result;
|
||||
return result as NotNullPersistedQueryResult<typeof result, 'fest'>;
|
||||
}
|
||||
|
||||
/** / -> /fest_record -> /fest_record/{id} - not closed -> /fest_record/voting_status/{id} - not voted in game */
|
||||
|
|
@ -482,10 +519,10 @@ export default class SplatNet3Api {
|
|||
});
|
||||
|
||||
if (!result.data.fest) {
|
||||
throw new ErrorResponse('[splatnet3] Fest not found', result[ResponseSymbol], result);
|
||||
throw SplatNet3GraphQLResourceNotFoundResponse.from('[splatnet3] Fest not found', result);
|
||||
}
|
||||
|
||||
return result;
|
||||
return result as NotNullPersistedQueryResult<typeof result, 'fest'>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -501,10 +538,10 @@ export default class SplatNet3Api {
|
|||
});
|
||||
|
||||
if (!result.data.node) {
|
||||
throw new ErrorResponse('[splatnet3] FestTeam not found', result[ResponseSymbol], result);
|
||||
throw SplatNet3GraphQLResourceNotFoundResponse.from('[splatnet3] FestTeam not found', result);
|
||||
}
|
||||
|
||||
return result;
|
||||
return result as NotNullPersistedQueryResult<typeof result, 'node'>;
|
||||
}
|
||||
|
||||
//
|
||||
|
|
@ -562,7 +599,7 @@ export default class SplatNet3Api {
|
|||
null :
|
||||
null;
|
||||
|
||||
if (!query) throw new Error('Invalid leaderboard');
|
||||
if (!query) throw new TypeError('Invalid leaderboard');
|
||||
|
||||
return this.persistedQuery<{
|
||||
[XRankingLeaderboardType.X_RANKING]: {
|
||||
|
|
@ -606,10 +643,10 @@ export default class SplatNet3Api {
|
|||
});
|
||||
|
||||
if (!result.data.saleGear) {
|
||||
throw new ErrorResponse('[splatnet3] Sale gear not found', result[ResponseSymbol], result);
|
||||
throw SplatNet3GraphQLResourceNotFoundResponse.from('[splatnet3] Sale gear not found', result);
|
||||
}
|
||||
|
||||
return result;
|
||||
return result as NotNullPersistedQueryResult<typeof result, 'saleGear'>;
|
||||
}
|
||||
|
||||
/** / -> /gesotown -> /gesotown/{id} -> order */
|
||||
|
|
@ -643,10 +680,10 @@ export default class SplatNet3Api {
|
|||
});
|
||||
|
||||
if (!result.data.myOutfit) {
|
||||
throw new ErrorResponse('[splatnet3] My outfit not found', result[ResponseSymbol], result);
|
||||
throw SplatNet3GraphQLResourceNotFoundResponse.from('[splatnet3] My outfit not found', result);
|
||||
}
|
||||
|
||||
return result;
|
||||
return result as NotNullPersistedQueryResult<typeof result, 'myOutfit'>;
|
||||
}
|
||||
|
||||
/** / -> /my_outfits -> /my_outfits/{id / create} */
|
||||
|
|
@ -683,6 +720,14 @@ export default class SplatNet3Api {
|
|||
});
|
||||
}
|
||||
|
||||
/** / -> /my_outfits [-> /my_outfits/{id}] -> share */
|
||||
async shareOutfit(index: number, timezone_offset_minutes = 0) {
|
||||
return this.persistedQuery(RequestId.ShareMyOutfitQuery, {
|
||||
myOutfitIndex: index,
|
||||
timezoneOffset: timezone_offset_minutes, // (new Date()).getTimezoneOffset()
|
||||
});
|
||||
}
|
||||
|
||||
//
|
||||
// Replays
|
||||
//
|
||||
|
|
@ -706,10 +751,10 @@ export default class SplatNet3Api {
|
|||
});
|
||||
|
||||
if (!result.data.replay) {
|
||||
throw new ErrorResponse('[splatnet3] Replay not found', result[ResponseSymbol], result);
|
||||
throw SplatNet3GraphQLResourceNotFoundResponse.from('[splatnet3] Replay not found', result);
|
||||
}
|
||||
|
||||
return result;
|
||||
return result as NotNullPersistedQueryResult<typeof result, 'replay'>;
|
||||
}
|
||||
|
||||
/** / -> /replay -> enter code -> download */
|
||||
|
|
@ -807,10 +852,10 @@ export default class SplatNet3Api {
|
|||
});
|
||||
|
||||
if (!result.data.vsHistoryDetail) {
|
||||
throw new ErrorResponse('[splatnet3] Battle history not found', result[ResponseSymbol], result);
|
||||
throw SplatNet3GraphQLResourceNotFoundResponse.from('[splatnet3] Battle history not found', result);
|
||||
}
|
||||
|
||||
return result;
|
||||
return result as NotNullPersistedQueryResult<typeof result, 'vsHistoryDetail'>;
|
||||
}
|
||||
|
||||
/** / -> /history -> /history/detail/{id} -> pull-to-refresh */
|
||||
|
|
@ -820,10 +865,10 @@ export default class SplatNet3Api {
|
|||
});
|
||||
|
||||
if (!result.data.vsHistoryDetail) {
|
||||
throw new ErrorResponse('[splatnet3] Battle history not found', result[ResponseSymbol], result);
|
||||
throw SplatNet3GraphQLResourceNotFoundResponse.from('[splatnet3] Battle history not found', result);
|
||||
}
|
||||
|
||||
return result;
|
||||
return result as NotNullPersistedQueryResult<typeof result, 'vsHistoryDetail'>;
|
||||
}
|
||||
|
||||
/** / -> /history -> /history/detail/* -> latest */
|
||||
|
|
@ -838,7 +883,7 @@ export default class SplatNet3Api {
|
|||
PagerUpdateBattleHistoriesByVsModeVariables
|
||||
>(RequestId.PagerUpdateBattleHistoriesByVsModeQuery, {
|
||||
isBankara: false,
|
||||
isLeague: false,
|
||||
isEvent: false,
|
||||
isPrivate: false,
|
||||
isRegular: false,
|
||||
isXBattle: false,
|
||||
|
|
@ -866,10 +911,10 @@ export default class SplatNet3Api {
|
|||
});
|
||||
|
||||
if (!result.data.coopHistoryDetail) {
|
||||
throw new ErrorResponse('[splatnet3] Co-op history not found', result[ResponseSymbol], result);
|
||||
throw SplatNet3GraphQLResourceNotFoundResponse.from('[splatnet3] Co-op history not found', result);
|
||||
}
|
||||
|
||||
return result;
|
||||
return result as NotNullPersistedQueryResult<typeof result, 'coopHistoryDetail'>;
|
||||
}
|
||||
|
||||
/** / -> /coop -> /coop/{id} -> pull-to-refresh */
|
||||
|
|
@ -879,10 +924,10 @@ export default class SplatNet3Api {
|
|||
});
|
||||
|
||||
if (!result.data.node) {
|
||||
throw new ErrorResponse('[splatnet3] Co-op history not found', result[ResponseSymbol], result);
|
||||
throw SplatNet3GraphQLResourceNotFoundResponse.from('[splatnet3] Co-op history not found', result);
|
||||
}
|
||||
|
||||
return result;
|
||||
return result as NotNullPersistedQueryResult<typeof result, 'node'>;
|
||||
}
|
||||
|
||||
/** / -> /coop -> /coop/* -> latest */
|
||||
|
|
@ -893,13 +938,13 @@ export default class SplatNet3Api {
|
|||
//
|
||||
//
|
||||
|
||||
async renewTokenWithCoral(nso: CoralApi, user: NintendoAccountUser) {
|
||||
const data = await SplatNet3Api.loginWithCoral(nso, user);
|
||||
async renewTokenWithCoral(coral: CoralApiInterface, user: NintendoAccountUserCoral) {
|
||||
const data = await SplatNet3Api.loginWithCoral(coral, user);
|
||||
this.setTokenWithSavedToken(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
async renewTokenWithWebServiceToken(webserviceToken: WebServiceToken, user: NintendoAccountUser) {
|
||||
async renewTokenWithWebServiceToken(webserviceToken: WebServiceToken, user: NintendoAccountUserCoral) {
|
||||
const data = await SplatNet3Api.loginWithWebServiceToken(webserviceToken, user);
|
||||
this.setTokenWithSavedToken(data);
|
||||
return data;
|
||||
|
|
@ -910,10 +955,11 @@ export default class SplatNet3Api {
|
|||
this.version = data.version;
|
||||
this.language = data.bullet_token.lang;
|
||||
this.useragent = data.useragent;
|
||||
this._token_expired = false;
|
||||
}
|
||||
|
||||
static async createWithCoral(nso: CoralApi, user: NintendoAccountUser) {
|
||||
const data = await this.loginWithCoral(nso, user);
|
||||
static async createWithCoral(coral: CoralApiInterface, user: NintendoAccountUserCoral) {
|
||||
const data = await this.loginWithCoral(coral, user);
|
||||
return {splatnet: this.createWithSavedToken(data), data};
|
||||
}
|
||||
|
||||
|
|
@ -923,6 +969,7 @@ export default class SplatNet3Api {
|
|||
data.version,
|
||||
data.queries ?? {},
|
||||
getMapPersistedQueriesModeFromEnvironment(),
|
||||
data.country,
|
||||
data.bullet_token.lang,
|
||||
data.useragent,
|
||||
);
|
||||
|
|
@ -934,22 +981,23 @@ export default class SplatNet3Api {
|
|||
data.version,
|
||||
data.queries ?? {},
|
||||
getMapPersistedQueriesModeFromEnvironment(),
|
||||
data.country ?? 'GB',
|
||||
data.language,
|
||||
SPLATNET3_WEBSERVICE_USERAGENT,
|
||||
);
|
||||
}
|
||||
|
||||
static async loginWithCoral(nso: CoralApi, user: NintendoAccountUser) {
|
||||
static async loginWithCoral(coral: CoralApiInterface, user: NintendoAccountUserCoral) {
|
||||
const { default: { coral_gws_splatnet3: config } } = await import('../common/remote-config.js');
|
||||
if (!config) throw new Error('Remote configuration prevents SplatNet 3 authentication');
|
||||
|
||||
const webserviceToken = await nso.getWebServiceToken(SPLATNET3_WEBSERVICE_ID);
|
||||
const webserviceToken = await coral.getWebServiceToken(SPLATNET3_WEBSERVICE_ID);
|
||||
|
||||
return this.loginWithWebServiceToken(webserviceToken, user);
|
||||
}
|
||||
|
||||
static async loginWithWebServiceToken(
|
||||
webserviceToken: WebServiceToken, user: NintendoAccountUser
|
||||
webserviceToken: WebServiceToken, user: NintendoAccountUserCoral
|
||||
): Promise<SplatNet3AuthData> {
|
||||
const { default: { coral_gws_splatnet3: config } } = await import('../common/remote-config.js');
|
||||
if (!config) throw new Error('Remote configuration prevents SplatNet 3 authentication');
|
||||
|
|
@ -969,6 +1017,7 @@ export default class SplatNet3Api {
|
|||
headers: {
|
||||
'Upgrade-Insecure-Requests': '1',
|
||||
'User-Agent': SPLATNET3_WEBSERVICE_USERAGENT,
|
||||
'x-appplatform': 'android',
|
||||
'x-appcolorscheme': 'DARK',
|
||||
'x-gamewebtoken': webserviceToken.accessToken,
|
||||
'dnt': '1',
|
||||
|
|
@ -981,12 +1030,12 @@ export default class SplatNet3Api {
|
|||
|
||||
debug('fetch %s %s, response %s', 'GET', url, response.status);
|
||||
|
||||
const body = await response.text();
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw new ErrorResponse('[splatnet3] Non-200 status code', response, body);
|
||||
throw await SplatNet3ErrorResponse.fromResponse(response, '[splatnet3] Non-200 status code');
|
||||
}
|
||||
|
||||
const body = await response.text();
|
||||
|
||||
const cookies = response.headers.get('Set-Cookie');
|
||||
|
||||
const [signal2, cancel2] = timeoutSignal();
|
||||
|
|
@ -1009,9 +1058,9 @@ export default class SplatNet3Api {
|
|||
|
||||
debug('fetch %s %s, response %s', 'POST', '/bullet_tokens', response.status);
|
||||
|
||||
const error: string | undefined = AUTH_ERROR_CODES[tr.status as keyof typeof AUTH_ERROR_CODES];
|
||||
if (error) throw new ErrorResponse('[splatnet3] ' + error, tr, await tr.text());
|
||||
if (tr.status !== 201) throw new ErrorResponse('[splatnet3] Non-201 status code', tr, await tr.text());
|
||||
const error: SplatNet3AuthErrorCode | undefined = AUTH_ERROR_CODES[tr.status as keyof typeof AUTH_ERROR_CODES];
|
||||
if (error) throw await SplatNet3AuthErrorResponse.fromResponse(tr, '[splatnet3] ' + error);
|
||||
if (tr.status !== 201) throw await SplatNet3ErrorResponse.fromResponse(tr, '[splatnet3] Non-201 status code');
|
||||
|
||||
const bullet_token = await tr.json() as BulletToken;
|
||||
const created_at = Date.now();
|
||||
|
|
@ -1045,6 +1094,66 @@ function getMapPersistedQueriesModeFromEnvironment(): MapQueriesMode {
|
|||
return MapQueriesMode.ALL;
|
||||
}
|
||||
|
||||
export class SplatNet3ErrorResponse<T = unknown> extends ErrorResponse<T> {}
|
||||
|
||||
export class SplatNet3AuthErrorResponse extends SplatNet3ErrorResponse {
|
||||
constructor(
|
||||
message: string, response: Response | globalThis.Response,
|
||||
body?: string | unknown | undefined,
|
||||
readonly code = AUTH_ERROR_CODES[response.status as keyof typeof AUTH_ERROR_CODES] ??
|
||||
SplatNet3AuthErrorCode.ERROR_SERVER,
|
||||
) {
|
||||
super(message, response, body);
|
||||
}
|
||||
}
|
||||
|
||||
type GraphQLResponseWithErrors = (GraphQLSuccessResponse & {errors: GraphQLError[]}) | GraphQLErrorResponse;
|
||||
|
||||
export class SplatNet3GraphQLErrorResponse<
|
||||
Id extends string = string,
|
||||
/** @private */
|
||||
_Variables extends Id extends KnownRequestId ? VariablesTypes[Id] : unknown =
|
||||
Id extends KnownRequestId ? VariablesTypes[Id] : unknown,
|
||||
> extends SplatNet3ErrorResponse<GraphQLResponseWithErrors> {
|
||||
constructor(
|
||||
message: string, response: Response | globalThis.Response,
|
||||
body?: string | GraphQLResponseWithErrors | undefined,
|
||||
readonly request_id?: Id | string,
|
||||
readonly variables?: _Variables,
|
||||
) {
|
||||
super(message, response, body);
|
||||
}
|
||||
|
||||
static from(response: Response, data: GraphQLResponseWithErrors, id: string, variables: unknown) {
|
||||
return new SplatNet3GraphQLErrorResponse('[splatnet3] GraphQL error: ' +
|
||||
data.errors.map(e => e.message).join(', '), response, data, id, variables);
|
||||
}
|
||||
}
|
||||
|
||||
export class SplatNet3GraphQLResourceNotFoundResponse<
|
||||
Id extends string = string,
|
||||
/** @private */
|
||||
_Result extends Id extends KnownRequestId ? ResultTypes[Id] : unknown =
|
||||
Id extends KnownRequestId ? ResultTypes[Id] : unknown,
|
||||
/** @private */
|
||||
_Variables extends Id extends KnownRequestId ? VariablesTypes[Id] : unknown =
|
||||
Id extends KnownRequestId ? VariablesTypes[Id] : unknown,
|
||||
> extends SplatNet3ErrorResponse<PersistedQueryResult<_Result>> {
|
||||
constructor(
|
||||
message: string, response: Response | globalThis.Response,
|
||||
body?: string | PersistedQueryResult<_Result> | undefined,
|
||||
readonly request_id?: Id | string,
|
||||
readonly variables?: _Variables,
|
||||
) {
|
||||
super(message, response, body);
|
||||
}
|
||||
|
||||
static from(message: string, data: PersistedQueryResult<any>) {
|
||||
return new SplatNet3GraphQLResourceNotFoundResponse<any, any>(
|
||||
message, data[ResponseSymbol], data, data[RequestIdSymbol], data[VariablesSymbol]);
|
||||
}
|
||||
}
|
||||
|
||||
export interface SplatNet3AuthData {
|
||||
webserviceToken: WebServiceToken;
|
||||
url: string;
|
||||
|
|
@ -1071,6 +1180,7 @@ export interface SplatNet3CliTokenData {
|
|||
bullet_token: string;
|
||||
expires_at: number;
|
||||
language: string;
|
||||
country: string;
|
||||
version: string;
|
||||
queries?: Partial<Record<string, [/** new query ID */ string, /** unsafe */ boolean] | null>>;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import * as util from 'node:util';
|
||||
import { Response as NodeFetchResponse } from 'node-fetch';
|
||||
import { Response as UndiciResponse } from 'undici';
|
||||
|
||||
export const ResponseSymbol = Symbol('Response');
|
||||
const ErrorResponseSymbol = Symbol('IsErrorResponse');
|
||||
|
|
@ -20,13 +20,26 @@ export class ErrorResponse<T = unknown> extends Error {
|
|||
|
||||
constructor(
|
||||
message: string,
|
||||
readonly response: Response | NodeFetchResponse,
|
||||
body?: string | T
|
||||
readonly response: Response | UndiciResponse,
|
||||
body?: string | ArrayBuffer | T
|
||||
) {
|
||||
super(message);
|
||||
|
||||
Object.defineProperty(this, ErrorResponseSymbol, {enumerable: false, value: ErrorResponseSymbol});
|
||||
|
||||
if (response.status === 502 &&
|
||||
response.headers.get('Server') === 'cloudflare' &&
|
||||
response.headers.get('Content-Type')?.match(/^text\/html(;|$)/)
|
||||
) {
|
||||
// Cloudflare returns it's own HTML error page for HTTP 502 errors
|
||||
// Logging this isn't helpful so just discard it
|
||||
body = 'Bad Gateway\n';
|
||||
}
|
||||
|
||||
if (body instanceof ArrayBuffer) {
|
||||
body = (new TextDecoder()).decode(body);
|
||||
}
|
||||
|
||||
if (typeof body === 'string') {
|
||||
this.body = body;
|
||||
try {
|
||||
|
|
@ -50,6 +63,12 @@ export class ErrorResponse<T = unknown> extends Error {
|
|||
(lines.length ? '\n' + lines.join('\n') : ''),
|
||||
});
|
||||
}
|
||||
|
||||
static async fromResponse<T>(response: UndiciResponse, message: string) {
|
||||
const body = await response.arrayBuffer();
|
||||
|
||||
return new this<T>(message, response, body);
|
||||
}
|
||||
}
|
||||
|
||||
Object.defineProperty(ErrorResponse, Symbol.hasInstance, {
|
||||
|
|
|
|||
|
|
@ -1,48 +1,57 @@
|
|||
import fetch, { Response } from 'node-fetch';
|
||||
import createDebug from 'debug';
|
||||
import { ActiveEvent, Announcements, CurrentUser, Event, Friend, Presence, PresencePermissions, User, WebService, WebServiceToken, CoralErrorResponse, CoralStatus, CoralSuccessResponse, FriendCodeUser, FriendCodeUrl } from './coral-types.js';
|
||||
import { fetch, Response } from 'undici';
|
||||
import { ActiveEvent, CurrentUser, Event, Friend, PresencePermissions, User, WebServiceToken, CoralStatus, CoralSuccessResponse, FriendCodeUser, FriendCodeUrl, WebService_4, Media, Announcements_4, Friend_4, PresenceOnline_4, PresenceOnline, PresenceOffline, GetActiveEventResult, ReceivedFriendRequest, SentFriendRequest, CoralError } from './coral-types.js';
|
||||
import { defineResponse, ErrorResponse, ResponseSymbol } from './util.js';
|
||||
import CoralApi, { CoralAuthData, CorrelationIdSymbol, PartialCoralAuthData, ResponseDataSymbol, Result } from './coral.js';
|
||||
import { NintendoAccountUser } from './na.js';
|
||||
import { AbstractCoralApi, CoralApiInterface, CoralAuthData, CoralErrorResponse, CorrelationIdSymbol, PartialCoralAuthData, RequestFlagAddPlatformSymbol, RequestFlagAddProductVersionSymbol, RequestFlagNoParameterSymbol, RequestFlagRequestIdSymbol, RequestFlags, ResponseDataSymbol, ResponseEncryptionSymbol, Result } from './coral.js';
|
||||
import { NintendoAccountToken, NintendoAccountUser } from './na.js';
|
||||
import { SavedToken } from '../common/auth/coral.js';
|
||||
import createDebug from '../util/debug.js';
|
||||
import { timeoutSignal } from '../util/misc.js';
|
||||
import { getAdditionalUserAgents, getUserAgent } from '../util/useragent.js';
|
||||
|
||||
const debug = createDebug('nxapi:api:znc-proxy');
|
||||
|
||||
export default class ZncProxyApi implements CoralApi {
|
||||
// Not used by ZncProxyApi
|
||||
onTokenExpired: ((data: CoralErrorResponse, res: Response) => Promise<CoralAuthData | void>) | null = null;
|
||||
/** @internal */
|
||||
_renewToken: Promise<void> | null = null;
|
||||
|
||||
readonly znca_version = '';
|
||||
readonly znca_useragent = '';
|
||||
|
||||
export default class ZncProxyApi extends AbstractCoralApi implements CoralApiInterface {
|
||||
constructor(
|
||||
private url: string,
|
||||
private url: URL | string,
|
||||
// ZncApi uses the NSO token (valid for a few hours)
|
||||
// ZncProxyApi uses the Nintendo Account session token (valid for two years)
|
||||
public token: string,
|
||||
public useragent = getAdditionalUserAgents()
|
||||
) {}
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async fetchProxyApi<T = unknown>(
|
||||
url: URL | string, method = 'GET', body?: string, _headers?: HeadersInit,
|
||||
/** @internal */ _log?: string,
|
||||
) {
|
||||
if (typeof url === 'string' && url.startsWith('/')) url = url.substring(1);
|
||||
|
||||
const base_url = typeof this.url === 'string' ? new URL(this.url) : this.url;
|
||||
if (typeof this.url === 'string' && !base_url.pathname.endsWith('/')) base_url.pathname += '/';
|
||||
|
||||
const headers = new Headers(_headers);
|
||||
|
||||
headers.append('Authorization', 'na ' + this.token);
|
||||
headers.append('User-Agent', getUserAgent(this.useragent));
|
||||
|
||||
if (body && !headers.has('Content-Type')) {
|
||||
headers.append('Content-Type', 'application/json');
|
||||
}
|
||||
|
||||
async fetch<T = unknown>(url: string, method = 'GET', body?: string, headers?: object) {
|
||||
const [signal, cancel] = timeoutSignal();
|
||||
const response = await fetch(this.url + url, {
|
||||
const response = await fetch(new URL(url, base_url), {
|
||||
method,
|
||||
headers: Object.assign({
|
||||
'Authorization': 'na ' + this.token,
|
||||
'User-Agent': getUserAgent(this.useragent),
|
||||
}, headers),
|
||||
headers,
|
||||
body,
|
||||
signal,
|
||||
}).finally(cancel);
|
||||
|
||||
debug('fetch %s %s, response %s', method, url, response.status);
|
||||
const debug_url = typeof url === 'string' ? '/' + url : url.toString();
|
||||
debug('fetch %s %s%s, response %s', method, debug_url, _log ? ', ' + _log : '', response.status);
|
||||
|
||||
if (response.status !== 200 && response.status !== 204) {
|
||||
throw new ErrorResponse('[zncproxy] Non-200/204 status code', response, await response.text());
|
||||
if (!response.ok) {
|
||||
throw await ZncProxyErrorResponse.fromResponse(response, '[zncproxy] Non-2xx status code');
|
||||
}
|
||||
|
||||
const data = (response.status === 204 ? {} : await response.json()) as T;
|
||||
|
|
@ -50,70 +59,138 @@ export default class ZncProxyApi implements CoralApi {
|
|||
return defineResponse(data, response);
|
||||
}
|
||||
|
||||
async call<T = unknown>(url: string, parameter = {}): Promise<Result<T>> {
|
||||
throw new Error('Not supported in ZncProxyApi');
|
||||
async call<T extends {}, R extends {}>(url: string, parameter: R & Partial<RequestFlags> = {} as R): Promise<Result<T>> {
|
||||
const options: [string, unknown][] = [];
|
||||
|
||||
if (parameter[RequestFlagAddPlatformSymbol]) options.push(['add_platform', true]);
|
||||
if (parameter[RequestFlagAddProductVersionSymbol]) options.push(['add_version', true]);
|
||||
if (parameter[RequestFlagNoParameterSymbol]) options.push(['no_parameter', true]);
|
||||
if (RequestFlagRequestIdSymbol in parameter) options.push(['request_id', parameter[RequestFlagRequestIdSymbol]]);
|
||||
|
||||
try {
|
||||
const result = await this.fetchProxyApi<{result: T}>('call', 'POST', JSON.stringify({
|
||||
url,
|
||||
parameter,
|
||||
|
||||
options: options.length ? Object.fromEntries(options) : undefined,
|
||||
}), undefined, 'call ' + url);
|
||||
|
||||
return createResult(result, result.result);
|
||||
} catch (err) {
|
||||
if (err instanceof ZncProxyErrorResponse &&
|
||||
err.response.status === 500 &&
|
||||
err.data && typeof err.data === 'object' &&
|
||||
'error' in err.data && err.data.error === 'unknown_error' &&
|
||||
'data' in err.data && err.data.data && typeof err.data.data === 'object' &&
|
||||
'status' in err.data.data && typeof err.data.data.status === 'number' &&
|
||||
'errorMessage' in err.data.data && typeof err.data.data.errorMessage === 'string' &&
|
||||
'correlationId' in err.data.data && typeof err.data.data.correlationId === 'string'
|
||||
) {
|
||||
const coral_err = new CoralErrorResponse('[znc] ' + err.data.data.errorMessage,
|
||||
err.response, err.data.data as CoralError);
|
||||
Object.defineProperty(coral_err, 'parent', {value: err});
|
||||
throw coral_err;
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async getAnnouncements() {
|
||||
const result = await this.fetch<{announcements: Announcements}>('/announcements');
|
||||
const result = await this.fetchProxyApi<{announcements: Announcements_4}>('announcements');
|
||||
return createResult(result, result.announcements);
|
||||
}
|
||||
|
||||
async getFriendList() {
|
||||
const result = await this.fetch<{friends: Friend[]}>('/friends');
|
||||
return createResult(result, result);
|
||||
const result = await this.fetchProxyApi<{friends: Friend_4[]; extract_ids?: string[]}>('friends');
|
||||
|
||||
return createResult(result, Object.assign(result, {
|
||||
extractFriendsIds: result.extract_ids ?? result.friends.slice(0, 10).map(f => f.nsaId),
|
||||
}));
|
||||
}
|
||||
|
||||
async addFavouriteFriend(nsaid: string) {
|
||||
const result = await this.fetch('/friend/' + nsaid, 'POST', JSON.stringify({
|
||||
async getFriend(nsa_id: string) {
|
||||
const result = await this.fetchProxyApi<{friend: Friend_4}>('friend/' + nsa_id);
|
||||
return createResult(result, result.friend);
|
||||
}
|
||||
|
||||
async addFavouriteFriend(nsa_id: string) {
|
||||
const result = await this.fetchProxyApi('friend/' + nsa_id, 'PATCH', JSON.stringify({
|
||||
isFavoriteFriend: true,
|
||||
}));
|
||||
return createResult(result, {});
|
||||
}
|
||||
|
||||
async removeFavouriteFriend(nsaid: string) {
|
||||
const result = await this.fetch('/friend/' + nsaid, 'POST', JSON.stringify({
|
||||
async removeFavouriteFriend(nsa_id: string) {
|
||||
const result = await this.fetchProxyApi('friend/' + nsa_id, 'PATCH', JSON.stringify({
|
||||
isFavoriteFriend: false,
|
||||
}));
|
||||
return createResult(result, {});
|
||||
}
|
||||
|
||||
async deleteFriendIsNew(nsa_id: string) {
|
||||
const result = await this.fetchProxyApi('friend/' + nsa_id, 'PATCH', JSON.stringify({
|
||||
isNew: false,
|
||||
}));
|
||||
return createResult(result, {});
|
||||
}
|
||||
|
||||
async getWebServices() {
|
||||
const result = await this.fetch<{webservices: WebService[]}>('/webservices');
|
||||
const result = await this.fetchProxyApi<{webservices: WebService_4[]}>('webservices');
|
||||
return createResult(result, result.webservices);
|
||||
}
|
||||
|
||||
async getChats() {
|
||||
const result = await this.fetchProxyApi<{chats: unknown[]}>('chats');
|
||||
return createResult(result, result.chats);
|
||||
}
|
||||
|
||||
async getMedia() {
|
||||
const result = await this.fetchProxyApi<{media: Media[]}>('media');
|
||||
return createResult(result, result);
|
||||
}
|
||||
|
||||
async getActiveEvent() {
|
||||
const result = await this.fetch<{activeevent: ActiveEvent}>('/activeevent');
|
||||
return createResult(result, result.activeevent);
|
||||
const result = await this.fetchProxyApi<{activeevent: ActiveEvent | null}>('activeevent');
|
||||
return createResult<GetActiveEventResult, typeof result>(result, result.activeevent ?? {});
|
||||
}
|
||||
|
||||
async getEvent(id: number) {
|
||||
const result = await this.fetch<{event: Event}>('/event/' + id);
|
||||
const result = await this.fetchProxyApi<{event: Event}>('event/' + id);
|
||||
return createResult(result, result.event);
|
||||
}
|
||||
|
||||
async getUser(id: number) {
|
||||
const result = await this.fetch<{user: User}>('/user/' + id);
|
||||
const result = await this.fetchProxyApi<{user: User}>('user/' + id);
|
||||
return createResult(result, result.user);
|
||||
}
|
||||
|
||||
async getUserByFriendCode(friend_code: string, hash?: string) {
|
||||
const result = await this.fetch<{user: FriendCodeUser}>('/friendcode/' + friend_code);
|
||||
const result = await this.fetchProxyApi<{user: FriendCodeUser}>('friendcode/' + friend_code);
|
||||
return createResult(result, result.user);
|
||||
}
|
||||
|
||||
async sendFriendRequest(nsa_id: string): Promise<Result<{}>> {
|
||||
throw new Error('Not supported in ZncProxyApi');
|
||||
}
|
||||
// async sendFriendRequest(nsa_id: string): Promise<Result<{}>> {
|
||||
// throw new Error('Not supported in ZncProxyApi');
|
||||
// }
|
||||
|
||||
async getCurrentUser() {
|
||||
const result = await this.fetch<{user: CurrentUser}>('/user');
|
||||
const result = await this.fetchProxyApi<{user: CurrentUser<true> | CurrentUser<false>}>('user');
|
||||
return createResult(result, result.user);
|
||||
}
|
||||
|
||||
async getReceivedFriendRequests() {
|
||||
const result = await this.fetchProxyApi<{friend_requests: ReceivedFriendRequest[]}>('friends/requests/received');
|
||||
return createResult(result, {friendRequests: result.friend_requests});
|
||||
}
|
||||
|
||||
async getSentFriendRequests() {
|
||||
const result = await this.fetchProxyApi<{friend_requests: SentFriendRequest[]}>('friends/requests/sent');
|
||||
return createResult(result, {friendRequests: result.friend_requests});
|
||||
}
|
||||
|
||||
async getFriendCodeUrl() {
|
||||
const result = await this.fetch<{friendcode: FriendCodeUrl}>('/friendcode');
|
||||
const result = await this.fetchProxyApi<{friendcode: FriendCodeUrl}>('friendcode');
|
||||
return createResult(result, result.friendcode);
|
||||
}
|
||||
|
||||
|
|
@ -126,35 +203,53 @@ export default class ZncProxyApi implements CoralApi {
|
|||
});
|
||||
}
|
||||
|
||||
async updateCurrentUserPermissions(
|
||||
to: PresencePermissions, from: PresencePermissions, etag: string
|
||||
): Promise<Result<{}>> {
|
||||
throw new Error('Not supported in ZncProxyApi');
|
||||
// async updateCurrentUserPermissions(
|
||||
// to: PresencePermissions, from: PresencePermissions, etag: string
|
||||
// ): Promise<Result<{}>> {
|
||||
// throw new Error('Not supported in ZncProxyApi');
|
||||
// }
|
||||
|
||||
async updateFriendOnlineNotificationSettings(nsa_id: string, value: boolean) {
|
||||
const result = await this.fetchProxyApi('friend/' + nsa_id, 'PATCH', JSON.stringify({
|
||||
isOnlineNotificationEnabled: value,
|
||||
}));
|
||||
return createResult(result, {});
|
||||
}
|
||||
|
||||
async getWebServiceToken(id: number) {
|
||||
const result = await this.fetch<{token: WebServiceToken}>('/webservice/' + id + '/token');
|
||||
const result = await this.fetchProxyApi<{token: WebServiceToken}>('webservice/' + id + '/token');
|
||||
return createResult(result, result.token);
|
||||
}
|
||||
|
||||
async getToken(token: string, user: NintendoAccountUser): ReturnType<CoralApi['getToken']> {
|
||||
async getToken(token: string, user: NintendoAccountUser): Promise<PartialCoralAuthData> {
|
||||
throw new Error('Not supported in ZncProxyApi');
|
||||
}
|
||||
|
||||
getTokenWithNintendoAccountToken(
|
||||
token: NintendoAccountToken, user: NintendoAccountUser,
|
||||
): Promise<PartialCoralAuthData> {
|
||||
throw new Error('Not supported in ZncProxyApi');
|
||||
}
|
||||
|
||||
async renewToken() {
|
||||
const data = await this.fetch<SavedToken>('/auth');
|
||||
data.proxy_url = this.url;
|
||||
const data = await this.fetchProxyApi<SavedToken>('auth');
|
||||
data.proxy_url = this.url.toString();
|
||||
return data;
|
||||
}
|
||||
|
||||
/** @private */
|
||||
setTokenWithSavedToken(data: CoralAuthData | PartialCoralAuthData) {
|
||||
renewTokenWithNintendoAccountToken(
|
||||
token: NintendoAccountToken, user: NintendoAccountUser,
|
||||
): Promise<PartialCoralAuthData> {
|
||||
throw new Error('Not supported in ZncProxyApi');
|
||||
}
|
||||
|
||||
protected setTokenWithSavedToken(data: CoralAuthData | PartialCoralAuthData) {
|
||||
throw new Error('Not supported in ZncProxyApi');
|
||||
}
|
||||
|
||||
static async createWithSessionToken(url: string, token: string) {
|
||||
const nso = new this(url, token);
|
||||
const data = await nso.fetch<SavedToken>('/auth');
|
||||
const data = await nso.fetchProxyApi<SavedToken>('auth');
|
||||
data.proxy_url = url;
|
||||
|
||||
return {nso, data};
|
||||
|
|
@ -169,6 +264,7 @@ function createResult<T extends {}, R>(data: R & {[ResponseSymbol]: Response}, r
|
|||
};
|
||||
|
||||
Object.defineProperty(result, ResponseSymbol, {enumerable: false, value: data[ResponseSymbol]});
|
||||
Object.defineProperty(result, ResponseEncryptionSymbol, {enumerable: false, value: null});
|
||||
Object.defineProperty(result, ResponseDataSymbol, {enumerable: false, value: coral_result});
|
||||
Object.defineProperty(result, CorrelationIdSymbol, {enumerable: false, value: ''});
|
||||
|
||||
|
|
@ -179,19 +275,26 @@ function createResult<T extends {}, R>(data: R & {[ResponseSymbol]: Response}, r
|
|||
return result as Result<T>;
|
||||
}
|
||||
|
||||
export class ZncProxyErrorResponse extends ErrorResponse {}
|
||||
|
||||
export interface AuthToken {
|
||||
user: string;
|
||||
policy?: AuthPolicy;
|
||||
created_at: number;
|
||||
}
|
||||
export interface AuthPolicy {
|
||||
api?: boolean;
|
||||
|
||||
announcements?: boolean;
|
||||
list_friends?: boolean;
|
||||
list_friends_presence?: boolean;
|
||||
friend?: boolean;
|
||||
friend_presence?: boolean;
|
||||
list_friend_requests?: boolean;
|
||||
webservices?: boolean;
|
||||
activeevent?: boolean;
|
||||
chats?: boolean;
|
||||
media?: boolean;
|
||||
current_user?: boolean;
|
||||
current_user_presence?: boolean;
|
||||
|
||||
|
|
@ -208,7 +311,8 @@ export enum ZncPresenceEventStreamEvent {
|
|||
}
|
||||
|
||||
export type PresenceUrlResponse =
|
||||
Presence | {presence: Presence} |
|
||||
PresenceOnline | PresenceOnline_4 | PresenceOffline |
|
||||
{presence: PresenceOnline | PresenceOnline_4 | PresenceOffline} |
|
||||
CurrentUser | {user: CurrentUser} |
|
||||
Friend | {friend: Friend};
|
||||
|
||||
|
|
@ -224,22 +328,22 @@ export async function getPresenceFromUrl(presence_url: string, useragent?: strin
|
|||
debug('fetch %s %s, response %s', 'GET', presence_url, response.status);
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw new ErrorResponse('[zncproxy] Unknown error', response, await response.text());
|
||||
throw await ZncProxyErrorResponse.fromResponse(response, '[zncproxy] Non-200 status code');
|
||||
}
|
||||
|
||||
if (!response.headers.get('Content-Type')?.match(/^application\/json(;|$)$/)) {
|
||||
controller.abort();
|
||||
throw new ErrorResponse('[zncproxy] Unacceptable content type', response);
|
||||
response.body?.cancel();
|
||||
throw new ZncProxyErrorResponse('[zncproxy] Unacceptable content type', response);
|
||||
}
|
||||
|
||||
const data = await response.json() as PresenceUrlResponse;
|
||||
|
||||
const user: CurrentUser | Friend | undefined =
|
||||
const user: CurrentUser<true> | CurrentUser<false> | Friend | Friend_4 | undefined =
|
||||
'user' in data ? data.user :
|
||||
'friend' in data ? data.friend :
|
||||
'nsaId' in data ? data :
|
||||
undefined;
|
||||
const presence: Presence =
|
||||
const presence: PresenceOnline | PresenceOnline_4 | PresenceOffline =
|
||||
'presence' in data ? data.presence :
|
||||
'user' in data ? data.user.presence :
|
||||
'friend' in data ? data.friend.presence :
|
||||
|
|
|
|||
|
|
@ -2,7 +2,11 @@ const electron = require('electron');
|
|||
|
||||
// Do anything that must be run before the app is ready...
|
||||
|
||||
electron.app.whenReady()
|
||||
Promise.all([
|
||||
// @ts-expect-error
|
||||
typeof __NXAPI_BUNDLE_APP_INIT__ !== 'undefined' ? import(__NXAPI_BUNDLE_APP_INIT__) : import('./app-init.js'),
|
||||
electron.app.whenReady(),
|
||||
])
|
||||
// @ts-expect-error
|
||||
.then(() => typeof __NXAPI_BUNDLE_APP_MAIN__ !== 'undefined' ? import(__NXAPI_BUNDLE_APP_MAIN__) : import('./main/index.js'))
|
||||
.then(m => m.init.call(null))
|
||||
|
|
|
|||
5
src/app/app-init.ts
Normal file
5
src/app/app-init.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import { join } from 'node:path';
|
||||
import { init as initDebug } from '../util/debug.js';
|
||||
import { paths } from '../util/product.js';
|
||||
|
||||
await initDebug(join(paths.log, 'app'));
|
||||
|
|
@ -1,67 +1,79 @@
|
|||
import React, { useCallback, useState } from 'react';
|
||||
import { StyleSheet, Text, TextInput, useColorScheme, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { StyleSheet, Text, TextInput, View } from 'react-native';
|
||||
import { Button } from '../components/index.js';
|
||||
import { DEFAULT_ACCENT_COLOUR, HIGHLIGHT_COLOUR_DARK, HIGHLIGHT_COLOUR_LIGHT, TEXT_COLOUR_DARK, TEXT_COLOUR_LIGHT } from '../constants.js';
|
||||
import ipc, { events } from '../ipc.js';
|
||||
import { Root, useEventListener } from '../util.js';
|
||||
import { Root, useAccentColour, useColourScheme, useEventListener } from '../util.js';
|
||||
|
||||
export interface AddAccountManualPromptProps {
|
||||
authoriseurl: string;
|
||||
client_id: string;
|
||||
}
|
||||
|
||||
export default function AddAccountManualPrompt(props: AddAccountManualPromptProps) {
|
||||
const colour_scheme = useColorScheme();
|
||||
const theme = colour_scheme === 'light' ? light : dark;
|
||||
|
||||
const [accent_colour, setAccentColour] = React.useState(() => ipc.getAccentColour());
|
||||
useEventListener(events, 'systemPreferences:accent-colour', setAccentColour, []);
|
||||
|
||||
export default function AddAccountManualPromptWindow(props: AddAccountManualPromptProps) {
|
||||
useEventListener(events, 'window:refresh', () => true, []);
|
||||
|
||||
const save = useCallback((callback_url: string) => {
|
||||
location.href = callback_url;
|
||||
}, []);
|
||||
|
||||
return <Root
|
||||
title={i18n => i18n.t('addaccountmanual_window:title')} scrollable autoresize
|
||||
i18nNamespace="addaccountmanual_window"
|
||||
>
|
||||
<AddAccountManualPrompt {...props} save={save} />
|
||||
</Root>
|
||||
}
|
||||
|
||||
function AddAccountManualPrompt(props: AddAccountManualPromptProps & {
|
||||
save?: (callback_url: string) => void;
|
||||
}) {
|
||||
const theme = useColourScheme() === 'light' ? light : dark;
|
||||
const accent_colour = useAccentColour();
|
||||
const { t, i18n } = useTranslation('addaccountmanual_window');
|
||||
|
||||
const [callback_url, setCallbackUrl] = useState('');
|
||||
const callback_url_valid = callback_url.startsWith('npf' + props.client_id + '://auth');
|
||||
|
||||
const save = useCallback(() => {
|
||||
if (callback_url_valid) {
|
||||
location.href = callback_url;
|
||||
props.save?.call(null, callback_url);
|
||||
}
|
||||
}, [callback_url, callback_url_valid]);
|
||||
}, [props.save, callback_url, callback_url_valid]);
|
||||
|
||||
return <Root title="Add account" scrollable autoresize>
|
||||
<View style={styles.main}>
|
||||
<Text style={theme.text}>1. Login to your Nintendo Account</Text>
|
||||
<Text style={[styles.help, theme.text]}>Do not select an account yet.</Text>
|
||||
return <View style={styles.main}>
|
||||
<Text style={theme.text}>{t('authorise_heading')}</Text>
|
||||
<Text style={[styles.help, theme.text]}>{t('authorise_help')}</Text>
|
||||
|
||||
<View style={styles.buttonSingle}>
|
||||
<Button title="Open Nintendo Account authorisation"
|
||||
onPress={() => ipc.openExternalUrl(props.authoriseurl)}
|
||||
<View style={styles.buttonSingle}>
|
||||
<Button title={t('authorise_open')}
|
||||
onPress={() => ipc.openExternalUrl(props.authoriseurl)}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
|
||||
</View>
|
||||
|
||||
<Text style={[styles.header, theme.text]}>{t('response_heading')}</Text>
|
||||
<Text style={[styles.help, theme.text]}>{t('response_help_1', {url: `npf${props.client_id}://auth`})}</Text>
|
||||
<Text style={[styles.help, theme.text]}>{t('response_help_2')}</Text>
|
||||
|
||||
<TextInput value={callback_url} onChangeText={setCallbackUrl}
|
||||
placeholder={'npf' + props.client_id + '://auth#...'}
|
||||
style={[styles.textInput, theme.textInput]} />
|
||||
|
||||
<View style={styles.buttons}>
|
||||
<View style={styles.button}>
|
||||
<Button title={t('cancel')}
|
||||
onPress={() => window.close()}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
|
||||
</View>
|
||||
|
||||
<Text style={[styles.header, theme.text]}>2. Enter the callback link</Text>
|
||||
<Text style={[styles.help, theme.text]}>On the "Linking an External Account" page, right click "Select this person" and copy the link. It should start with "npf{props.client_id}://auth".</Text>
|
||||
<Text style={[styles.help, theme.text]}>If you are adding a child account linked to your account, click "Select this person" next to their account to sign in as the child account, then with only the child account showing right click "Select this person" and copy the link.</Text>
|
||||
|
||||
<TextInput value={callback_url} onChangeText={setCallbackUrl}
|
||||
placeholder={'npf' + props.client_id + '://auth#...'}
|
||||
style={[styles.textInput, theme.textInput]} />
|
||||
|
||||
<View style={styles.buttons}>
|
||||
<View style={styles.button}>
|
||||
<Button title="Cancel"
|
||||
onPress={() => window.close()}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
|
||||
</View>
|
||||
{callback_url_valid ? <View style={styles.button}>
|
||||
<Button title="Add account"
|
||||
onPress={save}
|
||||
primary
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
|
||||
</View> : null}
|
||||
</View>
|
||||
{callback_url_valid ? <View style={styles.button}>
|
||||
<Button title={t('save')}
|
||||
onPress={save}
|
||||
primary
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
|
||||
</View> : null}
|
||||
</View>
|
||||
</Root>;
|
||||
</View>;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
import React, { useCallback, useEffect, useState } from 'react';
|
||||
import { ActivityIndicator, Image, NativeSyntheticEvent, StyleSheet, Text, TextInput, TextInputChangeEventData, TextInputKeyPressEventData, TouchableOpacity, useColorScheme, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ActivityIndicator, Image, NativeSyntheticEvent, StyleSheet, Text, TextInput, TextInputChangeEventData, TextInputKeyPressEventData, TouchableOpacity, View } from 'react-native';
|
||||
import { Friend, FriendCodeUser } from '../../../api/coral-types.js';
|
||||
import { SavedToken } from '../../../common/auth/coral.js';
|
||||
import Warning from '../components/icons/warning.js';
|
||||
import { Button } from '../components/index.js';
|
||||
import { DEFAULT_ACCENT_COLOUR, HIGHLIGHT_COLOUR_DARK, HIGHLIGHT_COLOUR_LIGHT, TEXT_COLOUR_DARK, TEXT_COLOUR_LIGHT } from '../constants.js';
|
||||
import ipc, { events } from '../ipc.js';
|
||||
import { RequestState, Root, useAsync, useEventListener } from '../util.js';
|
||||
import ipc from '../ipc.js';
|
||||
import { RequestState, Root, useAccentColour, useAsync, useColourScheme } from '../util.js';
|
||||
|
||||
export interface AddFriendProps {
|
||||
user: string;
|
||||
|
|
@ -27,36 +29,22 @@ type SendFriendRequestStateArray =
|
|||
const FRIEND_CODE = /^\d{4}-\d{4}-\d{4}$/;
|
||||
const FRIEND_CODE_URL = /^(?!https\:\/\/lounge\.nintendo\.com\/|com\.nintendo\.znca\:\/\/znca\/)friendcode\/(\d{4}-\d{4}-\d{4})\//;
|
||||
|
||||
export default function AddFriend(props: AddFriendProps) {
|
||||
const colour_scheme = useColorScheme();
|
||||
const theme = colour_scheme === 'light' ? light : dark;
|
||||
|
||||
const [accent_colour, setAccentColour] = React.useState(() => ipc.getAccentColour());
|
||||
useEventListener(events, 'systemPreferences:accent-colour', setAccentColour, []);
|
||||
export default function AddFriendWindow(props: AddFriendProps) {
|
||||
const accent_colour = useAccentColour();
|
||||
|
||||
const [token] = useAsync(useCallback(() => ipc.getNintendoAccountCoralToken(props.user), [ipc, props.user]));
|
||||
const [user] = useAsync(useCallback(() => token ?
|
||||
ipc.getSavedCoralToken(token) : Promise.resolve(null), [ipc, token]));
|
||||
|
||||
const [fr_received, fr_received_error, fr_received_state] = useAsync(useCallback(() => token ?
|
||||
ipc.getNsoReceivedFriendRequests(token) : Promise.resolve(null), [ipc, token]));
|
||||
const [fr_sent, fr_sent_error, fr_sent_state] = useAsync(useCallback(() => token ?
|
||||
ipc.getNsoSentFriendRequests(token) : Promise.resolve(null), [ipc, token]));
|
||||
|
||||
const [friendcode, setFriendCode] = useState(props.friendcode ?? '');
|
||||
const is_valid_friendcode = FRIEND_CODE.test(friendcode);
|
||||
const show_friendcode_field = !props.friendcode || !FRIEND_CODE.test(props.friendcode);
|
||||
|
||||
const onChangeFriendCode = useCallback((event: NativeSyntheticEvent<TextInputChangeEventData>) => {
|
||||
let match;
|
||||
if (match = event.nativeEvent.text.match(FRIEND_CODE_URL)) {
|
||||
setFriendCode(match[1]);
|
||||
} else {
|
||||
const friendcode = event.nativeEvent.text
|
||||
.replace(/[^0-9]/g, '')
|
||||
.replace(/^([0-9]{4})/g, '$1-')
|
||||
.replace(/^([0-9]{4}-[0-9]{4})/g, '$1-')
|
||||
.substr(0, 14);
|
||||
|
||||
setFriendCode(friendcode);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const [target_user, lookup_error, lookup_state] = useAsync(useCallback(() => token && is_valid_friendcode ?
|
||||
ipc.getNsoUserByFriendCode(token, friendcode) : Promise.resolve(null),
|
||||
[ipc, token, friendcode, is_valid_friendcode]));
|
||||
|
|
@ -65,25 +53,85 @@ export default function AddFriend(props: AddFriendProps) {
|
|||
ipc.getNsoFriends(token) : Promise.resolve(null), [ipc, token]));
|
||||
const friend = friends?.find(f => f.nsaId === target_user?.nsaId);
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (event: KeyboardEvent) => event.key === 'Escape' && window.close();
|
||||
window.addEventListener('keydown', handler);
|
||||
return () => window.removeEventListener('keydown', handler);
|
||||
}, []);
|
||||
|
||||
if (!user || !token || (!show_friendcode_field && lookup_state === RequestState.LOADING)) {
|
||||
return <Root
|
||||
title={i18n => i18n.t('addfriend_window:title')} titleUser={user ?? undefined} autoresize={!!user}
|
||||
i18nNamespace="addfriend_window"
|
||||
>
|
||||
<View style={styles.loading}>
|
||||
<ActivityIndicator size="large" color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
|
||||
</View>
|
||||
</Root>;
|
||||
}
|
||||
|
||||
return <Root
|
||||
title={i18n => i18n.t('addfriend_window:title')} titleUser={user} autoresize
|
||||
i18nNamespace="addfriend_window"
|
||||
>
|
||||
<AddFriend
|
||||
user={user} token={token}
|
||||
friendcode={friendcode} setFriendCode={show_friendcode_field ? setFriendCode : undefined}
|
||||
lookupState={lookup_state} lookupUser={target_user} lookupError={lookup_error}
|
||||
friendsState={friends_state} lookupFriend={friend}
|
||||
/>
|
||||
</Root>;
|
||||
}
|
||||
|
||||
function AddFriend(props: {
|
||||
user: SavedToken;
|
||||
token: string;
|
||||
friendcode: string;
|
||||
setFriendCode?: (friendcode: string) => void;
|
||||
lookupState: RequestState;
|
||||
lookupUser: FriendCodeUser | null;
|
||||
lookupError: Error | null;
|
||||
friendsState: RequestState;
|
||||
lookupFriend?: Friend;
|
||||
}) {
|
||||
const theme = useColourScheme() === 'light' ? light : dark;
|
||||
const accent_colour = useAccentColour();
|
||||
const { t, i18n } = useTranslation('addfriend_window');
|
||||
|
||||
const onChangeFriendCode = useCallback((event: NativeSyntheticEvent<TextInputChangeEventData>) => {
|
||||
let match;
|
||||
if (match = event.nativeEvent.text.match(FRIEND_CODE_URL)) {
|
||||
props.setFriendCode?.(match[1]);
|
||||
} else {
|
||||
const friendcode = event.nativeEvent.text
|
||||
.replace(/[^0-9]/g, '')
|
||||
.replace(/^([0-9]{4})/g, '$1-')
|
||||
.replace(/^([0-9]{4}-[0-9]{4})/g, '$1-')
|
||||
.substr(0, 14);
|
||||
|
||||
props.setFriendCode?.(friendcode);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const showLookupErrorDetails = useCallback(() => {
|
||||
alert(lookup_error);
|
||||
}, [lookup_error]);
|
||||
alert(props.lookupError);
|
||||
}, [props.lookupError]);
|
||||
|
||||
const [send_state, setSendFriendRequestState] = useState<SendFriendRequestStateArray>([SendFriendRequestState.NOT_LOADING]);
|
||||
|
||||
const sendFriendRequest = useCallback(async () => {
|
||||
if (send_state[0] === SendFriendRequestState.SENDING) return;
|
||||
if (!token || !target_user) return;
|
||||
setSendFriendRequestState([SendFriendRequestState.SENDING, target_user, friendcode]);
|
||||
if (!props.lookupUser) return;
|
||||
setSendFriendRequestState([SendFriendRequestState.SENDING, props.lookupUser, props.friendcode]);
|
||||
|
||||
try {
|
||||
const {result, friend} = await ipc.addNsoFriend(token, target_user.nsaId);
|
||||
const {result, friend} = await ipc.addNsoFriend(props.token, props.lookupUser.nsaId);
|
||||
|
||||
setSendFriendRequestState([SendFriendRequestState.SENT, target_user, friendcode, friend]);
|
||||
setSendFriendRequestState([SendFriendRequestState.SENT, props.lookupUser, props.friendcode, friend]);
|
||||
} catch (err) {
|
||||
setSendFriendRequestState([SendFriendRequestState.ERROR, target_user, friendcode, err as Error]);
|
||||
setSendFriendRequestState([SendFriendRequestState.ERROR, props.lookupUser, props.friendcode, err as Error]);
|
||||
}
|
||||
}, [token, target_user, friendcode, send_state]);
|
||||
}, [props.token, props.lookupUser, props.friendcode, send_state]);
|
||||
|
||||
const showSendFriendRequestErrorDetails = useCallback(() => {
|
||||
if (send_state[0] !== SendFriendRequestState.ERROR) return;
|
||||
|
|
@ -93,100 +141,86 @@ export default function AddFriend(props: AddFriendProps) {
|
|||
const onFriendCodeKeyPress = useCallback((event: NativeSyntheticEvent<TextInputKeyPressEventData>) =>
|
||||
event.nativeEvent.key === 'Escape' && window.close(), []);
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (event: KeyboardEvent) => event.key === 'Escape' && window.close();
|
||||
window.addEventListener('keydown', handler);
|
||||
return () => window.removeEventListener('keydown', handler);
|
||||
}, []);
|
||||
return <View style={styles.main}>
|
||||
{props.setFriendCode ? <>
|
||||
<Text style={theme.text}>{t('title')}</Text>
|
||||
|
||||
if (!user || (!show_friendcode_field && lookup_state === RequestState.LOADING)) {
|
||||
return <Root title="Add friend" titleUser={user ?? undefined} autoresize={!!user}>
|
||||
<View style={styles.loading}>
|
||||
<ActivityIndicator size="large" color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
|
||||
<Text style={[styles.help, theme.text]}>{t('help')}</Text>
|
||||
|
||||
<View style={styles.friendCodeInputContainer}>
|
||||
<TextInput value={props.friendcode} onChange={onChangeFriendCode}
|
||||
onKeyPress={onFriendCodeKeyPress}
|
||||
placeholder="0000-0000-0000"
|
||||
style={[styles.textInput, styles.friendCodeInput, theme.textInput]} />
|
||||
|
||||
{props.lookupState === RequestState.LOADING ?
|
||||
<ActivityIndicator style={styles.activityIndicator} size={20} color={'#' + accent_colour} /> :
|
||||
props.lookupError ? <TouchableOpacity onPress={showLookupErrorDetails} style={styles.iconTouchable}>
|
||||
<Text style={[styles.icon, {color: '#' + accent_colour}]}><Warning /></Text>
|
||||
</TouchableOpacity> : null}
|
||||
</View>
|
||||
</Root>;
|
||||
}
|
||||
</> : props.lookupError ? <TouchableOpacity onPress={showLookupErrorDetails}>
|
||||
<Text style={[styles.lookupErrorNoFriendCodeField, theme.text]}>
|
||||
<Text style={[styles.lookupErrorIcon, {color: '#' + accent_colour}]}><Warning /></Text>
|
||||
{t('lookup_error', {message: props.lookupError.name + ' ' + props.lookupError.message})}
|
||||
</Text>
|
||||
</TouchableOpacity> : null}
|
||||
|
||||
return <Root title="Add friend" titleUser={user} scrollable autoresize>
|
||||
<View style={styles.main}>
|
||||
{show_friendcode_field ? <>
|
||||
<Text style={theme.text}>Add friend</Text>
|
||||
{props.lookupUser ? <View style={[
|
||||
styles.targetUser,
|
||||
!props.setFriendCode ? styles.targetUserNoFriendCodeField : null,
|
||||
theme.targetUser,
|
||||
]}>
|
||||
<Image source={{uri: props.lookupUser.image2Uri, width: 100, height: 100}} style={styles.targetUserImage} />
|
||||
|
||||
<Text style={[styles.help, theme.text]}>Type or paste a friend code or friend code URL to send a friend request.</Text>
|
||||
<View style={styles.targetUserDetail}>
|
||||
<Text style={[styles.targetUserName, theme.text]}>{props.lookupUser.name}</Text>
|
||||
|
||||
<View style={styles.friendCodeInputContainer}>
|
||||
<TextInput value={friendcode} onChange={onChangeFriendCode}
|
||||
onKeyPress={onFriendCodeKeyPress}
|
||||
placeholder="0000-0000-0000"
|
||||
style={[styles.textInput, styles.friendCodeInput, theme.textInput]} />
|
||||
|
||||
{lookup_state === RequestState.LOADING ?
|
||||
<ActivityIndicator style={styles.activityIndicator} size={20} color={'#' + accent_colour} /> :
|
||||
lookup_error ? <TouchableOpacity onPress={showLookupErrorDetails} style={styles.iconTouchable}>
|
||||
<Text style={[styles.icon, {color: '#' + accent_colour}]}><Warning /></Text>
|
||||
</TouchableOpacity> : null}
|
||||
</View>
|
||||
</> : lookup_error ? <TouchableOpacity onPress={showLookupErrorDetails}>
|
||||
<Text style={[styles.lookupErrorNoFriendCodeField, theme.text]}>
|
||||
<Text style={[styles.lookupErrorIcon, {color: '#' + accent_colour}]}><Warning /></Text>
|
||||
Error looking up friend code: {lookup_error.name} {lookup_error.message}
|
||||
<Text style={[styles.targetUserNsaId, theme.text]}>
|
||||
{t('nsa_id')}: <Text style={styles.targetUserNsaIdValue}>{props.lookupUser.nsaId}</Text>
|
||||
</Text>
|
||||
</TouchableOpacity> : null}
|
||||
<Text style={[styles.targetUserCoralId, theme.text]}>{props.lookupUser.id ? <>
|
||||
{t('coral_id')}: <Text style={styles.targetUserCoralIdValue}>{props.lookupUser.id}</Text>
|
||||
</> : t('no_coral_user')}</Text>
|
||||
|
||||
{target_user ? <View style={[
|
||||
styles.targetUser,
|
||||
!show_friendcode_field ? styles.targetUserNoFriendCodeField : null,
|
||||
theme.targetUser,
|
||||
]}>
|
||||
<Image source={{uri: target_user.imageUri, width: 100, height: 100}} style={styles.targetUserImage} />
|
||||
|
||||
<View style={styles.targetUserDetail}>
|
||||
<Text style={[styles.targetUserName, theme.text]}>{target_user.name}</Text>
|
||||
|
||||
<Text style={[styles.targetUserNsaId, theme.text]}>NSA ID: <Text style={styles.targetUserNsaIdValue}>{target_user.nsaId}</Text></Text>
|
||||
<Text style={[styles.targetUserCoralId, theme.text]}>{target_user.id ? <>
|
||||
Coral user ID: <Text style={styles.targetUserCoralIdValue}>{target_user.id}</Text>
|
||||
</> : 'Never used Nintendo Switch Online app'}</Text>
|
||||
|
||||
{send_state[0] === SendFriendRequestState.SENT && send_state[3] ?
|
||||
<Text style={[styles.friendRequestState, theme.text]}>You are now friends with this user.</Text> :
|
||||
send_state[0] === SendFriendRequestState.SENT ?
|
||||
<Text style={[styles.friendRequestState, theme.text]}>Friend request sent. {target_user.name} can accept your friend request using a Nintendo Switch console, or by sending you a friend request using the Nintendo Switch Online app or nxapi.</Text> :
|
||||
send_state[0] === SendFriendRequestState.SENDING ?
|
||||
{send_state[0] === SendFriendRequestState.SENT && send_state[3] ?
|
||||
<Text style={[styles.friendRequestState, theme.text]}>{t('send_added')}</Text> :
|
||||
send_state[0] === SendFriendRequestState.SENT ?
|
||||
<Text style={[styles.friendRequestState, theme.text]}>{t('send_sent', {user: props.lookupUser.name})}</Text> :
|
||||
send_state[0] === SendFriendRequestState.SENDING ?
|
||||
<Text style={[styles.friendRequestState, theme.text]}>
|
||||
<ActivityIndicator style={styles.friendRequestActivityIndicator} color={'#' + accent_colour} />
|
||||
{t('send_sending')}
|
||||
</Text> :
|
||||
send_state[0] === SendFriendRequestState.ERROR ?
|
||||
<TouchableOpacity onPress={showSendFriendRequestErrorDetails}>
|
||||
<Text style={[styles.friendRequestState, theme.text]}>
|
||||
<ActivityIndicator style={styles.friendRequestActivityIndicator} color={'#' + accent_colour} />
|
||||
Sending friend request...
|
||||
</Text> :
|
||||
send_state[0] === SendFriendRequestState.ERROR ?
|
||||
<TouchableOpacity onPress={showSendFriendRequestErrorDetails}>
|
||||
<Text style={[styles.friendRequestState, theme.text]}>
|
||||
<Text style={[styles.friendRequestStateIcon, {color: '#' + accent_colour}]}><Warning /></Text>
|
||||
Error sending friend request: {send_state[3].name} {send_state[3].message}
|
||||
</Text>
|
||||
</TouchableOpacity> :
|
||||
friend ?
|
||||
<Text style={[styles.friendRequestState, theme.text]}>You are already friends with this user.</Text> : null}
|
||||
</View>
|
||||
</View> : null}
|
||||
|
||||
<View style={styles.buttons}>
|
||||
<View style={styles.button}>
|
||||
<Button title="Close"
|
||||
onPress={() => window.close()}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
|
||||
</View>
|
||||
|
||||
{lookup_state === RequestState.LOADED && target_user &&
|
||||
friends_state === RequestState.LOADED && !friend &&
|
||||
target_user?.nsaId !== user.nsoAccount.user.nsaId ? <View style={styles.button}>
|
||||
<Button title="Send friend request"
|
||||
onPress={sendFriendRequest}
|
||||
primary
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
|
||||
</View> : null}
|
||||
<Text style={[styles.friendRequestStateIcon, {color: '#' + accent_colour}]}><Warning /></Text>
|
||||
{t('send_error', {message: send_state[3].name + ' ' + send_state[3].message})}
|
||||
</Text>
|
||||
</TouchableOpacity> :
|
||||
props.lookupFriend ?
|
||||
<Text style={[styles.friendRequestState, theme.text]}>{t('already_friends')}</Text> : null}
|
||||
</View>
|
||||
</View> : null}
|
||||
|
||||
<View style={styles.buttons}>
|
||||
<View style={styles.button}>
|
||||
<Button title={t('close')}
|
||||
onPress={() => window.close()}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
|
||||
</View>
|
||||
|
||||
{props.lookupState === RequestState.LOADED && props.lookupUser &&
|
||||
props.friendsState === RequestState.LOADED && !props.lookupFriend &&
|
||||
props.lookupUser?.nsaId !== props.user.nsoAccount.user.nsaId ? <View style={styles.button}>
|
||||
<Button title={t('send')}
|
||||
onPress={sendFriendRequest}
|
||||
primary
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
|
||||
</View> : null}
|
||||
</View>
|
||||
</Root>;
|
||||
</View>;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
|
|
|
|||
|
|
@ -56,6 +56,7 @@ function ButtonMac(props: {
|
|||
|
||||
const styles_mac = StyleSheet.create({
|
||||
button: {
|
||||
// @ts-expect-error react-native-web
|
||||
cursor: 'default',
|
||||
lineHeight: 19,
|
||||
borderRadius: 3,
|
||||
|
|
@ -76,10 +77,12 @@ const styles_mac = StyleSheet.create({
|
|||
},
|
||||
innerActive: {
|
||||
backgroundColor: 'transparent',
|
||||
// @ts-expect-error react-native-web
|
||||
backgroundImage: 'linear-gradient(0deg, #00000050, #00000040)',
|
||||
},
|
||||
innerPressed: {
|
||||
backgroundColor: 'transparent',
|
||||
// @ts-expect-error react-native-web
|
||||
backgroundImage: 'linear-gradient(0deg, #00000040, #00000020)',
|
||||
},
|
||||
|
||||
|
|
|
|||
32
src/app/browser/components/friend-code.tsx
Normal file
32
src/app/browser/components/friend-code.tsx
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import React, { useCallback, useMemo } from 'react';
|
||||
import { StyleSheet, Text } from 'react-native';
|
||||
import { CurrentUserFriendCodeLink } from '../../../api/coral-types.js';
|
||||
import ipc from '../ipc.js';
|
||||
|
||||
export default function FriendCode(props: {
|
||||
friendcode: CurrentUserFriendCodeLink;
|
||||
} | {
|
||||
id: string;
|
||||
}) {
|
||||
const friendcode = useMemo(() => 'friendcode' in props ? props.friendcode : {
|
||||
id: props.id,
|
||||
regenerable: false,
|
||||
regenerableAt: 0,
|
||||
}, ['friendcode' in props ? props.friendcode : null, 'id' in props ? props.id : null]);
|
||||
|
||||
const onFriendCodeContextMenu = useCallback(() => {
|
||||
ipc.showFriendCodeMenu(friendcode);
|
||||
}, [ipc, friendcode]);
|
||||
|
||||
return <Text
|
||||
style={styles.friendCodeValue}
|
||||
// @ts-expect-error react-native-web
|
||||
onContextMenu={onFriendCodeContextMenu}
|
||||
>SW-{friendcode.id}</Text>;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
friendCodeValue: {
|
||||
userSelect: 'all',
|
||||
},
|
||||
});
|
||||
|
|
@ -2,8 +2,13 @@ import React from 'react';
|
|||
import { Platform, Text } from 'react-native';
|
||||
import { svg_styles } from './util.js';
|
||||
|
||||
const IconWeb = React.memo(() => <Text>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" style={svg_styles}><title>Add</title><path fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="32" d="M256 112v288M400 256H112"/></svg>
|
||||
const IconWeb = React.memo((props: {
|
||||
title?: string;
|
||||
}) => <Text>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" style={svg_styles}>
|
||||
{props.title ? <title>{props.title}</title> : null}
|
||||
<path fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="32" d="M256 112v288M400 256H112"/>
|
||||
</svg>
|
||||
</Text>);
|
||||
|
||||
export default Platform.OS === 'web' ? IconWeb : React.memo(() => null);
|
||||
|
|
|
|||
|
|
@ -2,8 +2,13 @@ import React from 'react';
|
|||
import { Platform, Text } from 'react-native';
|
||||
import { svg_styles } from './util.js';
|
||||
|
||||
const IconWeb = React.memo(() => <Text>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512" style={svg_styles}><title>ionicons-v5-r</title><path d="M449.07,399.08,278.64,82.58c-12.08-22.44-44.26-22.44-56.35,0L51.87,399.08A32,32,0,0,0,80,446.25H420.89A32,32,0,0,0,449.07,399.08Zm-198.6-1.83a20,20,0,1,1,20-20A20,20,0,0,1,250.47,397.25ZM272.19,196.1l-5.74,122a16,16,0,0,1-32,0l-5.74-121.95v0a21.73,21.73,0,0,1,21.5-22.69h.21a21.74,21.74,0,0,1,21.73,22.7Z"/></svg>
|
||||
const IconWeb = React.memo((props: {
|
||||
title?: string;
|
||||
}) => <Text>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512" style={svg_styles}>
|
||||
{props.title ? <title>{props.title}</title> : null}
|
||||
<path d="M449.07,399.08,278.64,82.58c-12.08-22.44-44.26-22.44-56.35,0L51.87,399.08A32,32,0,0,0,80,446.25H420.89A32,32,0,0,0,449.07,399.08Zm-198.6-1.83a20,20,0,1,1,20-20A20,20,0,0,1,250.47,397.25ZM272.19,196.1l-5.74,122a16,16,0,0,1-32,0l-5.74-121.95v0a21.73,21.73,0,0,1,21.5-22.69h.21a21.74,21.74,0,0,1,21.73,22.7Z"/>
|
||||
</svg>
|
||||
</Text>);
|
||||
|
||||
export default Platform.OS === 'web' ? IconWeb : React.memo(() => null);
|
||||
|
|
|
|||
|
|
@ -1 +1,4 @@
|
|||
export { default as Button } from './button.js';
|
||||
export { default as NintendoSwitchUser } from './nintendo-switch-user.js';
|
||||
export { NintendoSwitchUsers } from './nintendo-switch-user.js';
|
||||
export { default as FriendCode } from './friend-code.js';
|
||||
|
|
|
|||
40
src/app/browser/components/nintendo-switch-user.tsx
Normal file
40
src/app/browser/components/nintendo-switch-user.tsx
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import React from 'react';
|
||||
import { Image, StyleSheet } from 'react-native';
|
||||
import { CurrentUser, Friend } from '../../../api/coral-types.js';
|
||||
|
||||
export default function NintendoSwitchUser(props: {
|
||||
friend: Friend;
|
||||
nickname?: string;
|
||||
} | {
|
||||
user: CurrentUser<true> | CurrentUser<false>;
|
||||
nickname?: string;
|
||||
}) {
|
||||
const user = 'friend' in props ? props.friend : props.user;
|
||||
|
||||
return <>
|
||||
<Image source={{uri: user.image2Uri, width: 16, height: 16}}
|
||||
style={styles.userImage} />
|
||||
{' '}
|
||||
{user.name}
|
||||
{props.nickname && user.name !== props.nickname ? ' (' + props.nickname + ')' : ''}
|
||||
</>;
|
||||
}
|
||||
|
||||
export function NintendoSwitchUsers(props: {
|
||||
users: Parameters<typeof NintendoSwitchUser>[0][];
|
||||
}) {
|
||||
return <>
|
||||
{props.users.map((u, i) => <React.Fragment key={'friend' in u ? u.friend.nsaId : u.user.nsaId}>
|
||||
{i === 0 ? '' : ', '}
|
||||
<NintendoSwitchUser {...u} />
|
||||
</React.Fragment>)}
|
||||
</>;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
userImage: {
|
||||
borderRadius: 8,
|
||||
// @ts-expect-error react-native-web
|
||||
verticalAlign: -3 as 'auto',
|
||||
},
|
||||
});
|
||||
|
|
@ -1,10 +1,12 @@
|
|||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { StyleSheet, Text, TextInput, useColorScheme, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { StyleSheet, Text, TextInput, View } from 'react-native';
|
||||
import { Picker } from 'react-native-web';
|
||||
import { DiscordPresenceSource } from '../../common/types.js';
|
||||
import { Button } from '../components/index.js';
|
||||
import { DEFAULT_ACCENT_COLOUR, HIGHLIGHT_COLOUR_DARK, HIGHLIGHT_COLOUR_LIGHT, TEXT_COLOUR_DARK, TEXT_COLOUR_LIGHT } from '../constants.js';
|
||||
import ipc, { events } from '../ipc.js';
|
||||
import { getAccounts, RequestState, Root, useAsync, useDiscordPresenceSource, useEventListener } from '../util.js';
|
||||
import { getAccounts, RequestState, Root, useAccentColour, useAsync, useColourScheme, useDiscordPresenceSource, useEventListener, User } from '../util.js';
|
||||
|
||||
export interface DiscordSetupProps {
|
||||
users?: string[];
|
||||
|
|
@ -19,39 +21,68 @@ enum DiscordSourceType {
|
|||
NONE,
|
||||
}
|
||||
|
||||
export default function DiscordSetup(props: DiscordSetupProps) {
|
||||
const colour_scheme = useColorScheme();
|
||||
const theme = colour_scheme === 'light' ? light : dark;
|
||||
|
||||
const [accent_colour, setAccentColour] = React.useState(() => ipc.getAccentColour());
|
||||
useEventListener(events, 'systemPreferences:accent-colour', setAccentColour, []);
|
||||
|
||||
export default function DiscordSetupWindow(props: DiscordSetupProps) {
|
||||
const [users, ,, forceRefreshAccounts] = useAsync(useCallback(() => getAccounts(), [ipc]));
|
||||
useEventListener(events, 'update-nintendo-accounts', forceRefreshAccounts, []);
|
||||
useEventListener(events, 'window:refresh', () => forceRefreshAccounts(), []);
|
||||
|
||||
const [discord_presence_source, discord_presence_source_state] = useDiscordPresenceSource();
|
||||
|
||||
const [selectedMode, setSelectedMode] = useState(props.users?.length && props.friend_nsa_id ?
|
||||
useEffect(() => {
|
||||
const handler = (event: KeyboardEvent) => event.key === 'Escape' && window.close();
|
||||
window.addEventListener('keydown', handler);
|
||||
return () => window.removeEventListener('keydown', handler);
|
||||
}, []);
|
||||
|
||||
if (!users || discord_presence_source_state !== RequestState.LOADED) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <Root
|
||||
title={i18n => i18n.t('discordsetup_window:title')} scrollable autoresize
|
||||
i18nNamespace="discordsetup_window"
|
||||
>
|
||||
<DiscordSetup
|
||||
users={users} showUsers={props.users}
|
||||
friendNsaId={props.friend_nsa_id}
|
||||
discordPresenceSource={discord_presence_source}
|
||||
showPreferencesButton={props.show_preferences_button}
|
||||
/>
|
||||
</Root>;
|
||||
}
|
||||
|
||||
function DiscordSetup(props: {
|
||||
users: User[];
|
||||
showUsers?: string[];
|
||||
friendNsaId?: string;
|
||||
discordPresenceSource: DiscordPresenceSource | null;
|
||||
showPreferencesButton?: boolean;
|
||||
}) {
|
||||
const theme = useColourScheme() === 'light' ? light : dark;
|
||||
const accent_colour = useAccentColour();
|
||||
const { t, i18n } = useTranslation('discordsetup_window');
|
||||
|
||||
const [selectedMode, setSelectedMode] = useState(props.users?.length && props.friendNsaId ?
|
||||
DiscordSourceType.CORAL : DiscordSourceType.NONE);
|
||||
const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
|
||||
const [selectedFriendNsaId, setSelectedFriendNsaId] = useState<string | null>(props.friend_nsa_id ?? null);
|
||||
const [selectedFriendNsaId, setSelectedFriendNsaId] = useState<string | null>(props.friendNsaId ?? null);
|
||||
const [presenceUrl, setPresenceUrl] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (!discord_presence_source) {
|
||||
setSelectedMode(props.friend_nsa_id ? DiscordSourceType.CORAL : DiscordSourceType.NONE);
|
||||
} else if ('na_id' in discord_presence_source) {
|
||||
if (!props.discordPresenceSource) {
|
||||
setSelectedMode(props.friendNsaId ? DiscordSourceType.CORAL : DiscordSourceType.NONE);
|
||||
} else if ('na_id' in props.discordPresenceSource) {
|
||||
setSelectedMode(DiscordSourceType.CORAL);
|
||||
setSelectedUserId(discord_presence_source.na_id);
|
||||
setSelectedFriendNsaId(discord_presence_source.friend_nsa_id ?? null);
|
||||
} else if ('url' in discord_presence_source) {
|
||||
setSelectedUserId(props.discordPresenceSource.na_id);
|
||||
setSelectedFriendNsaId(props.discordPresenceSource.friend_nsa_id ?? null);
|
||||
} else if ('url' in props.discordPresenceSource) {
|
||||
setSelectedMode(DiscordSourceType.URL);
|
||||
setPresenceUrl(discord_presence_source.url);
|
||||
setPresenceUrl(props.discordPresenceSource.url);
|
||||
}
|
||||
}, [discord_presence_source]);
|
||||
}, [props.discordPresenceSource]);
|
||||
|
||||
const user = useMemo(() => selectedUserId ? users?.find(u => u.user.id === selectedUserId) : undefined,
|
||||
[selectedUserId, users]);
|
||||
const user = useMemo(() => selectedUserId ? props.users?.find(u => u.user.id === selectedUserId) : undefined,
|
||||
[selectedUserId, props.users]);
|
||||
const [friends, , friends_state, forceRefreshFriends] = useAsync(useCallback(() => user?.nsotoken ?
|
||||
ipc.getNsoFriends(user.nsotoken) : Promise.resolve(null), [ipc, user?.nsotoken]));
|
||||
const friends_with_presence = useMemo(() => friends?.filter(f => f.presence.updatedAt ||
|
||||
|
|
@ -59,10 +90,11 @@ export default function DiscordSetup(props: DiscordSetupProps) {
|
|||
const friend = useMemo(() => selectedFriendNsaId ? friends?.find(f => f.nsaId === selectedFriendNsaId) : undefined,
|
||||
[selectedFriendNsaId, friends]);
|
||||
|
||||
const filtered_users = useMemo(() => users?.filter(u => selectedUserId === u.user.id ||
|
||||
(u.nso && (!props.users || props.users.includes(u.user.id)))), [users, props.users, selectedUserId]);
|
||||
const filtered_users = useMemo(() => props.users.filter(u => selectedUserId === u.user.id ||
|
||||
(u.nso && (!props.showUsers || props.showUsers.includes(u.user.id)))),
|
||||
[props.users, props.showUsers, selectedUserId]);
|
||||
|
||||
useEventListener(events, 'window:refresh', () => (forceRefreshAccounts(), forceRefreshFriends()), []);
|
||||
useEventListener(events, 'window:refresh', () => forceRefreshFriends(), []);
|
||||
|
||||
useEffect(() => {
|
||||
if (filtered_users?.length && !user) setSelectedUserId(filtered_users[0].user.id);
|
||||
|
|
@ -87,103 +119,89 @@ export default function DiscordSetup(props: DiscordSetupProps) {
|
|||
window.close();
|
||||
}, [selectedMode, selectedUserId, selectedFriendNsaId, presenceUrl]);
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (event: KeyboardEvent) => event.key === 'Escape' && window.close();
|
||||
window.addEventListener('keydown', handler);
|
||||
return () => window.removeEventListener('keydown', handler);
|
||||
}, []);
|
||||
return <View style={styles.main}>
|
||||
<Text style={theme.text}>{t('title')}</Text>
|
||||
|
||||
if (!users || discord_presence_source_state !== RequestState.LOADED) {
|
||||
return null;
|
||||
}
|
||||
<Text style={[styles.header, theme.text]}>{t('mode_heading')}</Text>
|
||||
|
||||
return <Root title="Discord Rich Presence setup" scrollable autoresize>
|
||||
<View style={styles.main}>
|
||||
<Text style={theme.text}>Discord Rich Presence setup</Text>
|
||||
<Picker<DiscordSourceType> selectedValue={selectedMode} onValueChange={v => setSelectedMode(parseInt(v))}
|
||||
style={[styles.picker, theme.picker]}
|
||||
>
|
||||
<Picker.Item label={t('mode_coral_friend')!} value={DiscordSourceType.CORAL} />
|
||||
<Picker.Item label={t('mode_url')!} value={DiscordSourceType.URL} />
|
||||
<Picker.Item label={t('mode_none')!} value={DiscordSourceType.NONE} />
|
||||
</Picker>
|
||||
|
||||
<Text style={[styles.header, theme.text]}>1. Select mode</Text>
|
||||
{selectedMode === DiscordSourceType.CORAL ? <>
|
||||
<Text style={[styles.header, theme.text]}>{t('coral_user_heading')}</Text>
|
||||
<Text style={[styles.help, theme.text]}>{t('coral_user_help')}</Text>
|
||||
|
||||
<Picker<DiscordSourceType> selectedValue={selectedMode} onValueChange={v => setSelectedMode(parseInt(v))}
|
||||
<Picker<string> selectedValue={selectedUserId ?? ''} onValueChange={setSelectedUserId}
|
||||
style={[styles.picker, theme.picker]}
|
||||
>
|
||||
<Picker.Item label="Select a user that is friends with the user you want to share"
|
||||
value={DiscordSourceType.CORAL} />
|
||||
<Picker.Item label="Enter a URL that returns the presence data you want to share"
|
||||
value={DiscordSourceType.URL} />
|
||||
<Picker.Item label="Disable" value={DiscordSourceType.NONE} />
|
||||
{filtered_users?.map(u => <Picker.Item
|
||||
key={u.user.id}
|
||||
label={u.user.nickname +
|
||||
(u.user.nickname !== u.nso!.nsoAccount.user.name ? '/' + u.nso!.nsoAccount.user.name : '')}
|
||||
value={u.user.id}
|
||||
/>)}
|
||||
</Picker>
|
||||
|
||||
{selectedMode === DiscordSourceType.CORAL ? <>
|
||||
<Text style={[styles.header, theme.text]}>2. Select user</Text>
|
||||
<Text style={[styles.help, theme.text]}>This user must be friends with the user you want to share.</Text>
|
||||
{props.friendNsaId && (!selectedFriendNsaId || selectedFriendNsaId === props.friendNsaId) ? <>
|
||||
<Text style={[styles.header, theme.text]}>{t('coral_friend_heading')}</Text>
|
||||
<Text style={[styles.help, theme.text]}>{t('coral_friend_help')}</Text>
|
||||
|
||||
<Picker<string> selectedValue={selectedUserId ?? ''} onValueChange={setSelectedUserId}
|
||||
<Picker<string> selectedValue={selectedFriendNsaId ?? ''} onValueChange={setSelectedFriendNsaId}
|
||||
style={[styles.picker, theme.picker]}
|
||||
enabled={false}
|
||||
>
|
||||
<Picker.Item key={props.friendNsaId} label={friend?.name ?? props.friendNsaId}
|
||||
value={props.friendNsaId} />
|
||||
</Picker>
|
||||
</> : user && friends_with_presence ? <>
|
||||
<Text style={[styles.header, theme.text]}>{t('coral_friend_heading')}</Text>
|
||||
<Text style={[styles.help, theme.text]}>{t('coral_friend_help')}</Text>
|
||||
|
||||
<Picker<string> selectedValue={selectedFriendNsaId ?? ''} onValueChange={setSelectedFriendNsaId}
|
||||
style={[styles.picker, theme.picker]}
|
||||
>
|
||||
{filtered_users?.map(u => <Picker.Item
|
||||
key={u.user.id}
|
||||
label={u.user.nickname +
|
||||
(u.user.nickname !== u.nso!.nsoAccount.user.name ? '/' + u.nso!.nsoAccount.user.name : '')}
|
||||
value={u.user.id}
|
||||
/>)}
|
||||
{friends_with_presence.map(f => <Picker.Item key={f.nsaId} label={f.name} value={f.nsaId} />)}
|
||||
</Picker>
|
||||
|
||||
{props.friend_nsa_id && (!selectedFriendNsaId || selectedFriendNsaId === props.friend_nsa_id) ? <>
|
||||
<Text style={[styles.header, theme.text]}>3. Select friend</Text>
|
||||
<Text style={[styles.help, theme.text]}>This is the user you want to share.</Text>
|
||||
|
||||
<Picker<string> selectedValue={selectedFriendNsaId ?? ''} onValueChange={setSelectedFriendNsaId}
|
||||
style={[styles.picker, theme.picker]}
|
||||
enabled={false}
|
||||
>
|
||||
<Picker.Item key={props.friend_nsa_id} label={friend?.name ?? props.friend_nsa_id}
|
||||
value={props.friend_nsa_id} />
|
||||
</Picker>
|
||||
</> : user && friends_with_presence ? <>
|
||||
<Text style={[styles.header, theme.text]}>3. Select friend</Text>
|
||||
<Text style={[styles.help, theme.text]}>This is the user you want to share.</Text>
|
||||
|
||||
<Picker<string> selectedValue={selectedFriendNsaId ?? ''} onValueChange={setSelectedFriendNsaId}
|
||||
style={[styles.picker, theme.picker]}
|
||||
>
|
||||
{friends_with_presence.map(f => <Picker.Item key={f.nsaId} label={f.name} value={f.nsaId} />)}
|
||||
</Picker>
|
||||
</> : null}
|
||||
</> : null}
|
||||
</> : null}
|
||||
|
||||
{selectedMode === DiscordSourceType.URL ? <>
|
||||
<Text style={[styles.header, theme.text]}>2. Enter presence URL</Text>
|
||||
<Text style={[styles.help, theme.text]}>This must be a HTTPS URL that returns a JSON object with either a user, friend or presence key. This is intended to be used with nxapi's znc API proxy.</Text>
|
||||
{selectedMode === DiscordSourceType.URL ? <>
|
||||
<Text style={[styles.header, theme.text]}>{t('url_heading')}</Text>
|
||||
<Text style={[styles.help, theme.text]}>{t('url_help')}</Text>
|
||||
|
||||
<TextInput value={presenceUrl} onChangeText={setPresenceUrl}
|
||||
placeholder="https://nxapi.example.com/api/znc/friend/..."
|
||||
style={[styles.textInput, theme.textInput]} />
|
||||
</> : null}
|
||||
<TextInput value={presenceUrl} onChangeText={setPresenceUrl}
|
||||
placeholder="https://nxapi.example.com/api/znc/friend/..."
|
||||
style={[styles.textInput, theme.textInput]} />
|
||||
</> : null}
|
||||
|
||||
{discord_presence_source && (props.show_preferences_button ?? true) ? <>
|
||||
<Text style={[styles.help, styles.header, theme.text]}>Configure additional options for Discord Rich Presence</Text>
|
||||
<View style={[styles.button, styles.buttonPreferences]}>
|
||||
<Button title="Preferences"
|
||||
onPress={() => ipc.showPreferencesWindow()}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
|
||||
</View>
|
||||
</> : null}
|
||||
{props.discordPresenceSource && (props.showPreferencesButton ?? true) ? <>
|
||||
<Text style={[styles.help, styles.header, theme.text]}>{t('preferences_heading')}</Text>
|
||||
<View style={[styles.button, styles.buttonPreferences]}>
|
||||
<Button title={t('preferences')!}
|
||||
onPress={() => ipc.showPreferencesWindow()}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
|
||||
</View>
|
||||
</> : null}
|
||||
|
||||
<View style={styles.buttons}>
|
||||
<View style={styles.button}>
|
||||
<Button title="Cancel"
|
||||
onPress={() => window.close()}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
|
||||
</View>
|
||||
<View style={styles.button}>
|
||||
<Button title="Save"
|
||||
onPress={save}
|
||||
primary
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
|
||||
</View>
|
||||
<View style={styles.buttons}>
|
||||
<View style={styles.button}>
|
||||
<Button title={t('cancel')!}
|
||||
onPress={() => window.close()}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
|
||||
</View>
|
||||
<View style={styles.button}>
|
||||
<Button title={t('save')!}
|
||||
onPress={save}
|
||||
primary
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
|
||||
</View>
|
||||
</View>
|
||||
</Root>;
|
||||
</View>;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
/// <reference path="../react-native-web.d.ts" />
|
||||
|
||||
import React, { useCallback, useEffect } from 'react';
|
||||
import { ActivityIndicator, Image, StyleSheet, Text, TouchableOpacity, useColorScheme, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ActivityIndicator, Image, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
|
||||
import { CheckBox } from 'react-native-web';
|
||||
import { Game, Presence, PresencePermissions, PresenceState } from '../../../api/coral-types.js';
|
||||
import { Friend, Presence, PresenceGame, PresencePermissions, PresencePlatform, PresenceState } from '../../../api/coral-types.js';
|
||||
import { getTitleIdFromEcUrl, hrduration } from '../../../util/misc.js';
|
||||
import { Button } from '../components/index.js';
|
||||
import { DEFAULT_ACCENT_COLOUR, TEXT_COLOUR_ACTIVE, TEXT_COLOUR_DARK, TEXT_COLOUR_LIGHT } from '../constants.js';
|
||||
|
|
@ -15,10 +16,7 @@ export interface FriendProps {
|
|||
friend: string;
|
||||
}
|
||||
|
||||
export default function Friend(props: FriendProps) {
|
||||
const colour_scheme = useColorScheme();
|
||||
const theme = colour_scheme === 'light' ? light : dark;
|
||||
|
||||
export default function FriendWindow(props: FriendProps) {
|
||||
const [accent_colour, setAccentColour] = React.useState(() => ipc.getAccentColour());
|
||||
useEventListener(events, 'systemPreferences:accent-colour', setAccentColour, []);
|
||||
|
||||
|
|
@ -50,6 +48,7 @@ export default function Friend(props: FriendProps) {
|
|||
if (!user || !friend || discord_presence_source_state !== RequestState.LOADED) {
|
||||
return <Root title={friend?.name} titleUser={user ?? undefined}
|
||||
autoresize={!!user && discord_presence_source_state === RequestState.LOADED}
|
||||
i18nNamespace={['friend_window', 'time_since']}
|
||||
>
|
||||
<View style={styles.loading}>
|
||||
<ActivityIndicator size="large" color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
|
||||
|
|
@ -63,83 +62,127 @@ export default function Friend(props: FriendProps) {
|
|||
const can_see_user_presence = user.nsoAccount.user.permissions.presence === PresencePermissions.FRIENDS ||
|
||||
(user.nsoAccount.user.permissions.presence === PresencePermissions.FAVORITE_FRIENDS && friend.isFavoriteFriend);
|
||||
|
||||
return <Root title={friend.name} titleUser={user} autoresize>
|
||||
<View style={styles.main}>
|
||||
<View style={styles.friend}>
|
||||
<Image source={{uri: friend.imageUri, width: 130, height: 130}} style={styles.friendImage} />
|
||||
<Text style={[styles.friendName, theme.text]}>{friend.name}</Text>
|
||||
return <Root title={friend.name} titleUser={user} autoresize i18nNamespace={['friend_window', 'time_since']}>
|
||||
<Friend
|
||||
friend={friend} canSeeUserPresence={can_see_user_presence}
|
||||
showDiscordPresenceSetup={discord_presence_active || !!friend.presence.updatedAt || false}
|
||||
discordPresenceActive={discord_presence_active ?? false}
|
||||
setDiscordPresenceActive={active => ipc.setDiscordPresenceSource(active ?
|
||||
{na_id: user.user.id, friend_nsa_id: friend.nsaId} : null)} />
|
||||
</Root>;
|
||||
}
|
||||
|
||||
{friend.presence.updatedAt ?
|
||||
<FriendPresence presence={friend.presence} /> :
|
||||
<Text style={[styles.noPresence, theme.text]}>You don't have access to this user's presence, or they have never been online.</Text>}
|
||||
function Friend(props: {
|
||||
friend: Friend;
|
||||
canSeeUserPresence?: boolean;
|
||||
showDiscordPresenceSetup?: boolean;
|
||||
discordPresenceActive?: boolean;
|
||||
setDiscordPresenceActive?: (active: boolean) => void;
|
||||
}) {
|
||||
const theme = useColourScheme() === 'light' ? light : dark;
|
||||
const accent_colour = useAccentColour();
|
||||
const { t, i18n } = useTranslation('friend_window');
|
||||
|
||||
const friend = props.friend;
|
||||
|
||||
return <View style={styles.main}>
|
||||
<View style={styles.friend}>
|
||||
<Image source={{uri: friend.image2Uri, width: 130, height: 130}} style={styles.friendImage} />
|
||||
<Text style={[styles.friendName, theme.text]}>{friend.name}</Text>
|
||||
|
||||
{friend.presence.updatedAt ?
|
||||
<FriendPresence presence={friend.presence} /> :
|
||||
<Text style={[styles.noPresence, theme.text]}>{t('no_presence')}</Text>}
|
||||
</View>
|
||||
|
||||
<View style={styles.right}>
|
||||
<View style={styles.detail}>
|
||||
{(friend.presence.state === PresenceState.ONLINE || friend.presence.state === PresenceState.PLAYING) &&
|
||||
'name' in friend.presence.game ? <FriendPresenceGame game={friend.presence.game} /> : null}
|
||||
|
||||
<Text style={[styles.friendNsaId, theme.text]}>
|
||||
{t('nsa_id')}: <Text style={styles.friendNsaIdValue}>{friend.nsaId}</Text>
|
||||
</Text>
|
||||
<Text style={[styles.friendCoralId, theme.text]}>{friend.isServiceUser ? <>
|
||||
{t('coral_id')}: <Text style={styles.friendCoralIdValue}>{friend.id}</Text>
|
||||
</> : t('no_coral_user')}</Text>
|
||||
|
||||
<Text style={[styles.friendCreatedAt, theme.text]}>
|
||||
{t('friends_since', {
|
||||
date: new Date(friend.friendCreatedAt * 1000),
|
||||
formatParams: { date: { dateStyle: 'short', timeStyle: 'medium' } },
|
||||
})}
|
||||
</Text>
|
||||
{friend.presence.updatedAt ? <Text style={[styles.presenceUpdatedAt, theme.text]}>
|
||||
{t('presence_updated_at', {
|
||||
date: new Date(friend.presence.updatedAt * 1000),
|
||||
formatParams: { date: { dateStyle: 'short', timeStyle: 'medium' } },
|
||||
})}
|
||||
</Text> : null}
|
||||
{!(friend.presence.state === PresenceState.ONLINE || friend.presence.state === PresenceState.PLAYING) &&
|
||||
friend.presence.logoutAt ? <Text style={[styles.presenceUpdatedAt, theme.text]}>
|
||||
{t('presence_logout_at', {
|
||||
date: new Date(friend.presence.logoutAt * 1000),
|
||||
formatParams: { date: { dateStyle: 'short', timeStyle: 'medium' } },
|
||||
})}
|
||||
</Text> : null}
|
||||
<Text style={[styles.canSeeUserPresence, theme.text]}>
|
||||
{t(props.canSeeUserPresence ? 'presence_sharing' : 'presence_not_sharing')}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<View style={styles.right}>
|
||||
<View style={styles.detail}>
|
||||
{(friend.presence.state === PresenceState.ONLINE || friend.presence.state === PresenceState.PLAYING) &&
|
||||
'name' in friend.presence.game ? <FriendPresenceGame game={friend.presence.game} /> : null}
|
||||
|
||||
<Text style={[styles.friendNsaId, theme.text]}>NSA ID: <Text style={styles.friendNsaIdValue}>{friend.nsaId}</Text></Text>
|
||||
<Text style={[styles.friendCoralId, theme.text]}>{friend.isServiceUser ? <>
|
||||
Coral user ID: <Text style={styles.friendCoralIdValue}>{friend.id}</Text>
|
||||
</> : 'Never used Nintendo Switch Online app'}</Text>
|
||||
|
||||
<Text style={[styles.friendCreatedAt, theme.text]}>Friends since {new Date(friend.friendCreatedAt * 1000).toLocaleString('en-GB')}</Text>
|
||||
{friend.presence.updatedAt ? <Text style={[styles.presenceUpdatedAt, theme.text]}>Presence updated at {new Date(friend.presence.updatedAt * 1000).toLocaleString('en-GB')}</Text> : null}
|
||||
{!(friend.presence.state === PresenceState.ONLINE || friend.presence.state === PresenceState.PLAYING) &&
|
||||
friend.presence.logoutAt ? <Text style={[styles.presenceUpdatedAt, theme.text]}>Last online at {new Date(friend.presence.logoutAt * 1000).toLocaleString('en-GB')}</Text> : null}
|
||||
<Text style={[styles.canSeeUserPresence, theme.text]}>This user {can_see_user_presence ? 'can' : 'can not'} see your presence.</Text>
|
||||
</View>
|
||||
|
||||
<View style={styles.buttons}>
|
||||
{discord_presence_active || friend.presence.updatedAt ? <View style={styles.discord}>
|
||||
<CheckBox
|
||||
value={discord_presence_active ?? false}
|
||||
onValueChange={v => ipc.setDiscordPresenceSource(v ?
|
||||
{na_id: user.user.id, friend_nsa_id: friend.nsaId} : null)}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}
|
||||
style={styles.discordCheckbox}
|
||||
/>
|
||||
<TouchableOpacity onPress={() => ipc.setDiscordPresenceSource(!discord_presence_active ?
|
||||
{na_id: user.user.id, friend_nsa_id: friend.nsaId} : null)}>
|
||||
<Text style={theme.text}>Share presence to Discord</Text>
|
||||
</TouchableOpacity>
|
||||
</View> : null}
|
||||
|
||||
<Button title="Close"
|
||||
onPress={() => window.close()}
|
||||
<View style={styles.buttons}>
|
||||
{props.showDiscordPresenceSetup ? <View style={styles.discord}>
|
||||
<CheckBox
|
||||
value={props.discordPresenceActive ?? false}
|
||||
onValueChange={v => props.setDiscordPresenceActive?.(!!v)}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}
|
||||
primary autoFocus />
|
||||
</View>
|
||||
style={styles.discordCheckbox}
|
||||
/>
|
||||
<TouchableOpacity onPress={() => props.setDiscordPresenceActive?.(!props.discordPresenceActive)}>
|
||||
<Text style={theme.text}>{t('discord_presence')}</Text>
|
||||
</TouchableOpacity>
|
||||
</View> : null}
|
||||
|
||||
<Button title={t('close')}
|
||||
onPress={() => window.close()}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}
|
||||
primary autoFocus />
|
||||
</View>
|
||||
</View>
|
||||
</Root>;
|
||||
</View>;
|
||||
}
|
||||
|
||||
function FriendPresence(props: {
|
||||
presence: Presence;
|
||||
}) {
|
||||
const theme = useColourScheme() === 'light' ? light : dark;
|
||||
const { t, i18n } = useTranslation('friend_window');
|
||||
|
||||
const logout = props.presence.logoutAt ? new Date(props.presence.logoutAt * 1000) : null;
|
||||
const since_logout = useTimeSince(logout ?? new Date(0));
|
||||
const since_logout = useTimeSince(logout ?? new Date(0), false, i18n.getFixedT(null, 'time_since'));
|
||||
const game = 'name' in props.presence.game ? props.presence.game : null;
|
||||
|
||||
if (props.presence.state === PresenceState.ONLINE || props.presence.state === PresenceState.PLAYING) {
|
||||
return <Text style={[styles.presenceText, theme.text, styles.presenceTextOnline]}>Playing {game?.name}</Text>;
|
||||
if ((props.presence.state === PresenceState.ONLINE || props.presence.state === PresenceState.PLAYING) && game) {
|
||||
return <Text style={[styles.presenceText, theme.text, styles.presenceTextOnline]}>{t(
|
||||
'platform' in props.presence ?
|
||||
props.presence.platform === PresencePlatform.NX ? 'presence_playing_nx' :
|
||||
props.presence.platform === PresencePlatform.OUNCE ? 'presence_playing_ounce' :
|
||||
'presence_playing' : 'presence_playing', {game: game.name})}</Text>;
|
||||
}
|
||||
|
||||
return <View>
|
||||
<Text style={[styles.presenceText, styles.presenceTextOffline, theme.text]}>Offline</Text>
|
||||
{logout ? <Text style={[styles.presenceText, styles.presenceTextOffline, theme.text]}>Last seen {since_logout}</Text> : null}
|
||||
<Text style={[styles.presenceText, styles.presenceTextOffline, theme.text]}>{t('presence_offline')}</Text>
|
||||
{logout ? <Text style={[styles.presenceText, styles.presenceTextOffline, theme.text]}>{t('presence_last_seen', {since_logout})}</Text> : null}
|
||||
</View>;
|
||||
}
|
||||
|
||||
function FriendPresenceGame(props: {
|
||||
game: Game;
|
||||
game: PresenceGame;
|
||||
}) {
|
||||
const theme = useColourScheme() === 'light' ? light : dark;
|
||||
const accent_colour = useAccentColour();
|
||||
const { t, i18n } = useTranslation('friend_window');
|
||||
|
||||
const openShop = useCallback(() => {
|
||||
ipc.openExternalUrl(props.game.shopUri);
|
||||
|
|
@ -154,12 +197,26 @@ function FriendPresenceGame(props: {
|
|||
<View style={styles.gameDetail}>
|
||||
<Text style={[styles.gameName, theme.text]}>{props.game.name}</Text>
|
||||
{props.game.sysDescription ? <Text style={[styles.gameActivity, theme.text]}>{props.game.sysDescription}</Text> : null}
|
||||
<Text style={[styles.gameTotalPlayTime, theme.text]}>Played for {hrduration(props.game.totalPlayTime)}</Text>
|
||||
<Text style={[styles.gameFirstPlayed, theme.text]}>First played {first_played?.toLocaleString('en-GB') ?? 'now'}</Text>
|
||||
{titleid ? <Text style={[styles.gameTitleId, theme.text]}>Title ID: <Text style={styles.gameTitleIdValue}>{titleid}</Text></Text> : null}
|
||||
<Text style={[styles.gameTotalPlayTime, theme.text]}>
|
||||
{props.game.totalPlayTime >= 60 ?
|
||||
props.game.totalPlayTime % 60 ?
|
||||
t('game_played_for_hm', {hours: Math.floor(props.game.totalPlayTime / 60),
|
||||
minutes: props.game.totalPlayTime % 60}) :
|
||||
t('game_played_for_h', {hours: props.game.totalPlayTime / 60}) :
|
||||
t('game_played_for_m', {minutes: props.game.totalPlayTime})}
|
||||
</Text>
|
||||
<Text style={[styles.gameFirstPlayed, theme.text]}>
|
||||
{first_played ? t('game_first_played', {
|
||||
date: first_played,
|
||||
formatParams: { date: { dateStyle: 'short', timeStyle: 'medium' } },
|
||||
}) : t('game_first_played_now')}
|
||||
</Text>
|
||||
{titleid ? <Text style={[styles.gameTitleId, theme.text]}>
|
||||
{t('game_title_id')}: <Text style={styles.gameTitleIdValue}>{titleid}</Text>
|
||||
</Text> : null}
|
||||
|
||||
<View style={styles.gameShopButton}>
|
||||
<Button title="Nintendo eShop" onPress={openShop} color={'#' + accent_colour} />
|
||||
<Button title={t('game_shop')} onPress={openShop} color={'#' + accent_colour} />
|
||||
</View>
|
||||
</View>
|
||||
</View>;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { EventEmitter } from 'events';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import createDebug from 'debug';
|
||||
import type { NxapiElectronIpc } from '../preload/index.js';
|
||||
|
||||
|
|
|
|||
|
|
@ -1,11 +1,12 @@
|
|||
import React, { useCallback, useMemo } from 'react';
|
||||
import { Image, StyleSheet, Text, View } from 'react-native';
|
||||
import { Trans, useTranslation } from 'react-i18next';
|
||||
import ipc, { events } from '../ipc.js';
|
||||
import { getAccounts, RequestState, useAccentColour, useAsync, useColourScheme, useDiscordPresenceSource, useEventListener, User } from '../util.js';
|
||||
import { Friend, PresencePermissions } from '../../../api/coral-types.js';
|
||||
import { TEXT_COLOUR_DARK, TEXT_COLOUR_LIGHT } from '../constants.js';
|
||||
import Section from './section.js';
|
||||
import { Button } from '../components/index.js';
|
||||
import { Button, NintendoSwitchUser, NintendoSwitchUsers } from '../components/index.js';
|
||||
|
||||
export default function SetupDiscordPresence(props: {
|
||||
user: User;
|
||||
|
|
@ -13,6 +14,7 @@ export default function SetupDiscordPresence(props: {
|
|||
}) {
|
||||
const theme = useColourScheme() === 'light' ? light : dark;
|
||||
const accent_colour = useAccentColour();
|
||||
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'discord_section' });
|
||||
|
||||
const [source, discord_presence_source_state] = useDiscordPresenceSource();
|
||||
|
||||
|
|
@ -35,51 +37,46 @@ export default function SetupDiscordPresence(props: {
|
|||
|
||||
const content = !source && added_friends?.length ? <>
|
||||
<Text style={[styles.text, theme.text]}>
|
||||
Use one of these accounts to set up Discord Rich Presence for this user:{' '}
|
||||
{added_friends.map((u, i) => <React.Fragment key={u.user.id}>
|
||||
{i === 0 ? '' : ', '}
|
||||
<Image source={{uri: u.nso!.nsoAccount.user.imageUri, width: 16, height: 16}} style={styles.discordNsoUserImage} />{' '}
|
||||
{u.nso!.nsoAccount.user.name}
|
||||
{u.nso!.nsoAccount.user.name !== u.user.nickname ? ' (' + u.user.nickname + ')' : ''}
|
||||
</React.Fragment>)}.
|
||||
<Trans i18nKey="main_window:discord_section.setup_with_existing_user">
|
||||
<NintendoSwitchUsers users={added_friends.map(u => ({
|
||||
user: u.nso!.nsoAccount.user, nickname: u.user.nickname,
|
||||
}))} />
|
||||
</Trans>
|
||||
</Text>
|
||||
|
||||
<View style={styles.button}>
|
||||
<Button title="Setup" onPress={() => ipc.showDiscordModal({
|
||||
<Button title={t('setup')} onPress={() => ipc.showDiscordModal({
|
||||
users: added_friends.map(u => u.user.id),
|
||||
friend_nsa_id: props.user.nso!.nsoAccount.user.nsaId,
|
||||
})} color={'#' + accent_colour} />
|
||||
</View>
|
||||
</> :!source && users ? <>
|
||||
<Text style={[styles.text, theme.text]}>Add a Nintendo Switch Online account with this user as a friend to set up Discord Rich Presence.</Text>
|
||||
<Text style={[styles.text, theme.text]}>{t('add_user')}</Text>
|
||||
</> : source && 'na_id' in source && source.na_id === props.user.user.id && !source.friend_nsa_id ? <>
|
||||
<Text style={[styles.text, theme.text]}>
|
||||
This user's presence is being shared to Discord.
|
||||
</Text>
|
||||
<Text style={[styles.text, theme.text]}>{t('active_self')}</Text>
|
||||
</> : source && 'na_id' in source && source.na_id === props.user.user.id && friend ? <>
|
||||
<Text style={[styles.text, theme.text]}>
|
||||
<Image source={{uri: friend.imageUri, width: 16, height: 16}} style={styles.discordNsoUserImage} />{' '}
|
||||
{friend.name}'s presence is being shared to Discord using this account.
|
||||
<Trans i18nKey="main_window:discord_section.active_friend">
|
||||
<NintendoSwitchUser friend={friend} />
|
||||
</Trans>
|
||||
</Text>
|
||||
</> : source && 'na_id' in source && source.na_id === props.user.user.id && source.friend_nsa_id ? <>
|
||||
<Text style={[styles.text, theme.text]}>
|
||||
An unknown user's presence is being shared to Discord using this account.
|
||||
</Text>
|
||||
<Text style={[styles.text, theme.text]}>{t('active_unknown')}</Text>
|
||||
</> : source && 'na_id' in source && auth_user && source.friend_nsa_id && source.friend_nsa_id === props.user.nso?.nsoAccount.user.nsaId ? <>
|
||||
<Text style={[styles.text, theme.text]}>
|
||||
This user's presence is being shared to Discord using{' '}
|
||||
<Image source={{uri: auth_user.nsoAccount.user.imageUri, width: 16, height: 16}} style={styles.discordNsoUserImage} />{' '}
|
||||
{auth_user.nsoAccount.user.name}
|
||||
{auth_user.nsoAccount.user.name !== auth_user.user.nickname ? ' (' + auth_user.user.nickname + ')' : ''}.
|
||||
<Trans i18nKey="main_window:discord_section.active_via">
|
||||
<NintendoSwitchUser user={auth_user.nsoAccount.user} nickname={auth_user.user.nickname} />
|
||||
</Trans>
|
||||
</Text>
|
||||
</> : null;
|
||||
|
||||
return content ? <Section title="Discord Rich Presence">
|
||||
return content ? <Section title={t('title')}>
|
||||
<View style={styles.content}>
|
||||
{content}
|
||||
|
||||
{source ? <View style={styles.button}>
|
||||
<Button title="Disable" onPress={() => ipc.setDiscordPresenceSource(null)} color={'#' + accent_colour} />
|
||||
<Button title={t('disable')}
|
||||
onPress={() => ipc.setDiscordPresenceSource(null)} color={'#' + accent_colour} />
|
||||
</View> : null}
|
||||
</View>
|
||||
</Section> : null;
|
||||
|
|
@ -96,10 +93,6 @@ const styles = StyleSheet.create({
|
|||
fontSize: 13,
|
||||
opacity: 0.7,
|
||||
},
|
||||
discordNsoUserImage: {
|
||||
borderRadius: 8,
|
||||
textAlignVertical: -3,
|
||||
},
|
||||
|
||||
button: {
|
||||
marginTop: 10,
|
||||
|
|
|
|||
|
|
@ -1,23 +1,41 @@
|
|||
import React, { useCallback, useEffect } from 'react';
|
||||
import React, { useCallback, useEffect, useState } from 'react';
|
||||
import { Image, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
|
||||
import { Trans, useTranslation } from 'react-i18next';
|
||||
import { User } from 'discord-rpc';
|
||||
import ipc, { events } from '../ipc.js';
|
||||
import { RequestState, useAsync, useEventListener } from '../util.js';
|
||||
import { DiscordPresenceSource, DiscordPresenceSourceUrl, DiscordPresenceSourceCoral } from '../../common/types.js';
|
||||
import { DiscordPresenceSource, DiscordPresenceSourceUrl, DiscordPresenceSourceCoral, DiscordStatus } from '../../common/types.js';
|
||||
import { DiscordPresence } from '../../../discord/types.js';
|
||||
import { DISCORD_COLOUR, TEXT_COLOUR_DARK } from '../constants.js';
|
||||
import { NintendoSwitchUser } from '../components/index.js';
|
||||
import Warning from '../components/icons/warning.js';
|
||||
|
||||
export default function DiscordPresenceSource(props: {
|
||||
source: DiscordPresenceSource | null;
|
||||
presence: DiscordPresence | null;
|
||||
user: User | null;
|
||||
}) {
|
||||
const [status, setStatus] = useState<DiscordStatus | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
ipc.getDiscordStatus().then(setStatus);
|
||||
}, [ipc]);
|
||||
|
||||
useEventListener(events, 'update-discord-status', setStatus, []);
|
||||
|
||||
const showErrorDetails = useCallback(() => {
|
||||
ipc.showDiscordLastUpdateError();
|
||||
}, [ipc]);
|
||||
|
||||
if (!props.source) return null;
|
||||
|
||||
return <TouchableOpacity onPress={() => ipc.showDiscordModal()}>
|
||||
<View style={[styles.discord, !props.source ? styles.discordInactive : null]}>
|
||||
{renderDiscordPresenceSource(props.source)}
|
||||
{props.presence && props.user ? <DiscordPresence presence={props.presence} user={props.user} /> : null}
|
||||
{props.presence || props.user ? <DiscordPresence presence={props.presence} user={props.user} /> : null}
|
||||
|
||||
{status?.error_message ?
|
||||
<DiscordPresenceError message={status?.error_message} onPress={showErrorDetails} /> : null}
|
||||
</View>
|
||||
</TouchableOpacity>;
|
||||
}
|
||||
|
|
@ -35,6 +53,8 @@ function renderDiscordPresenceSource(source: DiscordPresenceSource | null) {
|
|||
function DiscordPresenceSourceCoral(props: {
|
||||
source: DiscordPresenceSourceCoral;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'sidebar' });
|
||||
|
||||
const [token] = useAsync(useCallback(() =>
|
||||
ipc.getNintendoAccountCoralToken(props.source.na_id), [ipc, props.source.na_id]));
|
||||
const [friends, , friends_state, forceRefreshFriends] = useAsync(useCallback(() => token ?
|
||||
|
|
@ -51,11 +71,11 @@ function DiscordPresenceSourceCoral(props: {
|
|||
|
||||
return <View style={styles.discordSource}>
|
||||
{friend ? <Text style={styles.discordSourceText}>
|
||||
Discord Rich Presence active:{' '}
|
||||
<Image source={{uri: friend.imageUri, width: 16, height: 16}} style={styles.discordNsoUserImage} />{' '}
|
||||
{friend.name}
|
||||
<Trans i18nKey="main_window:sidebar.discord_active_friend">
|
||||
<NintendoSwitchUser friend={friend} />
|
||||
</Trans>
|
||||
</Text> : <Text style={styles.discordSourceText}>
|
||||
Discord Rich Presence active
|
||||
{t('discord_active')}
|
||||
</Text>}
|
||||
</View>;
|
||||
}
|
||||
|
|
@ -63,41 +83,70 @@ function DiscordPresenceSourceCoral(props: {
|
|||
function DiscordPresenceSourceUrl(props: {
|
||||
source: DiscordPresenceSourceUrl;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'sidebar' });
|
||||
|
||||
return <View style={styles.discordSource}>
|
||||
<Text style={styles.discordSourceText} numberOfLines={3} ellipsizeMode="tail">
|
||||
Discord Rich Presence active:{' '}
|
||||
{t('discord_active')}:{' '}
|
||||
<Text style={styles.discordSourceUrlValue}>{props.source.url}</Text>
|
||||
</Text>
|
||||
</View>;
|
||||
}
|
||||
|
||||
function DiscordPresenceInactive() {
|
||||
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'sidebar' });
|
||||
|
||||
return <View style={styles.discordSource}>
|
||||
<Text style={styles.discordSourceText}>Discord Rich Presence not active</Text>
|
||||
<Text style={styles.discordSourceText}>{t('discord_not_active')}</Text>
|
||||
</View>;
|
||||
}
|
||||
|
||||
function DiscordPresence(props: {
|
||||
presence: DiscordPresence;
|
||||
user: User;
|
||||
presence: DiscordPresence | null;
|
||||
user: User | null;
|
||||
}) {
|
||||
const large_image_url = props.presence.activity.largeImageKey?.match(/^\d{16}$/) ?
|
||||
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'sidebar' });
|
||||
|
||||
const large_image_url = props.presence ? props.presence.activity.largeImageKey?.match(/^\d{16}$/) ?
|
||||
'https://cdn.discordapp.com/app-assets/' + props.presence.id + '/' +
|
||||
props.presence.activity.largeImageKey + '.png' :
|
||||
props.presence.activity.largeImageKey;
|
||||
const user_image_url = 'https://cdn.discordapp.com/avatars/' + props.user.id + '/' + props.user.avatar + '.png';
|
||||
props.presence.activity.largeImageKey : undefined;
|
||||
|
||||
return <>
|
||||
<View style={styles.discordPresence}>
|
||||
const user_image_url = props.user ?
|
||||
props.user.avatar ? 'https://cdn.discordapp.com/avatars/' + props.user.id + '/' + props.user.avatar + '.png' :
|
||||
!props.user.discriminator || props.user.discriminator === '0' ?
|
||||
'https://cdn.discordapp.com/embed/avatars/' + ((parseInt(props.user.id) >> 22) % 6) + '.png' :
|
||||
'https://cdn.discordapp.com/embed/avatars/' + (parseInt(props.user.discriminator) % 5) + '.png' : undefined;
|
||||
|
||||
return <View style={styles.discordPresenceContainer}>
|
||||
{props.presence ? <View style={styles.discordPresence}>
|
||||
<Image source={{uri: large_image_url, width: 18, height: 18}} style={styles.discordPresenceImage} />
|
||||
<Text style={styles.discordPresenceText} numberOfLines={1} ellipsizeMode="tail">Playing</Text>
|
||||
</View>
|
||||
<Text style={styles.discordPresenceText} numberOfLines={1} ellipsizeMode="tail">{t('discord_playing')}</Text>
|
||||
</View> : null}
|
||||
|
||||
<View style={styles.discordUser}>
|
||||
{props.user ? <View style={styles.discordUser}>
|
||||
<Image source={{uri: user_image_url, width: 18, height: 18}} style={styles.discordUserImage} />
|
||||
<Text style={styles.discordUserText} numberOfLines={1} ellipsizeMode="tail">{props.user.username}#{props.user.discriminator}</Text>
|
||||
<Text style={styles.discordUserText} numberOfLines={1} ellipsizeMode="tail">
|
||||
{props.user.username}
|
||||
{props.user.discriminator && props.user.discriminator !== '0' ?
|
||||
<Text style={styles.discordUserDiscriminator}>#{props.user.discriminator}</Text> : null}
|
||||
</Text>
|
||||
</View> : <View style={styles.discordUser}>
|
||||
<Text style={styles.discordUserText} numberOfLines={1} ellipsizeMode="tail">{t('discord_not_connected')}</Text>
|
||||
</View>}
|
||||
</View>;
|
||||
}
|
||||
|
||||
function DiscordPresenceError(props: {
|
||||
message: string;
|
||||
onPress?: () => void;
|
||||
}) {
|
||||
return <TouchableOpacity onPress={props.onPress} style={styles.errorTouchable}>
|
||||
<View style={styles.error}>
|
||||
<Text style={styles.icon}><Warning /></Text>
|
||||
<Text style={styles.errorText} numberOfLines={1} ellipsizeMode="tail">{props.message}</Text>
|
||||
</View>
|
||||
</>;
|
||||
</TouchableOpacity>;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
|
|
@ -115,18 +164,18 @@ const styles = StyleSheet.create({
|
|||
discordSourceText: {
|
||||
color: TEXT_COLOUR_DARK,
|
||||
},
|
||||
discordNsoUserImage: {
|
||||
borderRadius: 8,
|
||||
textAlignVertical: -3,
|
||||
},
|
||||
discordSourceUrlValue: {
|
||||
fontFamily: 'monospace',
|
||||
fontSize: 12,
|
||||
userSelect: 'all',
|
||||
},
|
||||
|
||||
discordPresenceContainer: {
|
||||
marginTop: 2,
|
||||
},
|
||||
|
||||
discordPresence: {
|
||||
marginTop: 12,
|
||||
marginTop: 10,
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
},
|
||||
|
|
@ -150,4 +199,26 @@ const styles = StyleSheet.create({
|
|||
discordUserText: {
|
||||
color: TEXT_COLOUR_DARK,
|
||||
},
|
||||
discordUserDiscriminator: {
|
||||
opacity: 0.7,
|
||||
},
|
||||
|
||||
errorTouchable: {
|
||||
marginVertical: -16,
|
||||
marginHorizontal: -20,
|
||||
marginTop: 6,
|
||||
paddingVertical: 16,
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 10,
|
||||
},
|
||||
error: {
|
||||
flexDirection: 'row',
|
||||
},
|
||||
icon: {
|
||||
marginRight: 10,
|
||||
color: TEXT_COLOUR_DARK,
|
||||
},
|
||||
errorText: {
|
||||
color: TEXT_COLOUR_DARK,
|
||||
},
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import React from 'react';
|
||||
import { Image, StyleSheet, Text, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import ipc from '../ipc.js';
|
||||
import { useAccentColour, useColourScheme, User } from '../util.js';
|
||||
import { ActiveEvent } from '../../../api/coral-types.js';
|
||||
|
|
@ -8,34 +9,38 @@ import Section from './section.js';
|
|||
import { Button } from '../components/index.js';
|
||||
|
||||
export default function Event(props: {
|
||||
user: User;
|
||||
user: User<true>;
|
||||
event: ActiveEvent;
|
||||
loading?: boolean;
|
||||
error?: Error;
|
||||
}) {
|
||||
const theme = useColourScheme() === 'light' ? light : dark;
|
||||
const accent_colour = useAccentColour();
|
||||
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'event_section' });
|
||||
|
||||
const event_members = props.event.members.filter(m => m.isPlaying).length;
|
||||
const voip_members = props.event.members.filter(m => m.isJoinedVoip).length;
|
||||
|
||||
return <Section title="Voice chat" loading={props.loading} error={props.error}>
|
||||
return <Section title={t('title')} loading={props.loading} error={props.error}
|
||||
errorKey={[props.user.nsotoken, 'activeevent']}
|
||||
>
|
||||
<View style={styles.content}>
|
||||
<Image source={{uri: props.event.imageUri, width: 100, height: 100}} style={styles.image} />
|
||||
|
||||
<View style={styles.detail}>
|
||||
<Text style={[styles.eventName, theme.text]}>{props.event.name}</Text>
|
||||
<Text style={[styles.eventMembers, theme.text]}>
|
||||
{event_members} in game, {voip_members} in voice chat
|
||||
{props.event.members.length > 1 ? ' of ' + props.event.members.length + ' members' : ''}
|
||||
{props.event.members.length > 1 ?
|
||||
t('members_with_total', {event: event_members, voip: voip_members, total: props.event.members.length}) :
|
||||
t('members', {event: event_members, voip: voip_members})}
|
||||
</Text>
|
||||
|
||||
<Text style={[styles.eventInstruction, theme.text]}>
|
||||
Use the Nintendo Switch Online app on iOS or Android to {voip_members ? 'join' : 'start'} voice chat.
|
||||
{t(voip_members ? 'app_join' : 'app_start')}
|
||||
</Text>
|
||||
|
||||
{props.event.shareUri ? <View style={styles.shareButton}>
|
||||
<Button title="Share" onPress={() => ipc.share({urls: [props.event.shareUri]})}
|
||||
<Button title={t('share')} onPress={() => ipc.share({urls: [props.event.shareUri]})}
|
||||
color={'#' + accent_colour} />
|
||||
</View> : null}
|
||||
</View>
|
||||
|
|
|
|||
|
|
@ -1,58 +1,62 @@
|
|||
import React, { useCallback } from 'react';
|
||||
import { Image, ImageStyle, Platform, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
|
||||
import { Trans, useTranslation } from 'react-i18next';
|
||||
import ipc from '../ipc.js';
|
||||
import { useAccentColour, useColourScheme, User, useTimeSince } from '../util.js';
|
||||
import { Friend, Presence, PresenceState } from '../../../api/coral-types.js';
|
||||
import { Friend_4, Presence, PresenceState } from '../../../api/coral-types.js';
|
||||
import { TEXT_COLOUR_ACTIVE, TEXT_COLOUR_DARK, TEXT_COLOUR_LIGHT } from '../constants.js';
|
||||
import Section, { HEADER_SIZE } from './section.js';
|
||||
import AddOutline from '../components/icons/add-outline.js';
|
||||
import { FriendCode } from '../components/index.js';
|
||||
|
||||
export default function Friends(props: {
|
||||
user: User;
|
||||
friends: Friend[];
|
||||
user: User<true>;
|
||||
friends: Friend_4[];
|
||||
loading?: boolean;
|
||||
error?: Error;
|
||||
}) {
|
||||
const theme = useColourScheme() === 'light' ? light : dark;
|
||||
const accent_colour = useAccentColour();
|
||||
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'friends_section' });
|
||||
|
||||
const showAddFriendModal = useCallback(() => {
|
||||
ipc.showAddFriendModal({user: props.user.user.id});
|
||||
}, [props.user.user.id]);
|
||||
|
||||
const header_buttons = <TouchableOpacity onPress={showAddFriendModal} style={styles.iconTouchable}>
|
||||
<Text style={[styles.icon, {color: '#' + accent_colour}]}><AddOutline /></Text>
|
||||
<Text style={[styles.icon, {color: '#' + accent_colour}]}><AddOutline title={t('add')!} /></Text>
|
||||
</TouchableOpacity>;
|
||||
|
||||
const onFriendCodeContextMenu = useCallback(() => {
|
||||
ipc.showFriendCodeMenu(props.user.nso!.nsoAccount.user.links.friendCode);
|
||||
}, [ipc, props.user.nso?.nsoAccount.user.links.friendCode]);
|
||||
|
||||
const fc = <Text
|
||||
style={styles.friendCodeValue}
|
||||
// @ts-expect-error react-native-web
|
||||
onContextMenu={onFriendCodeContextMenu}
|
||||
>SW-{props.user.nso!.nsoAccount.user.links.friendCode.id}</Text>;
|
||||
|
||||
return <Section title="Friends" loading={props.loading} error={props.error} headerButtons={header_buttons}>
|
||||
return <Section title={t('title')} loading={props.loading} error={props.error}
|
||||
errorKey={[props.user.nsotoken, 'friends']}
|
||||
headerButtons={header_buttons}
|
||||
>
|
||||
{props.friends.length ? <ScrollView horizontal>
|
||||
<View style={styles.content}>
|
||||
{props.friends.map(f => <Friend key={f.nsaId} friend={f} user={props.user} />)}
|
||||
</View>
|
||||
</ScrollView> : <View style={styles.noFriends}>
|
||||
<Text style={[styles.noFriendsText, theme.text]}>Add friends using a Nintendo Switch console.</Text>
|
||||
<Text style={[styles.noFriendsText, styles.noFriendsFriendCodeText, theme.text]}>Your friend code: {fc}</Text>
|
||||
<Text style={[styles.noFriendsText, theme.text]}>{t('no_friends')}</Text>
|
||||
<Text style={[styles.noFriendsText, styles.noFriendsFriendCodeText, theme.text]}>
|
||||
<Trans i18nKey="main_window:friends_section.friend_code">
|
||||
<FriendCode friendcode={props.user.nso!.nsoAccount.user.links.friendCode} />
|
||||
</Trans>
|
||||
</Text>
|
||||
</View>}
|
||||
|
||||
{props.friends.length ? <View style={styles.footer}>
|
||||
<Text style={[styles.friendCode, theme.text]}>Your friend code: {fc}</Text>
|
||||
<Text style={[styles.friendCode, theme.text]}>
|
||||
<Trans i18nKey="main_window:friends_section.friend_code">
|
||||
<FriendCode friendcode={props.user.nso!.nsoAccount.user.links.friendCode} />
|
||||
</Trans>
|
||||
</Text>
|
||||
</View> : null}
|
||||
</Section>;
|
||||
}
|
||||
|
||||
function Friend(props: {
|
||||
friend: Friend;
|
||||
user?: User;
|
||||
friend: Friend_4;
|
||||
user?: User<true>;
|
||||
}) {
|
||||
const theme = useColourScheme() === 'light' ? light : dark;
|
||||
|
||||
|
|
@ -69,7 +73,7 @@ function Friend(props: {
|
|||
const game = 'name' in props.friend.presence.game ? props.friend.presence.game : null;
|
||||
|
||||
const content = <View style={styles.friend}>
|
||||
<Image source={{uri: props.friend.imageUri, width: 50, height: 50}} style={styles.friendImage as ImageStyle} />
|
||||
<Image source={{uri: props.friend.image2Uri, width: 50, height: 50}} style={styles.friendImage as ImageStyle} />
|
||||
{game ? <Image source={{uri: game.imageUri, width: 20, height: 20}} style={styles.presenceImage as ImageStyle} /> : null}
|
||||
|
||||
<Text style={theme.text}>{props.friend.name}</Text>
|
||||
|
|
@ -94,15 +98,16 @@ function FriendPresence(props: {
|
|||
presence: Presence;
|
||||
}) {
|
||||
const theme = useColourScheme() === 'light' ? light : dark;
|
||||
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'friends_section' });
|
||||
|
||||
const logout = props.presence.logoutAt ? new Date(props.presence.logoutAt * 1000) : null;
|
||||
const since_logout = useTimeSince(logout ?? new Date(0), true);
|
||||
const since_logout = useTimeSince(logout ?? new Date(0), true, i18n.getFixedT(null, 'time_since'));
|
||||
|
||||
if (props.presence.state === PresenceState.ONLINE || props.presence.state === PresenceState.PLAYING) {
|
||||
return <Text style={[styles.presenceText, theme.text, styles.presenceTextOnline]}>Playing</Text>;
|
||||
return <Text style={[styles.presenceText, theme.text, styles.presenceTextOnline]}>{t('presence_playing')}</Text>;
|
||||
}
|
||||
|
||||
return <Text style={[styles.presenceText, styles.presenceTextOffline, theme.text]}>{logout ? since_logout : 'Offline'}</Text>;
|
||||
return <Text style={[styles.presenceText, styles.presenceTextOffline, theme.text]}>{logout ? since_logout : t('presence_offline')}</Text>;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
|
|
@ -121,10 +126,6 @@ const styles = StyleSheet.create({
|
|||
fontSize: 12,
|
||||
opacity: 0.7,
|
||||
},
|
||||
friendCodeValue: {
|
||||
// @ts-expect-error
|
||||
userSelect: 'all',
|
||||
},
|
||||
content: {
|
||||
paddingBottom: 16,
|
||||
paddingLeft: ipc.platform === 'win32' ? 24 : 20,
|
||||
|
|
|
|||
|
|
@ -1,12 +1,14 @@
|
|||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { ScrollView, StyleSheet, Text, TouchableOpacity, useColorScheme, View } from 'react-native';
|
||||
import { CheckBox } from 'react-native-web';
|
||||
import { ScrollView, StyleSheet, Text, useColorScheme, View } from 'react-native';
|
||||
import ipc, { events } from '../ipc.js';
|
||||
import { AccentColourContext, getAccounts, Root, useAsync, useEventListener } from '../util.js';
|
||||
import { getAccounts, Root, useAsync, useEventListener } from '../util.js';
|
||||
import Sidebar from './sidebar.js';
|
||||
import Update from './update.js';
|
||||
import Main from './main.js';
|
||||
import { BACKGROUND_COLOUR_MAIN_DARK, BACKGROUND_COLOUR_MAIN_LIGHT, BACKGROUND_COLOUR_SECONDARY_DARK, BACKGROUND_COLOUR_SECONDARY_LIGHT, TEXT_COLOUR_DARK, TEXT_COLOUR_LIGHT } from '../constants.js';
|
||||
import StatusUpdates from './status-updates.js';
|
||||
|
||||
const REFRESH_INTERVAL = 30 * 1000; // 30 seconds
|
||||
|
||||
export interface AppProps {
|
||||
vibrancy?: boolean;
|
||||
|
|
@ -25,7 +27,8 @@ export default function App(props: AppProps) {
|
|||
const [selectedUserId, setSelectedUserId] = useState<string | undefined>(undefined);
|
||||
const selectedUser = useMemo(() => users?.find(u => u.user.id === selectedUserId), [users, selectedUserId]);
|
||||
|
||||
const [auto_refresh, setAutoRefresh] = useState<number | undefined>(undefined);
|
||||
const [focused, setFocused] = useState(ipc.getWindowFocused());
|
||||
useEventListener(events, 'window:focused', setFocused, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedUser) setSelectedUserId(users?.[0]?.user.id);
|
||||
|
|
@ -35,31 +38,19 @@ export default function App(props: AppProps) {
|
|||
titleUser={selectedUser}
|
||||
vibrancy={props.vibrancy}
|
||||
style={[styles.app, !props.vibrancy ? theme.appNoVibrancy : null]}
|
||||
i18nNamespace={['main_window', 'time_since']}
|
||||
>
|
||||
<Sidebar users={users} selectedUser={selectedUserId} onSelectUser={setSelectedUserId}
|
||||
insetTitleBarControls={props.insetTitleBarControls}
|
||||
>
|
||||
<View style={[styles.content, styles.checkboxContainer]}>
|
||||
<AccentColourContext.Consumer children={accent_colour => (
|
||||
<CheckBox
|
||||
value={!!auto_refresh}
|
||||
onValueChange={v => setAutoRefresh(v ? 30 * 1000 : undefined)}
|
||||
color={'#' + accent_colour}
|
||||
style={styles.checkbox}
|
||||
/>
|
||||
)} />
|
||||
<TouchableOpacity onPress={() => setAutoRefresh(auto_refresh ? undefined : 30 * 1000)}>
|
||||
<Text style={theme.text}>Enable auto refresh</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</Sidebar>
|
||||
/>
|
||||
|
||||
<View style={[styles.main, theme.main]}>
|
||||
<ScrollView style={styles.scroller} contentContainerStyle={styles.scrollerContent}>
|
||||
<StatusUpdates />
|
||||
<Update />
|
||||
|
||||
{selectedUser ? <Main key={selectedUser.user.id} user={selectedUser}
|
||||
autoRefresh={auto_refresh} /> : null}
|
||||
autoRefresh={focused ? REFRESH_INTERVAL : undefined} /> : null}
|
||||
</ScrollView>
|
||||
</View>
|
||||
</Root>;
|
||||
|
|
@ -78,19 +69,6 @@ const styles = StyleSheet.create({
|
|||
scrollerContent: {
|
||||
flex: 1,
|
||||
},
|
||||
content: {
|
||||
paddingVertical: 16,
|
||||
paddingHorizontal: 20,
|
||||
},
|
||||
checkboxContainer: {
|
||||
flex: 1,
|
||||
marginRight: 20,
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
},
|
||||
checkbox: {
|
||||
marginRight: 10,
|
||||
},
|
||||
});
|
||||
|
||||
const light = StyleSheet.create({
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import React, { useCallback, useEffect } from 'react';
|
||||
import React, { useCallback, useEffect, useState } from 'react';
|
||||
import { ActivityIndicator, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import ipc, { events } from '../ipc.js';
|
||||
import { RequestState, useAccentColour, useAsync, useColourScheme, useEventListener, User } from '../util.js';
|
||||
import Friends from './friends.js';
|
||||
|
|
@ -9,7 +10,6 @@ import Section from './section.js';
|
|||
import { TEXT_COLOUR_DARK, TEXT_COLOUR_LIGHT } from '../constants.js';
|
||||
import SetupDiscordPresence from './discord-setup.js';
|
||||
import { Button } from '../components/index.js';
|
||||
import { hrlist } from '../../../util/misc.js';
|
||||
|
||||
export default function Main(props: {
|
||||
user: User;
|
||||
|
|
@ -17,6 +17,7 @@ export default function Main(props: {
|
|||
}) {
|
||||
const theme = useColourScheme() === 'light' ? light : dark;
|
||||
const accent_colour = useAccentColour();
|
||||
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'main_section' });
|
||||
|
||||
const [announcements, announcements_error, announcements_state] = useAsync(useCallback(() => props.user.nsotoken ?
|
||||
ipc.getCoralAnnouncements(props.user.nsotoken) : Promise.resolve(null), [ipc, props.user.nsotoken]));
|
||||
|
|
@ -27,11 +28,15 @@ export default function Main(props: {
|
|||
const [active_event, active_event_error, active_event_state, forceRefreshActiveEvent] = useAsync(useCallback(() => props.user.nsotoken ?
|
||||
ipc.getCoralActiveEvent(props.user.nsotoken) : Promise.resolve(null), [ipc, props.user.nsotoken]));
|
||||
|
||||
const [last_refresh_at, setLastRefreshAt] = useState(() => Date.now());
|
||||
|
||||
const loading = announcements_state === RequestState.LOADING ||
|
||||
friends_state === RequestState.LOADING ||
|
||||
webservices_state === RequestState.LOADING ||
|
||||
active_event_state === RequestState.LOADING;
|
||||
|
||||
const refresh = useCallback(() => Promise.all([
|
||||
setLastRefreshAt(Date.now()),
|
||||
forceRefreshFriends(), forceRefreshWebServices(), forceRefreshActiveEvent(),
|
||||
]), [forceRefreshFriends, forceRefreshWebServices, forceRefreshActiveEvent]);
|
||||
|
||||
|
|
@ -41,12 +46,17 @@ export default function Main(props: {
|
|||
return () => clearTimeout(timeout);
|
||||
}, [ipc, props.user.nsotoken, loading, props.autoRefresh]);
|
||||
|
||||
useEffect(() => {
|
||||
if (loading || !props.autoRefresh) return;
|
||||
|
||||
// When enabling auto refresh, update now if we haven't updated within the interval
|
||||
if (last_refresh_at + props.autoRefresh < Date.now()) refresh();
|
||||
}, [ipc, props.autoRefresh]);
|
||||
|
||||
useEventListener(events, 'window:refresh', refresh, []);
|
||||
|
||||
const showErrorDetails = useCallback(() => {
|
||||
if (friends_error) alert(friends_error.stack ?? friends_error.message);
|
||||
if (webservices_error) alert(webservices_error.stack ?? webservices_error.message);
|
||||
if (active_event_error) alert(active_event_error.stack ?? active_event_error.message);
|
||||
ipc.showCoralErrors(props.user.nsotoken!, ['friends', 'webservices', 'activeevent']);
|
||||
}, [friends_error, webservices_error, active_event_error]);
|
||||
|
||||
if (!friends || !webservices || !active_event) {
|
||||
|
|
@ -58,18 +68,17 @@ export default function Main(props: {
|
|||
|
||||
if (friends_error || webservices_error || active_event_error) {
|
||||
const errors = [];
|
||||
if (friends_error) errors.push('friends');
|
||||
if (webservices_error) errors.push('game-specific services');
|
||||
if (active_event_error) errors.push('voice chat');
|
||||
const errors_text = hrlist(errors);
|
||||
if (friends_error) errors.push(t('error.message_friends'));
|
||||
if (webservices_error) errors.push(t('error.message_webservices'));
|
||||
if (active_event_error) errors.push(t('error.message_event'));
|
||||
|
||||
return <View style={styles.error}>
|
||||
<Text style={[styles.errorHeader, theme.text]}>Error loading data</Text>
|
||||
<Text style={[styles.errorMessage, theme.text]}>An error occured while loading {errors_text} data.</Text>
|
||||
<Text style={[styles.errorHeader, theme.text]}>{t('error.title')}</Text>
|
||||
<Text style={[styles.errorMessage, theme.text]}>{t('error.message', {errors})}</Text>
|
||||
<View style={styles.errorActions}>
|
||||
<Button title="Retry" onPress={refresh} color={'#' + accent_colour} primary />
|
||||
<Button title={t('error.retry')} onPress={refresh} color={'#' + accent_colour} primary />
|
||||
<TouchableOpacity onPress={showErrorDetails} style={styles.errorViewDetailsTouchable}>
|
||||
<Text style={theme.text}>View details</Text>
|
||||
<Text style={theme.text}>{t('error.view_details')}</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>;
|
||||
|
|
@ -92,14 +101,15 @@ export default function Main(props: {
|
|||
function MoonOnlyUser() {
|
||||
const theme = useColourScheme() === 'light' ? light : dark;
|
||||
const accent_colour = useAccentColour();
|
||||
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'main_section.moon_only_user' });
|
||||
|
||||
return <Section title="Nintendo Switch Online">
|
||||
return <Section title={t('title')}>
|
||||
<View style={styles.moonOnlyUser}>
|
||||
<Text style={[styles.moonOnlyUserText, theme.text]}>This user is signed in to the Nintendo Switch Parental Controls app, but not the Nintendo Switch Online app.</Text>
|
||||
<Text style={[styles.moonOnlyUserText, theme.text]}>Login to the Nintendo Switch Online app to view details here, or use the nxapi command to access Parental Controls data.</Text>
|
||||
<Text style={[styles.moonOnlyUserText, theme.text]}>{t('desc_1')}</Text>
|
||||
<Text style={[styles.moonOnlyUserText, theme.text]}>{t('desc_2')}</Text>
|
||||
|
||||
<View style={styles.moonOnlyUserButton}>
|
||||
<Button title="Login" onPress={() => ipc.addCoralAccount()} color={'#' + accent_colour} primary />
|
||||
<Button title={t('login')} onPress={() => ipc.addCoralAccount()} color={'#' + accent_colour} primary />
|
||||
</View>
|
||||
</View>
|
||||
</Section>;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
import React, { useCallback } from 'react';
|
||||
import { ActivityIndicator, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
|
||||
import { useAccentColour, useColourScheme } from '../util.js';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { BORDER_COLOUR_LIGHT, BORDER_COLOUR_SECONDARY_DARK, TEXT_COLOUR_DARK, TEXT_COLOUR_LIGHT } from '../constants.js';
|
||||
import type { CachedErrorKey } from '../../main/ipc.js';
|
||||
import ipc from '../ipc.js';
|
||||
import Warning from '../components/icons/warning.js';
|
||||
|
||||
|
|
@ -9,13 +11,15 @@ export default function Section(props: React.PropsWithChildren<{
|
|||
title: string;
|
||||
loading?: boolean;
|
||||
error?: Error;
|
||||
errorKey?: [string, CachedErrorKey];
|
||||
headerButtons?: React.ReactNode;
|
||||
}>) {
|
||||
const theme = useColourScheme() === 'light' ? light : dark;
|
||||
const accent_colour = useAccentColour();
|
||||
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'main_section' });
|
||||
|
||||
const showErrorDetails = useCallback(() => {
|
||||
alert(props.error);
|
||||
props.errorKey ? ipc.showCoralErrors(...props.errorKey) : alert(props.error);
|
||||
}, [props.error]);
|
||||
|
||||
return <View style={[styles.container, theme.container]}>
|
||||
|
|
@ -24,7 +28,7 @@ export default function Section(props: React.PropsWithChildren<{
|
|||
{props.loading ? <ActivityIndicator style={styles.activityIndicator} size={HEADER_SIZE}
|
||||
color={'#' + accent_colour} /> :
|
||||
props.error ? <TouchableOpacity onPress={showErrorDetails} style={styles.iconTouchable}>
|
||||
<Text style={[styles.icon, {color: '#' + accent_colour}]}><Warning /></Text>
|
||||
<Text style={[styles.icon, {color: '#' + accent_colour}]}><Warning title={t('section_error')!} /></Text>
|
||||
</TouchableOpacity> : null}
|
||||
{props.headerButtons}
|
||||
</View>
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import React, { useCallback } from 'react';
|
||||
import { Image, ImageURISource, Platform, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import ipc from '../ipc.js';
|
||||
import { RequestState, useActiveDiscordPresence, useActiveDiscordUser, useColourScheme, useDiscordPresenceSource, User } from '../util.js';
|
||||
import DiscordPresenceSource from './discord.js';
|
||||
|
|
@ -13,6 +14,7 @@ export default function Sidebar(props: {
|
|||
children?: React.ReactNode;
|
||||
}) {
|
||||
const theme = useColourScheme() === 'light' ? light : dark;
|
||||
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'sidebar' });
|
||||
|
||||
const [discord_presence_source, discord_presence_source_state] = useDiscordPresenceSource();
|
||||
const presence = useActiveDiscordPresence();
|
||||
|
|
@ -40,13 +42,13 @@ export default function Sidebar(props: {
|
|||
</View> : null}
|
||||
|
||||
{props.users ? <TouchableOpacity onPress={() => ipc.showAddUserMenu()} style={styles.addUser}>
|
||||
<Text style={theme.text}>Add user</Text>
|
||||
<Text style={theme.text}>{t('add_user')}</Text>
|
||||
</TouchableOpacity> : null}
|
||||
|
||||
{discord_presence_source_state === RequestState.LOADED && !discord_presence_source ? <TouchableOpacity
|
||||
onPress={() => ipc.showDiscordModal()} style={styles.discordSetup}
|
||||
>
|
||||
<Text style={theme.text}>Set up Discord Rich Presence</Text>
|
||||
<Text style={theme.text}>{t('discord_setup')}</Text>
|
||||
</TouchableOpacity> : null}
|
||||
|
||||
{props.children}
|
||||
|
|
@ -66,15 +68,24 @@ function User(props: {
|
|||
ipc.showUserMenu(props.user.user, props.user.nso?.nsoAccount.user);
|
||||
}, [ipc, props.user.user, props.user.nso?.nsoAccount.user]);
|
||||
|
||||
const miiImageSource: ImageURISource = props.user.user.mii ? {
|
||||
uri: 'https://' + props.user.user.mii.imageOrigin + '/2.0.0/mii_images/' +
|
||||
const mii_url = new URL(props.user.user.iconUri ?? (props.user.user.mii ?
|
||||
'https://' + props.user.user.mii.imageOrigin + '/2.0.0/mii_images/' +
|
||||
props.user.user.mii.id + '/' +
|
||||
props.user.user.mii.etag + '.png' +
|
||||
'?type=face&width=140&bgColor=DFDFDFFF',
|
||||
width: 32,
|
||||
height: 32,
|
||||
} : {
|
||||
uri: 'https://cdn.accounts.nintendo.com/account/images/common/defaults/mii.png',
|
||||
props.user.user.mii.etag + '.png' :
|
||||
'https://cdn.accounts.nintendo.com/account/images/common/defaults/mii.png'));
|
||||
|
||||
if (mii_url.origin === 'https://cdn-mii.accounts.nintendo.com' ||
|
||||
props.user.user.mii && mii_url.hostname === props.user.user.mii.imageOrigin
|
||||
) {
|
||||
mii_url.searchParams.append('type', 'face');
|
||||
mii_url.searchParams.append('width', '140');
|
||||
mii_url.searchParams.append('bgColor', 'DFDFDFFF');
|
||||
} else {
|
||||
mii_url.href = 'https://cdn.accounts.nintendo.com/account/images/common/defaults/mii.png';
|
||||
}
|
||||
|
||||
const miiImageSource: ImageURISource = {
|
||||
uri: mii_url.toString(),
|
||||
width: 32,
|
||||
height: 32,
|
||||
};
|
||||
|
|
@ -90,7 +101,8 @@ function User(props: {
|
|||
|
||||
{props.user.nso ? <View style={styles.userNso}>
|
||||
<View style={styles.userNsoImage}>
|
||||
<Image source={{uri: props.user.nso.nsoAccount.user.imageUri, width: 16, height: 16}} />
|
||||
<Image source={{uri: props.user.nso.nsoAccount.user.image2Uri ??
|
||||
props.user.nso.nsoAccount.user.imageUri, width: 16, height: 16}} />
|
||||
</View>
|
||||
|
||||
<Text style={[styles.userNsoName, theme.text]}>{props.user.nso.nsoAccount.user.name}</Text>
|
||||
|
|
|
|||
48
src/app/browser/main/status-updates.tsx
Normal file
48
src/app/browser/main/status-updates.tsx
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import React, { useEffect, useState } from 'react';
|
||||
import { StyleSheet, Text, View } from 'react-native';
|
||||
import ipc from '../ipc.js';
|
||||
import { useAccentColour, useEventListener } from '../util.js';
|
||||
import type { StatusUpdate } from '../../../common/status.js';
|
||||
import { BORDER_COLOUR_SECONDARY_DARK, TEXT_COLOUR_DARK, UPDATE_COLOUR } from '../constants.js';
|
||||
import { Button } from '../components/index.js';
|
||||
|
||||
enum StatusUpdateFlag {
|
||||
HIDDEN = 0,
|
||||
}
|
||||
|
||||
export default function StatusUpdates() {
|
||||
const accent_colour = useAccentColour();
|
||||
|
||||
const [status_updates, setStatusUpdateData] = useState<StatusUpdate[] | null>(null);
|
||||
useEffect(() => (ipc.getStatusUpdateData().then(setStatusUpdateData), undefined), [ipc]);
|
||||
useEventListener(ipc.events, 'status-updates', setStatusUpdateData, [ipc.events]);
|
||||
|
||||
return status_updates?.map(status_update => status_update.flags & (1 << StatusUpdateFlag.HIDDEN) ? null : <View style={[styles.container, status_update.colour ? {backgroundColor: status_update.colour} : null]}>
|
||||
<Text style={styles.updateText}>{status_update.content}</Text>
|
||||
{status_update.action ? <View style={styles.updateButton}>
|
||||
<Button title={status_update.action.label}
|
||||
onPress={() => ipc.openExternalUrl(status_update.action!.url)}
|
||||
color={'#' + accent_colour} />
|
||||
</View> : null}
|
||||
</View>);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
backgroundColor: UPDATE_COLOUR,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: BORDER_COLOUR_SECONDARY_DARK,
|
||||
paddingVertical: 8,
|
||||
paddingHorizontal: 20,
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
},
|
||||
updateText: {
|
||||
marginVertical: 4,
|
||||
flex: 1,
|
||||
color: TEXT_COLOUR_DARK,
|
||||
},
|
||||
updateButton: {
|
||||
marginLeft: 14,
|
||||
},
|
||||
});
|
||||
|
|
@ -1,29 +1,44 @@
|
|||
import React, { useEffect, useState } from 'react';
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { StyleSheet, Text, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import ipc from '../ipc.js';
|
||||
import { useAccentColour, useEventListener } from '../util.js';
|
||||
import type { UpdateCacheData } from '../../../common/update.js';
|
||||
import { TEXT_COLOUR_DARK, UPDATE_COLOUR } from '../constants.js';
|
||||
import type { StatusUpdate } from '../../../common/status.js';
|
||||
import { BORDER_COLOUR_SECONDARY_DARK, TEXT_COLOUR_DARK, UPDATE_COLOUR } from '../constants.js';
|
||||
import { Button } from '../components/index.js';
|
||||
|
||||
enum StatusUpdateFlag {
|
||||
SUPPRESS_UPDATE_BANNER = 1,
|
||||
}
|
||||
|
||||
export default function Update() {
|
||||
const accent_colour = useAccentColour();
|
||||
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'update' });
|
||||
|
||||
const [update, setUpdateData] = useState<UpdateCacheData | null>(null);
|
||||
useEffect(() => (ipc.getUpdateData().then(setUpdateData), undefined), [ipc]);
|
||||
useEventListener(ipc.events, 'nxapi:update:latest', setUpdateData, [ipc.events]);
|
||||
|
||||
return update && 'update_available' in update && update.update_available ? <View style={styles.container}>
|
||||
<Text style={styles.updateText}>Update available: {update.latest.name}</Text>
|
||||
const [status_updates, setStatusUpdateData] = useState<StatusUpdate[] | null>(null);
|
||||
useEffect(() => (ipc.getStatusUpdateData().then(setStatusUpdateData), undefined), [ipc]);
|
||||
useEventListener(ipc.events, 'status-updates', setStatusUpdateData, [ipc.events]);
|
||||
|
||||
const status_update_suppress_update_banner = useMemo(() =>
|
||||
status_updates?.find(s => s.flags & (1 << StatusUpdateFlag.SUPPRESS_UPDATE_BANNER)),
|
||||
[status_updates]);
|
||||
|
||||
return update && 'update_available' in update && update.update_available && !status_update_suppress_update_banner ? <View style={styles.container}>
|
||||
<Text style={styles.updateText}>{t('update_available', {name: update.latest.name})}</Text>
|
||||
<View style={styles.updateButton}>
|
||||
<Button title="Download"
|
||||
<Button title={t('download')}
|
||||
onPress={() => ipc.openExternalUrl(update.latest.html_url)}
|
||||
color={'#' + accent_colour} />
|
||||
</View>
|
||||
</View> : update && 'error_message' in update ? <View style={styles.container}>
|
||||
<Text style={styles.updateText}>Error checking for updates: {update.error_message}</Text>
|
||||
<Text style={styles.updateText}>{t('error', {message: update.error_message})}</Text>
|
||||
<View style={styles.updateButton}>
|
||||
<Button title="Try again"
|
||||
<Button title={t('retry')}
|
||||
onPress={() => (setUpdateData(null), ipc.checkUpdates())}
|
||||
color={'#' + accent_colour} />
|
||||
</View>
|
||||
|
|
@ -33,6 +48,8 @@ export default function Update() {
|
|||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
backgroundColor: UPDATE_COLOUR,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: BORDER_COLOUR_SECONDARY_DARK,
|
||||
paddingVertical: 8,
|
||||
paddingHorizontal: 20,
|
||||
flexDirection: 'row',
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import React from 'react';
|
||||
import { Image, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import ipc from '../ipc.js';
|
||||
import { useColourScheme, User } from '../util.js';
|
||||
import { WebService } from '../../../api/coral-types.js';
|
||||
|
|
@ -7,14 +8,18 @@ import { TEXT_COLOUR_DARK, TEXT_COLOUR_LIGHT } from '../constants.js';
|
|||
import Section from './section.js';
|
||||
|
||||
export default function WebServices(props: {
|
||||
user: User;
|
||||
user: User<true>;
|
||||
webservices: WebService[];
|
||||
loading?: boolean;
|
||||
error?: Error;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'webservices_section' });
|
||||
|
||||
if (!props.webservices.length) return null;
|
||||
|
||||
return <Section title="Game-specific services" loading={props.loading} error={props.error}>
|
||||
return <Section title={t('title')} loading={props.loading} error={props.error}
|
||||
errorKey={[props.user.nsotoken, 'webservices']}
|
||||
>
|
||||
<ScrollView horizontal>
|
||||
<View style={styles.content}>
|
||||
{props.webservices.map(g => <WebService key={g.id} webservice={g} token={props.user.nsotoken} />)}
|
||||
|
|
|
|||
|
|
@ -1,26 +1,37 @@
|
|||
import React, { useCallback, useEffect, useMemo, useReducer, useState } from 'react';
|
||||
import { StyleSheet, Text, TextInput, TouchableHighlight, TouchableOpacity, useColorScheme, View } from 'react-native';
|
||||
import React, { useCallback, useEffect, useReducer, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';
|
||||
import { CheckBox, Picker } from 'react-native-web';
|
||||
import { DiscordPresencePlayTime } from '../../../discord/types.js';
|
||||
import { Button } from '../components/index.js';
|
||||
import { DEFAULT_ACCENT_COLOUR, HIGHLIGHT_COLOUR_DARK, HIGHLIGHT_COLOUR_LIGHT, TEXT_COLOUR_DARK, TEXT_COLOUR_LIGHT } from '../constants.js';
|
||||
import ipc, { events } from '../ipc.js';
|
||||
import { getAccounts, RequestState, Root, useAsync, useDiscordPresenceSource, useEventListener } from '../util.js';
|
||||
import { getAccounts, RequestState, Root, useAccentColour, useAsync, useColourScheme, useDiscordPresenceSource, useEventListener } from '../util.js';
|
||||
|
||||
export interface PreferencesProps {}
|
||||
|
||||
export default function Preferences(props: PreferencesProps) {
|
||||
const colour_scheme = useColorScheme();
|
||||
const theme = colour_scheme === 'light' ? light : dark;
|
||||
export default function PreferencesWindow(props: PreferencesProps) {
|
||||
return <Root
|
||||
title={i18n => i18n.t('preferences_window:title')} scrollable autoresize
|
||||
i18nNamespace="preferences_window"
|
||||
>
|
||||
<Preferences />
|
||||
</Root>;
|
||||
}
|
||||
|
||||
const [accent_colour, setAccentColour] = React.useState(() => ipc.getAccentColour());
|
||||
useEventListener(events, 'systemPreferences:accent-colour', setAccentColour, []);
|
||||
function _Preferences(props: {
|
||||
}) {
|
||||
const theme = useColourScheme() === 'light' ? light : dark;
|
||||
const accent_colour = useAccentColour();
|
||||
const { t, i18n, ready } = useTranslation('preferences_window');
|
||||
|
||||
const [users, ,, forceRefreshAccounts] = useAsync(useCallback(() => getAccounts(), [ipc]));
|
||||
useEventListener(events, 'update-nintendo-accounts', forceRefreshAccounts, []);
|
||||
|
||||
const [login_item, ,, forceRefreshLoginItem] = useAsync(useCallback(() => ipc.getLoginItemSettings(), [ipc]));
|
||||
|
||||
const [show_error_alerts, , show_error_alerts_state, forceRefreshErrorAlerts] = useAsync(useCallback(() => ipc.getShowErrorAlerts(), [ipc]));
|
||||
|
||||
const setOpenAtLogin = useCallback(async (open_at_login: boolean | 'mixed') => {
|
||||
await ipc.setLoginItemSettings({...login_item!, startup_enabled: !!open_at_login});
|
||||
forceRefreshLoginItem();
|
||||
|
|
@ -30,6 +41,11 @@ export default function Preferences(props: PreferencesProps) {
|
|||
forceRefreshLoginItem();
|
||||
}, [ipc, login_item]);
|
||||
|
||||
const setShowErrorAlerts = useCallback(async (show_error_alerts: boolean | 'mixed') => {
|
||||
await ipc.setShowErrorAlerts(!!show_error_alerts);
|
||||
forceRefreshErrorAlerts();
|
||||
}, [ipc]);
|
||||
|
||||
const [discord_users, discord_users_error, discord_users_state, forceRefreshDiscordUsers] =
|
||||
useAsync(useCallback(() => ipc.getDiscordUsers(), [ipc]));
|
||||
|
||||
|
|
@ -88,197 +104,215 @@ export default function Preferences(props: PreferencesProps) {
|
|||
|
||||
useEventListener(events, 'window:refresh', () => (
|
||||
forceRefreshAccounts(), forceRefreshLoginItem(),
|
||||
forceRefreshDiscordUsers(), forceRefreshDiscordOptions()
|
||||
forceRefreshDiscordUsers(), forceRefreshDiscordOptions(),
|
||||
forceRefreshErrorAlerts()
|
||||
), []);
|
||||
|
||||
if (!users ||
|
||||
!login_item ||
|
||||
!has_ever_loaded_discord_options ||
|
||||
discord_presence_source_state !== RequestState.LOADED
|
||||
discord_presence_source_state !== RequestState.LOADED ||
|
||||
!ready
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const discord_user_picker = [<Picker.Item key="*" label="First discovered" value="*" />];
|
||||
const discord_user_picker = [<Picker.Item key="*" label={t('discord.user_any')!} value="*" />];
|
||||
|
||||
if (discord_options?.user && !discord_users?.find(u => u.id === discord_options.user)) {
|
||||
discord_user_picker.push(<Picker.Item key={discord_options?.user} label={discord_options.user}
|
||||
value={discord_options.user} />);
|
||||
}
|
||||
for (const user of discord_users ?? []) {
|
||||
discord_user_picker.push(<Picker.Item key={user.id} label={user.username + '#' + user.discriminator}
|
||||
discord_user_picker.push(<Picker.Item key={user.id}
|
||||
label={user.username + (user.discriminator && user.discriminator !== '0' ? '#' + user.discriminator : '')}
|
||||
value={user.id} />);
|
||||
}
|
||||
|
||||
return <Root title="Preferences" scrollable autoresize>
|
||||
<View style={styles.main}>
|
||||
{/* <Text style={theme.text}>Preferences</Text> */}
|
||||
return <View style={styles.main}>
|
||||
{/* <Text style={theme.text}>Preferences</Text> */}
|
||||
|
||||
{login_item.supported || login_item.startup_enabled ? <View style={styles.section}>
|
||||
<View style={styles.sectionLeft}>
|
||||
<Text style={[styles.label, theme.text]}>Startup</Text>
|
||||
{login_item.supported || login_item.startup_enabled ? <View style={styles.section}>
|
||||
<View style={styles.sectionLeft}>
|
||||
<Text style={[styles.label, theme.text]}>{t('startup.heading')}</Text>
|
||||
</View>
|
||||
<View style={styles.sectionRight}>
|
||||
<View style={styles.checkboxContainer}>
|
||||
<CheckBox
|
||||
value={login_item.startup_enabled}
|
||||
onValueChange={setOpenAtLogin}
|
||||
disabled={!login_item.supported}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}
|
||||
style={styles.checkbox}
|
||||
/>
|
||||
<TouchableOpacity disabled={!login_item.supported} style={styles.checkboxLabel} onPress={() => setOpenAtLogin(!login_item.startup_enabled)}>
|
||||
<Text style={[styles.checkboxLabelText, theme.text]}>{t('startup.login')}</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
<View style={styles.sectionRight}>
|
||||
{/* <Text style={theme.text}>Launch at startup menu here</Text>
|
||||
<Text style={theme.text}>{JSON.stringify(login_item, null, 4)}</Text> */}
|
||||
|
||||
<View
|
||||
style={[styles.checkboxContainer, !login_item.startup_enabled ? styles.disabled : null]}
|
||||
>
|
||||
<CheckBox
|
||||
value={login_item.startup_hidden}
|
||||
onValueChange={setOpenAsHidden}
|
||||
disabled={!login_item.startup_enabled}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}
|
||||
style={styles.checkbox}
|
||||
/>
|
||||
<TouchableOpacity disabled={!login_item.startup_enabled} style={styles.checkboxLabel}
|
||||
onPress={() => setOpenAsHidden(!login_item.startup_hidden)}
|
||||
>
|
||||
<Text style={[styles.checkboxLabelText, theme.text]}>{t('startup.background')}</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
</View> : null}
|
||||
|
||||
{/* <View style={styles.section}>
|
||||
<View style={styles.sectionLeft}>
|
||||
<Text style={[styles.label, theme.text]}>Sleep</Text>
|
||||
</View>
|
||||
<View style={styles.sectionRight}>
|
||||
<Text style={theme.text}>Prevent sleep menu here</Text>
|
||||
</View>
|
||||
</View> */}
|
||||
|
||||
<View style={styles.section}>
|
||||
<View style={styles.sectionLeft}>
|
||||
<Text style={[styles.label, theme.text]}>{t('discord.heading')}</Text>
|
||||
</View>
|
||||
<View style={styles.sectionRight}>
|
||||
<Text style={theme.text}>{t(discord_presence_source ? 'discord.enabled' : 'discord.disabled')}</Text>
|
||||
|
||||
<View style={styles.button}>
|
||||
<Button title={t('discord.setup')}
|
||||
onPress={() => ipc.showDiscordModal({show_preferences_button: false})}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
|
||||
</View>
|
||||
|
||||
<Text style={[styles.header, theme.text]}>{t('discord.user')}</Text>
|
||||
|
||||
<Picker<string> selectedValue={discord_options?.user ?? '*'} onValueChange={setDiscordUser}
|
||||
style={[styles.picker, theme.picker]}
|
||||
enabled={discord_options_state !== RequestState.LOADING &&
|
||||
discord_users_state !== RequestState.LOADING}
|
||||
>{...discord_user_picker}</Picker>
|
||||
|
||||
<Text style={[styles.header, theme.text]}>{t('discord.friend_code')}</Text>
|
||||
<Text style={[styles.help, theme.text]}>{t('discord.friend_code_help')}</Text>
|
||||
|
||||
{is_discord_friend_code_self ? <View style={styles.friendCodeCheckbox}>
|
||||
<View style={styles.checkboxContainer}>
|
||||
<CheckBox
|
||||
value={login_item.startup_enabled}
|
||||
onValueChange={setOpenAtLogin}
|
||||
disabled={!login_item.supported}
|
||||
value={!!discord_options?.friend_code}
|
||||
onValueChange={v => setDiscordFriendCode(v ? discord_friend_code_self : undefined)}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}
|
||||
style={styles.checkbox}
|
||||
/>
|
||||
<TouchableOpacity disabled={!login_item.supported} style={styles.checkboxLabel} onPress={() => setOpenAtLogin(!login_item.startup_enabled)}>
|
||||
<Text style={[styles.checkboxLabelText, theme.text]}>Open at login</Text>
|
||||
<TouchableOpacity style={styles.checkboxLabel} onPress={() => setDiscordFriendCode(discord_options?.friend_code ? undefined : discord_friend_code_self)}>
|
||||
<Text style={theme.text}>{t('discord.friend_code_self')}</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
<View
|
||||
style={[styles.checkboxContainer, !login_item.startup_enabled ? styles.disabled : null]}
|
||||
>
|
||||
<CheckBox
|
||||
value={login_item.startup_hidden}
|
||||
onValueChange={setOpenAsHidden}
|
||||
disabled={!login_item.startup_enabled}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}
|
||||
style={styles.checkbox}
|
||||
/>
|
||||
<TouchableOpacity disabled={!login_item.startup_enabled} style={styles.checkboxLabel}
|
||||
onPress={() => setOpenAsHidden(!login_item.startup_hidden)}
|
||||
>
|
||||
<Text style={[styles.checkboxLabelText, theme.text]}>Open in background</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
<TouchableOpacity style={styles.textLinkTouchable} onPress={() => setIsDiscordFriendCodeSelf(false)}>
|
||||
<Text style={[styles.textLink, theme.text, {color: '#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}]}>
|
||||
{t('discord.friend_code_custom')}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
</View> : <View style={styles.friendCodeInput}>
|
||||
<TextInput value={discord_friend_code} onChangeText={setDiscordFriendCode}
|
||||
placeholder="0000-0000-0000"
|
||||
style={[styles.textInput, theme.textInput]} />
|
||||
</View>}
|
||||
|
||||
<View style={[styles.checkboxContainer, styles.checkboxContainerMargin]}>
|
||||
<CheckBox
|
||||
value={discord_options?.show_console_online ?? false}
|
||||
onValueChange={setDiscordShowConsoleOnline}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}
|
||||
style={styles.checkbox}
|
||||
/>
|
||||
<TouchableOpacity style={styles.checkboxLabel} onPress={() => setDiscordShowConsoleOnline(!discord_options?.show_console_online)}>
|
||||
<Text style={[styles.checkboxLabelText, theme.text]}>{t('discord.inactive_presence')}</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View> : null}
|
||||
<Text style={[styles.help, theme.text]}>{t('discord.inactive_presence_help')}</Text>
|
||||
|
||||
{/* <View style={styles.section}>
|
||||
<View style={styles.sectionLeft}>
|
||||
<Text style={[styles.label, theme.text]}>Sleep</Text>
|
||||
</View>
|
||||
<View style={styles.sectionRight}>
|
||||
<Text style={theme.text}>Prevent sleep menu here</Text>
|
||||
</View>
|
||||
</View> */}
|
||||
<Text style={[styles.header, theme.text]}>{t('discord.play_time')}</Text>
|
||||
|
||||
<View style={styles.section}>
|
||||
<View style={styles.sectionLeft}>
|
||||
<Text style={[styles.label, theme.text]}>Discord Rich Presence</Text>
|
||||
</View>
|
||||
<View style={styles.sectionRight}>
|
||||
<Text style={theme.text}>Discord Rich Presence is {discord_presence_source ? 'en' : 'dis'}abled.</Text>
|
||||
|
||||
<View style={styles.button}>
|
||||
<Button title="Discord Rich Presence setup"
|
||||
onPress={() => ipc.showDiscordModal({show_preferences_button: false})}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
|
||||
</View>
|
||||
|
||||
<Text style={[styles.header, theme.text]}>Discord user</Text>
|
||||
|
||||
<Picker<string> selectedValue={discord_options?.user ?? '*'} onValueChange={setDiscordUser}
|
||||
style={[styles.picker, theme.picker]}
|
||||
enabled={discord_options_state !== RequestState.LOADING &&
|
||||
discord_users_state !== RequestState.LOADING}
|
||||
>{...discord_user_picker}</Picker>
|
||||
|
||||
<Text style={[styles.header, theme.text]}>Friend code</Text>
|
||||
<Text style={[styles.help, theme.text]}>Adding your friend code will also show your Nintendo Switch user icon in Discord.</Text>
|
||||
|
||||
{is_discord_friend_code_self ? <View style={styles.friendCodeCheckbox}>
|
||||
<View style={styles.checkboxContainer}>
|
||||
<CheckBox
|
||||
value={!!discord_options?.friend_code}
|
||||
onValueChange={v => setDiscordFriendCode(v ? discord_friend_code_self : undefined)}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}
|
||||
style={styles.checkbox}
|
||||
/>
|
||||
<TouchableOpacity style={styles.checkboxLabel} onPress={() => setDiscordFriendCode(discord_options?.friend_code ? undefined : discord_friend_code_self)}>
|
||||
<Text style={theme.text}>Share my friend code</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
<TouchableOpacity style={styles.textLinkTouchable} onPress={() => setIsDiscordFriendCodeSelf(false)}>
|
||||
<Text style={[styles.textLink, theme.text, {color: '#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}]}>
|
||||
Set custom friend code
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
</View> : <View style={styles.friendCodeInput}>
|
||||
<TextInput value={discord_friend_code} onChangeText={setDiscordFriendCode}
|
||||
placeholder="0000-0000-0000"
|
||||
style={[styles.textInput, theme.textInput]} />
|
||||
</View>}
|
||||
|
||||
{/* <View style={styles.header} /> */}
|
||||
|
||||
<View style={[styles.checkboxContainer, styles.checkboxContainerMargin]}>
|
||||
<CheckBox
|
||||
value={discord_options?.show_console_online ?? false}
|
||||
onValueChange={setDiscordShowConsoleOnline}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}
|
||||
style={styles.checkbox}
|
||||
/>
|
||||
<TouchableOpacity style={styles.checkboxLabel} onPress={() => setDiscordShowConsoleOnline(!discord_options?.show_console_online)}>
|
||||
<Text style={[styles.checkboxLabelText, theme.text]}>Show inactive presence</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
<Text style={[styles.help, theme.text]}>Shows "Not playing" when a console linked to your account is online, but you are not selected in a game.</Text>
|
||||
|
||||
<Text style={[styles.header, theme.text]}>Play time</Text>
|
||||
|
||||
<Picker<string>
|
||||
selectedValue={'' + (discord_options?.show_play_time ??
|
||||
DiscordPresencePlayTime.DETAILED_PLAY_TIME_SINCE)}
|
||||
onValueChange={v => setDiscordShowPlayTime(parseInt(v))}
|
||||
style={[styles.picker, theme.picker]}
|
||||
enabled={discord_options_state !== RequestState.LOADING}
|
||||
>
|
||||
<Picker.Item key={DiscordPresencePlayTime.HIDDEN} value={DiscordPresencePlayTime.HIDDEN}
|
||||
label="Never show play time" />
|
||||
<Picker.Item key={DiscordPresencePlayTime.NINTENDO} value={DiscordPresencePlayTime.NINTENDO}
|
||||
label="Show play time as it appears on a Nintendo Switch console" />
|
||||
<Picker.Item key={DiscordPresencePlayTime.APPROXIMATE_PLAY_TIME} value={DiscordPresencePlayTime.APPROXIMATE_PLAY_TIME}
|
||||
label="Show approximate play time (nearest 5 hours)" />
|
||||
<Picker.Item key={DiscordPresencePlayTime.APPROXIMATE_PLAY_TIME_SINCE} value={DiscordPresencePlayTime.APPROXIMATE_PLAY_TIME_SINCE}
|
||||
label="Show approximate play time (nearest 5 hours) with first played date" />
|
||||
<Picker.Item key={DiscordPresencePlayTime.HOUR_PLAY_TIME} value={DiscordPresencePlayTime.HOUR_PLAY_TIME}
|
||||
label="Show approximate play time (nearest hour)" />
|
||||
<Picker.Item key={DiscordPresencePlayTime.HOUR_PLAY_TIME_SINCE} value={DiscordPresencePlayTime.HOUR_PLAY_TIME_SINCE}
|
||||
label="Show approximate play time (nearest hour) with first played date" />
|
||||
<Picker.Item key={DiscordPresencePlayTime.DETAILED_PLAY_TIME} value={DiscordPresencePlayTime.DETAILED_PLAY_TIME}
|
||||
label="Show exact play time" />
|
||||
<Picker.Item key={DiscordPresencePlayTime.DETAILED_PLAY_TIME_SINCE} value={DiscordPresencePlayTime.DETAILED_PLAY_TIME_SINCE}
|
||||
label="Show exact play time with first played date" />
|
||||
</Picker>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View style={styles.section}>
|
||||
<View style={styles.sectionLeft}>
|
||||
<Text style={[styles.label, theme.text]}>SplatNet 3</Text>
|
||||
</View>
|
||||
<View style={styles.sectionRight}>
|
||||
<View style={[styles.checkboxContainer]}>
|
||||
<CheckBox
|
||||
value={discord_options?.monitors?.enable_splatnet3_monitoring ?? false}
|
||||
onValueChange={setDiscordEnableSplatNet3Monitor}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}
|
||||
style={styles.checkbox}
|
||||
/>
|
||||
<TouchableOpacity style={styles.checkboxLabel} onPress={() => setDiscordEnableSplatNet3Monitor(!discord_options?.monitors?.enable_splatnet3_monitoring)}>
|
||||
<Text style={[styles.checkboxLabelText, theme.text]}>Enable enhanced Discord Rich Presence for Splatoon 3</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
<Text style={[styles.help, theme.text]}>Uses SplatNet 3 to retrieve additional presence information while playing Splatoon 3. You must be using a secondary Nintendo Account that is friends with your main account to fetch your presence, and the secondary account must be able to access SplatNet 3.</Text>
|
||||
<Text style={[styles.help, theme.text]}>When using a presence URL that returns Splatoon 3 data additional presence information will be shown regardless of this setting.</Text>
|
||||
</View>
|
||||
<Picker<string>
|
||||
selectedValue={'' + (discord_options?.show_play_time ??
|
||||
DiscordPresencePlayTime.DETAILED_PLAY_TIME_SINCE)}
|
||||
onValueChange={v => setDiscordShowPlayTime(parseInt(v))}
|
||||
style={[styles.picker, theme.picker]}
|
||||
enabled={discord_options_state !== RequestState.LOADING}
|
||||
>
|
||||
<Picker.Item key={DiscordPresencePlayTime.HIDDEN} value={DiscordPresencePlayTime.HIDDEN}
|
||||
label={t('discord.play_time_hidden')!} />
|
||||
<Picker.Item key={DiscordPresencePlayTime.NINTENDO} value={DiscordPresencePlayTime.NINTENDO}
|
||||
label={t('discord.play_time_nintendo')!} />
|
||||
<Picker.Item key={DiscordPresencePlayTime.APPROXIMATE_PLAY_TIME} value={DiscordPresencePlayTime.APPROXIMATE_PLAY_TIME}
|
||||
label={t('discord.play_time_approximate_play_time')!} />
|
||||
<Picker.Item key={DiscordPresencePlayTime.APPROXIMATE_PLAY_TIME_SINCE} value={DiscordPresencePlayTime.APPROXIMATE_PLAY_TIME_SINCE}
|
||||
label={t('discord.play_time_approximate_play_time_since')!} />
|
||||
<Picker.Item key={DiscordPresencePlayTime.HOUR_PLAY_TIME} value={DiscordPresencePlayTime.HOUR_PLAY_TIME}
|
||||
label={t('discord.play_time_hour_play_time')!} />
|
||||
<Picker.Item key={DiscordPresencePlayTime.HOUR_PLAY_TIME_SINCE} value={DiscordPresencePlayTime.HOUR_PLAY_TIME_SINCE}
|
||||
label={t('discord.play_time_hour_play_time_since')!} />
|
||||
<Picker.Item key={DiscordPresencePlayTime.DETAILED_PLAY_TIME} value={DiscordPresencePlayTime.DETAILED_PLAY_TIME}
|
||||
label={t('discord.play_time_detailed_play_time')!} />
|
||||
<Picker.Item key={DiscordPresencePlayTime.DETAILED_PLAY_TIME_SINCE} value={DiscordPresencePlayTime.DETAILED_PLAY_TIME_SINCE}
|
||||
label={t('discord.play_time_detailed_play_time_since')!} />
|
||||
</Picker>
|
||||
</View>
|
||||
</View>
|
||||
</Root>;
|
||||
|
||||
<View style={styles.section}>
|
||||
<View style={styles.sectionLeft}>
|
||||
<Text style={[styles.label, theme.text]}>{t('splatnet3.heading')}</Text>
|
||||
</View>
|
||||
<View style={styles.sectionRight}>
|
||||
<View style={[styles.checkboxContainer]}>
|
||||
<CheckBox
|
||||
value={discord_options?.monitors?.enable_splatnet3_monitoring ?? false}
|
||||
onValueChange={setDiscordEnableSplatNet3Monitor}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}
|
||||
style={styles.checkbox}
|
||||
/>
|
||||
<TouchableOpacity style={styles.checkboxLabel} onPress={() => setDiscordEnableSplatNet3Monitor(!discord_options?.monitors?.enable_splatnet3_monitoring)}>
|
||||
<Text style={[styles.checkboxLabelText, theme.text]}>{t('splatnet3.discord')}</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
<Text style={[styles.help, theme.text]}>{t('splatnet3.discord_help_1')}</Text>
|
||||
<Text style={[styles.help, theme.text]}>{t('splatnet3.discord_help_2')}</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View style={styles.section}>
|
||||
<View style={styles.sectionLeft}>
|
||||
<Text style={[styles.label, theme.text]}>{t('miscellaneous.heading')}</Text>
|
||||
</View>
|
||||
<View style={styles.sectionRight}>
|
||||
<View style={[styles.checkboxContainer]}>
|
||||
<CheckBox
|
||||
value={show_error_alerts ?? true}
|
||||
onValueChange={setShowErrorAlerts}
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}
|
||||
style={styles.checkbox}
|
||||
/>
|
||||
<TouchableOpacity style={styles.checkboxLabel} onPress={() => setShowErrorAlerts(!(show_error_alerts ?? true))}>
|
||||
<Text style={[styles.checkboxLabelText, theme.text]}>{t('miscellaneous.show_error_alerts')}</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
<Text style={[styles.help, theme.text]}>{t('miscellaneous.show_error_alerts_help')}</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>;
|
||||
}
|
||||
|
||||
const Preferences = React.memo(_Preferences);
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
loading: {
|
||||
flex: 1,
|
||||
|
|
|
|||
4
src/app/browser/react-native-web.d.ts
vendored
4
src/app/browser/react-native-web.d.ts
vendored
|
|
@ -87,3 +87,7 @@ declare module 'react-native-web' {
|
|||
type Item<T = number | string> = PickerItem<T>;
|
||||
}
|
||||
}
|
||||
|
||||
declare module 'node:timers' {
|
||||
function setTimeout(callback: (_: void) => void, delay?: number): NodeJS.Timeout;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,24 +1,29 @@
|
|||
import { EventEmitter } from 'node:events';
|
||||
import React, { useCallback, useEffect, useLayoutEffect, useState } from 'react';
|
||||
import React, { useCallback, useEffect, useLayoutEffect, useMemo, useState } from 'react';
|
||||
import { ColorSchemeName, LayoutChangeEvent, Platform, StyleProp, StyleSheet, useColorScheme, View, ViewStyle } from 'react-native';
|
||||
import { i18n, TFunction } from 'i18next';
|
||||
import { I18nextProvider, initReactI18next } from 'react-i18next';
|
||||
import type { User as DiscordUser } from 'discord-rpc';
|
||||
import { NintendoAccountUserCoral } from '../../api/coral.js';
|
||||
import { NintendoAccountUserMoon } from '../../api/moon.js';
|
||||
import { ErrorResponse } from '../../api/util.js';
|
||||
import { DiscordPresence } from '../../discord/types.js';
|
||||
import ipc, { events } from './ipc.js';
|
||||
import { NintendoAccountUser } from '../../api/na.js';
|
||||
import { SavedToken } from '../../common/auth/coral.js';
|
||||
import { SavedMoonToken } from '../../common/auth/moon.js';
|
||||
import { DiscordPresence } from '../../discord/types.js';
|
||||
import ipc, { events } from './ipc.js';
|
||||
import { BACKGROUND_COLOUR_MAIN_DARK, BACKGROUND_COLOUR_MAIN_LIGHT, DEFAULT_ACCENT_COLOUR } from './constants.js';
|
||||
import createI18n from '../i18n/index.js';
|
||||
|
||||
export const WindowFocusedContext = React.createContext(false);
|
||||
|
||||
export function Root(props: React.PropsWithChildren<{
|
||||
title?: string;
|
||||
title?: string | ((i18n: i18n) => string);
|
||||
titleUser?: User | SavedToken;
|
||||
style?: StyleProp<ViewStyle>;
|
||||
scrollable?: boolean;
|
||||
autoresize?: boolean;
|
||||
vibrancy?: boolean;
|
||||
i18nNamespace?: string | string[];
|
||||
}>) {
|
||||
const colour_scheme = useColorScheme();
|
||||
const theme = colour_scheme === 'light' ? light : dark;
|
||||
|
|
@ -26,34 +31,49 @@ export function Root(props: React.PropsWithChildren<{
|
|||
const [accent_colour, setAccentColour] = React.useState(() => ipc.getAccentColour());
|
||||
useEventListener(events, 'systemPreferences:accent-colour', setAccentColour, []);
|
||||
|
||||
const [window_focused, setWindowFocus] = useState(true);
|
||||
const [window_focused, setWindowFocused] = useState(ipc.getWindowFocused());
|
||||
useEventListener(events, 'window:focused', setWindowFocused, []);
|
||||
|
||||
const [i18n, i18n_error] = useAsync(useCallback(async () => {
|
||||
const i18n = createI18n();
|
||||
|
||||
// @ts-expect-error
|
||||
window.i18n = i18n;
|
||||
|
||||
i18n.use(initReactI18next);
|
||||
|
||||
await i18n.init({
|
||||
lng: ipc.getLanguage(),
|
||||
});
|
||||
|
||||
await i18n.loadNamespaces('app');
|
||||
if (props.i18nNamespace) await i18n.loadNamespaces(props.i18nNamespace);
|
||||
|
||||
return i18n;
|
||||
}, []));
|
||||
|
||||
if (i18n_error) throw i18n_error;
|
||||
|
||||
useEventListener(events, 'update-language', language => i18n?.changeLanguage(language), [i18n]);
|
||||
|
||||
// Force rerender when language changes so the window title is updated
|
||||
const [language, setCurrentLanguage] = useState();
|
||||
useEffect(() => {
|
||||
const handler = (event: FocusEvent) => setWindowFocus(event.type === 'focus');
|
||||
window.addEventListener('focus', handler);
|
||||
window.addEventListener('blur', handler);
|
||||
return () => {
|
||||
window.removeEventListener('focus', handler);
|
||||
window.removeEventListener('blur', handler);
|
||||
};
|
||||
}, []);
|
||||
i18n?.on('languageChanged', setCurrentLanguage);
|
||||
return () => i18n?.off('languageChanged', setCurrentLanguage);
|
||||
}, [i18n]);
|
||||
|
||||
useEffect(() => {
|
||||
const user_na = props.titleUser?.user;
|
||||
const user_nso = (props.titleUser && 'nso' in props.titleUser ? props.titleUser.nso : props.titleUser)?.nsoAccount.user;
|
||||
const user_prefix =
|
||||
user_na ? '[' + user_na.nickname +
|
||||
(user_nso && user_nso.name !== user_na.nickname ? '/' + user_nso.name : '') +
|
||||
'] ' : '';
|
||||
|
||||
document.title = user_prefix + (props.title ?? 'Nintendo Switch Online');
|
||||
}, [props.title, props.titleUser]);
|
||||
useAsync(useCallback(async () => i18n?.loadNamespaces('app'), [i18n, language]));
|
||||
useAsync(useCallback(async () => props.i18nNamespace && i18n?.loadNamespaces(props.i18nNamespace),
|
||||
[i18n, props.i18nNamespace, language]));
|
||||
|
||||
const [preventingFocus, setPreventFocus] = useState(true);
|
||||
const unlockFocus = useCallback(() => setPreventFocus(false), []);
|
||||
useLayoutEffect(() => setPreventFocus(props.autoresize ?? true), [props.autoresize]);
|
||||
|
||||
const onLayout = useCallback(async (event: LayoutChangeEvent) => {
|
||||
if (!event.nativeEvent.layout.height) return;
|
||||
|
||||
await ipc.setWindowHeight(event.nativeEvent.layout.height);
|
||||
setPreventFocus(false);
|
||||
}, []);
|
||||
|
|
@ -62,6 +82,17 @@ export function Root(props: React.PropsWithChildren<{
|
|||
document.documentElement.style.overflowY = props.scrollable ? 'auto' : 'hidden';
|
||||
}, [props.scrollable]);
|
||||
|
||||
const title_user_prefix = useMemo(() => {
|
||||
const user_na = props.titleUser?.user;
|
||||
const user_nso = (props.titleUser && 'nso' in props.titleUser ? props.titleUser.nso : props.titleUser)?.nsoAccount.user;
|
||||
|
||||
return user_na ? '[' + user_na.nickname +
|
||||
(user_nso && user_nso.name !== user_na.nickname ? '/' + user_nso.name : '') +
|
||||
'] ' : '';
|
||||
}, [props.titleUser]);
|
||||
|
||||
if (!i18n) return null;
|
||||
|
||||
const content = <View style={[
|
||||
props.scrollable ? styles.appScrollable : styles.app,
|
||||
!props.vibrancy ? theme.appNoVibrancy : null,
|
||||
|
|
@ -83,17 +114,35 @@ export function Root(props: React.PropsWithChildren<{
|
|||
return <ColourSchemeContext.Provider value={colour_scheme}>
|
||||
<AccentColourContext.Provider value={accent_colour ?? DEFAULT_ACCENT_COLOUR}>
|
||||
<WindowFocusedContext.Provider value={window_focused}>
|
||||
{content}
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<WindowTitle title={title_user_prefix + (
|
||||
typeof props.title === 'function' ? props.title.call(null, i18n) :
|
||||
props.title ?? i18n.t('app:default_title'))} />
|
||||
|
||||
{content}
|
||||
</I18nextProvider>
|
||||
</WindowFocusedContext.Provider>
|
||||
</AccentColourContext.Provider>
|
||||
</ColourSchemeContext.Provider>;
|
||||
}
|
||||
|
||||
function WindowTitle(props: {
|
||||
title: string;
|
||||
}) {
|
||||
useEffect(() => {
|
||||
document.title = props.title;
|
||||
}, [props.title]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
app: {
|
||||
// @ts-expect-error vh unit only supported on web
|
||||
height: Platform.OS === 'web' ? '100vh' : '100%',
|
||||
},
|
||||
appScrollable: {
|
||||
// @ts-expect-error vh unit only supported on web
|
||||
minHeight: Platform.OS === 'web' ? '100vh' : '100%',
|
||||
},
|
||||
});
|
||||
|
|
@ -194,10 +243,19 @@ export function useColourScheme() {
|
|||
return React.useContext(ColourSchemeContext);
|
||||
}
|
||||
|
||||
export interface User {
|
||||
user: NintendoAccountUser;
|
||||
nso: SavedToken | null;
|
||||
nsotoken: string | undefined;
|
||||
export interface User<IsCoral extends boolean = boolean> {
|
||||
user:
|
||||
IsCoral extends true ? NintendoAccountUserCoral :
|
||||
IsCoral extends false ? NintendoAccountUserMoon :
|
||||
NintendoAccountUserCoral | NintendoAccountUserMoon;
|
||||
nso:
|
||||
IsCoral extends true ? SavedToken :
|
||||
IsCoral extends false ? null :
|
||||
SavedToken | null;
|
||||
nsotoken:
|
||||
IsCoral extends true ? string :
|
||||
IsCoral extends false ? null :
|
||||
string | null;
|
||||
moon: SavedMoonToken | null;
|
||||
moontoken: string | undefined;
|
||||
}
|
||||
|
|
@ -208,7 +266,7 @@ export async function getAccounts() {
|
|||
const accounts: User[] = [];
|
||||
|
||||
for (const id of ids ?? []) {
|
||||
const nsotoken = await ipc.getNintendoAccountCoralToken(id);
|
||||
const nsotoken = await ipc.getNintendoAccountCoralToken(id) ?? null;
|
||||
const moontoken = await ipc.getNintendoAccountMoonToken(id);
|
||||
|
||||
const nso = nsotoken ? await ipc.getSavedCoralToken(nsotoken) ?? null : null;
|
||||
|
|
@ -250,10 +308,10 @@ export function useActiveDiscordUser() {
|
|||
return user;
|
||||
}
|
||||
|
||||
export function useTimeSince(time: Date, short = false) {
|
||||
export function useTimeSince(time: Date, short = false, t?: TFunction) {
|
||||
const [now, setNow] = useState(Date.now());
|
||||
|
||||
const [since, update_in] = getTimeSince(time, now, short ? short_time_since_intervals : time_since_intervals);
|
||||
const [since, update_in] = getTimeSince(time, now, short ? short_time_since_intervals : time_since_intervals, t);
|
||||
const update_at = Date.now() + update_in;
|
||||
|
||||
useEffect(() => {
|
||||
|
|
@ -268,24 +326,28 @@ interface TimeSinceInterval {
|
|||
interval: number;
|
||||
max: number;
|
||||
string: (count: number) => string;
|
||||
key?: string;
|
||||
}
|
||||
|
||||
const time_since_intervals: TimeSinceInterval[] = [
|
||||
{interval: 1000, max: 10, string: () => 'just now'},
|
||||
{interval: 1000, max: 60, string: c => c + ' second' + (c === 1 ? '' : 's') + ' ago'},
|
||||
{interval: 60 * 1000, max: 60, string: c => c + ' minute' + (c === 1 ? '' : 's') + ' ago'},
|
||||
{interval: 60 * 60 * 1000, max: 24, string: c => c + ' hour' + (c === 1 ? '' : 's') + ' ago'},
|
||||
{interval: 24 * 60 * 60 * 1000, max: Infinity, string: c => c + ' day' + (c === 1 ? '' : 's') + ' ago'},
|
||||
{interval: 1000, max: 10, string: () => 'just now', key: 'default.now'},
|
||||
{interval: 1000, max: 60, string: c => c + ' second' + (c === 1 ? '' : 's') + ' ago', key: 'default.seconds'},
|
||||
{interval: 60 * 1000, max: 60, string: c => c + ' minute' + (c === 1 ? '' : 's') + ' ago', key: 'default.minutes'},
|
||||
{interval: 60 * 60 * 1000, max: 24, string: c => c + ' hour' + (c === 1 ? '' : 's') + ' ago', key: 'default.hours'},
|
||||
{interval: 24 * 60 * 60 * 1000, max: Infinity, string: c => c + ' day' + (c === 1 ? '' : 's') + ' ago', key: 'default.days'},
|
||||
];
|
||||
const short_time_since_intervals: TimeSinceInterval[] = [
|
||||
{interval: 1000, max: 10, string: () => 'Just now'},
|
||||
{interval: 1000, max: 60, string: c => c + ' sec' + (c === 1 ? '' : 's')},
|
||||
{interval: 60 * 1000, max: 60, string: c => c + ' min' + (c === 1 ? '' : 's')},
|
||||
{interval: 60 * 60 * 1000, max: 24, string: c => c + ' hr' + (c === 1 ? '' : 's')},
|
||||
{interval: 24 * 60 * 60 * 1000, max: Infinity, string: c => c + ' day' + (c === 1 ? '' : 's')},
|
||||
{interval: 1000, max: 10, string: () => 'Just now', key: 'default.now'},
|
||||
{interval: 1000, max: 60, string: c => c + ' sec' + (c === 1 ? '' : 's'), key: 'short.seconds'},
|
||||
{interval: 60 * 1000, max: 60, string: c => c + ' min' + (c === 1 ? '' : 's'), key: 'short.minutes'},
|
||||
{interval: 60 * 60 * 1000, max: 24, string: c => c + ' hr' + (c === 1 ? '' : 's'), key: 'short.hours'},
|
||||
{interval: 24 * 60 * 60 * 1000, max: Infinity, string: c => c + ' day' + (c === 1 ? '' : 's'), key: 'short.days'},
|
||||
];
|
||||
|
||||
function getTimeSince(time: Date | number, now = Date.now(), intervals = time_since_intervals): [string, number] {
|
||||
function getTimeSince(
|
||||
time: Date | number, now = Date.now(),
|
||||
intervals = time_since_intervals, t?: TFunction,
|
||||
): [string, number] {
|
||||
if (time instanceof Date) time = time.getTime();
|
||||
|
||||
const elapsed = Math.max(0, now - time);
|
||||
|
|
@ -294,7 +356,10 @@ function getTimeSince(time: Date | number, now = Date.now(), intervals = time_si
|
|||
for (const i of intervals) {
|
||||
if (elapsed < i.max * i.interval || last === i) {
|
||||
const count = Math.floor(elapsed / i.interval);
|
||||
return [i.string.call(null, count), i.interval - (elapsed - (count * i.interval))];
|
||||
return [
|
||||
(t && i.key ? t(i.key, {count, defaultValue: ''}) : '') || i.string.call(null, count),
|
||||
i.interval - (elapsed - (count * i.interval)),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -48,6 +48,10 @@ export interface DiscordPresenceExternalMonitorsConfiguration {
|
|||
enable_splatnet3_monitoring?: boolean;
|
||||
}
|
||||
|
||||
export interface DiscordStatus {
|
||||
error_message: string | null;
|
||||
}
|
||||
|
||||
export interface LoginItem {
|
||||
supported: boolean;
|
||||
startup_enabled: boolean;
|
||||
|
|
|
|||
104
src/app/i18n/index.ts
Normal file
104
src/app/i18n/index.ts
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
import createDebug from 'debug';
|
||||
import { BackendModule, CallbackError, createInstance, ReadCallback } from 'i18next';
|
||||
|
||||
const debug = createDebug('app:i18n');
|
||||
|
||||
import './locale/en-gb.js';
|
||||
|
||||
export const languages = {
|
||||
'en-GB': {
|
||||
name: 'English',
|
||||
app: () => import('./locale/en-gb.js'),
|
||||
authors: [
|
||||
['Ellie', 'https://gitlab.fancy.org.uk/ellie'],
|
||||
],
|
||||
},
|
||||
'de-DE': {
|
||||
name: 'Deutsch',
|
||||
app: () => import('./locale/de-de.js'),
|
||||
authors: [
|
||||
['Inkception', 'https://github.com/Inkception'],
|
||||
],
|
||||
},
|
||||
'es-ES': {
|
||||
name: 'Español',
|
||||
app: () => import('./locale/es-es.js'),
|
||||
authors: [
|
||||
['sarayalth', 'https://github.com/sarayalth'],
|
||||
],
|
||||
},
|
||||
'ja-JP': {
|
||||
name: 'Japanese',
|
||||
app: () => import('./locale/ja-jp.js'),
|
||||
authors: [
|
||||
['hilot06', 'https://github.com/hilot06'],
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const namespaces = {
|
||||
app: 'app',
|
||||
app_menu: 'app',
|
||||
menu_app: 'app',
|
||||
menus: 'app',
|
||||
notifications: 'app',
|
||||
handle_uri: 'app',
|
||||
|
||||
main_window: 'app',
|
||||
preferences_window: 'app',
|
||||
friend_window: 'app',
|
||||
addfriend_window: 'app',
|
||||
discordsetup_window: 'app',
|
||||
addaccountmanual_window: 'app',
|
||||
} as const;
|
||||
|
||||
type Namespace = keyof typeof namespaces;
|
||||
|
||||
export default function createI18n() {
|
||||
const i18n = createInstance({
|
||||
fallbackLng: 'en-GB',
|
||||
debug: true,
|
||||
supportedLngs: Object.keys(languages),
|
||||
load: 'currentOnly',
|
||||
returnNull: false,
|
||||
|
||||
interpolation: {
|
||||
escapeValue: false, // not needed for react as it escapes by default
|
||||
},
|
||||
|
||||
react: {
|
||||
useSuspense: false,
|
||||
},
|
||||
});
|
||||
|
||||
i18n.use(LanguageBackend);
|
||||
|
||||
return i18n;
|
||||
}
|
||||
|
||||
const LanguageBackend: BackendModule = {
|
||||
type: 'backend',
|
||||
read: (
|
||||
language: keyof typeof languages,
|
||||
namespace: Namespace,
|
||||
callback: ReadCallback,
|
||||
) => {
|
||||
debug('Loading %s translations for %s', namespace, language);
|
||||
|
||||
importLocale(language, namespaces[namespace]).then(resources => {
|
||||
callback(null, resources[namespace as keyof typeof resources]);
|
||||
}, (error: CallbackError) => {
|
||||
callback(error, null);
|
||||
});
|
||||
},
|
||||
init: null as any,
|
||||
};
|
||||
|
||||
async function importLocale(
|
||||
language: keyof typeof languages,
|
||||
chunk: typeof namespaces[keyof typeof namespaces] = 'app',
|
||||
) {
|
||||
if (!(language in languages)) throw new Error('Unknown language ' + language);
|
||||
|
||||
return languages[language][chunk]();
|
||||
}
|
||||
386
src/app/i18n/locale/de-de.ts
Normal file
386
src/app/i18n/locale/de-de.ts
Normal file
|
|
@ -0,0 +1,386 @@
|
|||
import { CREDITS_NOTICE, LICENCE_NOTICE } from '../../../common/constants.js';
|
||||
|
||||
export const app = {
|
||||
default_title: 'Nintendo Switch Online',
|
||||
|
||||
licence: LICENCE_NOTICE,
|
||||
credits: CREDITS_NOTICE,
|
||||
translation_credits: '{{language}} Übersetzungen von {{authors, list}}.',
|
||||
};
|
||||
|
||||
export const app_menu = {
|
||||
preferences: 'Einstellungen',
|
||||
view: 'Anschauen',
|
||||
learn_more: 'Mehr erfahren',
|
||||
learn_more_github: 'Mehr erfahren (GitHub)',
|
||||
search_issues: 'Probleme untersuchen',
|
||||
|
||||
refresh: 'Aktualisieren',
|
||||
};
|
||||
|
||||
export const menu_app = {
|
||||
coral_heading: 'Nintendo Switch Online',
|
||||
na_id: 'Nintendo Account ID: {{id}}',
|
||||
coral_id: 'Coral ID: {{id}}',
|
||||
nsa_id: 'NSA ID: {{id}}',
|
||||
discord_presence_enable: 'Discord Rich Presence aktivieren',
|
||||
user_notifications_enable: 'Aktiviere Benachrichtigungen für diesen User',
|
||||
friend_notifications_enable: 'Aktiviere Benachrichtigungen für Freunde von diesen User',
|
||||
refresh: 'Jetzt aktualisieren',
|
||||
add_friend: 'Freund hinzufügen',
|
||||
web_services: 'Web-Services',
|
||||
|
||||
moon_heading: 'Nintendo Switch-Altersbeschränkungen',
|
||||
|
||||
add_account: 'Account hinzufügen',
|
||||
|
||||
show_main_window: 'Zeige Hauptfenster',
|
||||
preferences: 'Einstellungen',
|
||||
quit: 'Beenden',
|
||||
};
|
||||
|
||||
export const menus = {
|
||||
add_account: {
|
||||
add_account_coral: 'Nintendo Switch Online Account hinzufügen',
|
||||
add_account_moon: 'Altersbeschränkter Nintendo Switch Account hinzufügen',
|
||||
},
|
||||
|
||||
friend_code: {
|
||||
share: 'Teilen',
|
||||
copy: 'Kopieren',
|
||||
friend_code_regenerable: 'Regeneriere durch Nintendo Switch Konsole',
|
||||
friend_code_regenerable_at: 'Kann {{date, datetime}} neu generiert werden',
|
||||
},
|
||||
|
||||
user: {
|
||||
na_id: 'Nintendo Account ID: {{id}}',
|
||||
coral_id: 'Coral ID: {{id}}',
|
||||
nsa_id: 'NSA ID: {{id}}',
|
||||
discord_disable: 'Deaktiviere Discord Rich Presence',
|
||||
discord_enabled_for: 'Discord Rich Presence für {{name}} aktiviert',
|
||||
discord_enabled_via: 'Discord Rich Presence durch {{name}} aktiviert',
|
||||
discord_enable: 'Aktiviere Discord Rich Presence für diesen User...',
|
||||
friend_notifications_enable: 'Aktiviere Freund-Benachrichtigungen',
|
||||
refresh: 'Jetzt aktualisieren',
|
||||
add_friend: 'Freund hinzufügen',
|
||||
remove_help: 'Benutze den nxapi Befehl, um diesen User zu entfernen',
|
||||
},
|
||||
|
||||
friend: {
|
||||
presence_online: 'Online',
|
||||
presence_online_nx: 'Online (Nintendo Switch)',
|
||||
presence_online_ounce: 'Online (Nintendo Switch 2)',
|
||||
game_first_played: 'Zuerst gespielt: {{date, datetime}}',
|
||||
|
||||
game_play_time_h: 'Spielzeit: $t(friend.hours, {"count": {{hours}}})',
|
||||
game_play_time_hm: 'Spielzeit: $t(friend.hours, {"count": {{hours}}}), $t(friend.minutes, {"count": {{minutes}}})',
|
||||
game_play_time_m: 'Spielzeit: $t(friend.minutes, {"count": {{minutes}}})',
|
||||
hours_one: '{{count}} Stunde',
|
||||
hours_other: '{{count}} Stunden',
|
||||
minutes_one: '{{count}} Minute',
|
||||
minutes_other: '{{count}} Minuten',
|
||||
|
||||
presence_inactive: 'Offline (Konsole online)',
|
||||
presence_offline: 'Offline',
|
||||
presence_updated: 'Aktualisiert: {{date, datetime}}',
|
||||
presence_logout_time: 'Ausgeloggt: {{date, datetime}}',
|
||||
discord_presence_enable: 'Aktiviere Discord Rich Presence',
|
||||
},
|
||||
};
|
||||
|
||||
export const notifications = {
|
||||
playing: 'Spielt {{name}}',
|
||||
offline: 'Offline',
|
||||
};
|
||||
|
||||
export const handle_uri = {
|
||||
friend_code_select: 'Wähle einen User aus, um Freunde hinzuzufügen',
|
||||
web_service_select: 'Wähle einen User aus, um diesen Service zu öffnen',
|
||||
web_service_invalid_title: 'Unbekannter Titel',
|
||||
web_service_invalid_detail: 'Die angegebene URL verwies nicht auf einen existierenden Web-Service.',
|
||||
cancel: 'Abbrechen',
|
||||
};
|
||||
|
||||
export const na_auth = {
|
||||
window: {
|
||||
title: 'Nintendo Account',
|
||||
},
|
||||
|
||||
znca_api_use: {
|
||||
title: 'Verwendung einer Drittanbieter-API',
|
||||
|
||||
ok: 'OK',
|
||||
cancel: 'Abbrechen',
|
||||
more_information: 'Weitere Informationen',
|
||||
},
|
||||
|
||||
notification_coral: {
|
||||
title: 'Nintendo Switch Online',
|
||||
body_existing: 'Bereits als {{name}} (Nintendo Account {{na_name}} / {{na_username}}) eingeloggt',
|
||||
body_authenticated: 'Authentifiziert als {{name}} (Nintendo Account {{na_name}} / {{na_username}})',
|
||||
body_reauthenticated: 'Erneut als {{name}} (Nintendo Account {{na_name}} / {{na_username}}) authentifiziert',
|
||||
},
|
||||
|
||||
notification_moon: {
|
||||
title: 'Nintendo Switch-Altersbeschränkungen',
|
||||
body_existing: 'Bereits als {{na_name}} ({{na_username}}) eingeloggt',
|
||||
body_authenticated: 'Authentifiziert als {{na_name}} ({{na_username}})',
|
||||
body_reauthenticated: 'Erneut als {{na_name}} ({{na_username}}) authentifiziert',
|
||||
},
|
||||
|
||||
error: {
|
||||
title: 'Fehler beim Hinzufügen des Accounts',
|
||||
},
|
||||
};
|
||||
|
||||
export const time_since = {
|
||||
default: {
|
||||
now: 'jetzt',
|
||||
seconds_one: 'Vor {{count}} Sekunde',
|
||||
seconds_other: 'Vor {{count}} Sekunden',
|
||||
minutes_one: 'Vor {{count}} Minute',
|
||||
minutes_other: 'Vor {{count}} Minuten',
|
||||
hours_one: 'Vor {{count}} Stunde',
|
||||
hours_other: 'Vor {{count}} Stunden',
|
||||
days_one: 'Vor {{count}} Tag',
|
||||
days_other: 'Vor {{count}} Tagen',
|
||||
},
|
||||
|
||||
short: {
|
||||
now: 'jetzt',
|
||||
seconds_one: '{{count}} Sek',
|
||||
seconds_other: '{{count}} Sek',
|
||||
minutes_one: '{{count}} Min',
|
||||
minutes_other: '{{count}} Min',
|
||||
hours_one: '{{count}} Std',
|
||||
hours_other: '{{count}} Std',
|
||||
days_one: '{{count}} Tg',
|
||||
days_other: '{{count}} Tg',
|
||||
},
|
||||
};
|
||||
|
||||
export const main_window = {
|
||||
sidebar: {
|
||||
discord_active: 'Discord Rich Presence aktiv',
|
||||
discord_active_friend: 'Discord Rich Presence aktiv: <0></0>',
|
||||
discord_not_active: 'Discord Rich Presence nicht aktiv',
|
||||
discord_playing: 'Spielt',
|
||||
discord_not_connected: 'Nicht mit Discord verbunden',
|
||||
|
||||
add_user: 'User hinzufügen',
|
||||
discord_setup: 'Discord Rich Presence einrichten',
|
||||
},
|
||||
|
||||
update: {
|
||||
update_available: 'Update verfügbar: {{name}}',
|
||||
download: 'Download',
|
||||
error: 'Fehler beim Überprüfen von Updates aufgetreten: {{message}}',
|
||||
retry: 'Erneut versuchen',
|
||||
},
|
||||
|
||||
main_section: {
|
||||
error: {
|
||||
title: 'Fehler beim Laden der Daten',
|
||||
message: 'Ein Fehler ist beim Laden der {{errors, list}} Daten aufgetreten.',
|
||||
message_friends: 'freunde',
|
||||
message_webservices: 'spielspezifische services',
|
||||
message_event: 'sprachchat',
|
||||
retry: 'Erneut versuchen',
|
||||
view_details: 'Details anschauen',
|
||||
},
|
||||
|
||||
moon_only_user: {
|
||||
title: 'Nintendo Switch Online',
|
||||
desc_1: 'Dieser User ist mit der Nintendo Switch-Altersbeschränkungen App angemeldet, aber nicht mit der Nintendo Switch Online App.',
|
||||
desc_2: 'Logge dich mit der Nintendo Switch Online App ein, um Details einzusehen oder benutze den nxapi Befehl, um auf Altersbeschränkungen zuzugreifen.',
|
||||
login: 'Login',
|
||||
},
|
||||
|
||||
section_error: 'Fehler beim Aktualisieren der Daten',
|
||||
},
|
||||
|
||||
discord_section: {
|
||||
title: 'Discord Rich Presence',
|
||||
|
||||
setup_with_existing_user: 'Benutze einer dieser Account, um die Discord Rich Presence einzurichten: <0></0>.',
|
||||
add_user: 'Füge einen Nintendo Switch Online Account mit diesem User als Freund hinzu, um die Discord Rich Presence einzurichten.',
|
||||
active_self: 'Die Aktivität wird mit diesem User auf Discord geteilt.',
|
||||
active_friend: '<0></0>\'s Aktivität wird mit diesem Account auf Discord geteilt.',
|
||||
active_unknown: 'Die Aktivität eines unbekannten Users wird mit Discord geteilt.',
|
||||
active_via: 'Die Aktivität wird mit diesem User auf Discord über <0></0> geteilt.',
|
||||
|
||||
setup: 'Einrichten',
|
||||
disable: 'Deaktivieren',
|
||||
},
|
||||
|
||||
friends_section: {
|
||||
title: 'Freunde',
|
||||
|
||||
no_friends: 'Füge Freunde mit deiner Nintendo Switch Konsole hinzu.',
|
||||
friend_code: 'Dein Freundescode: <0></0>',
|
||||
|
||||
presence_playing: 'Spielt',
|
||||
presence_offline: 'Offline',
|
||||
},
|
||||
|
||||
webservices_section: {
|
||||
title: 'Spielspezifische Services',
|
||||
},
|
||||
|
||||
event_section: {
|
||||
title: 'Sprachchat',
|
||||
|
||||
members: '{{event}} im Spiel, {{voip}} im Sprachchat',
|
||||
members_with_total: '{{event}} im Spiel, {{voip}} von {{total}} im Sprachkanal',
|
||||
|
||||
app_start: 'Benutze die Nintendo Switch Online App auf iOS oder Android, um einen Sprachchat zu starten.',
|
||||
app_join: 'Benutze die Nintendo Switch Online App auf iOS oder Android, um einem Sprachchat beizutreten.',
|
||||
|
||||
share: 'Teilen',
|
||||
},
|
||||
};
|
||||
|
||||
export const preferences_window = {
|
||||
title: 'Einstellungen',
|
||||
|
||||
startup: {
|
||||
heading: 'Start',
|
||||
login: 'Öffne beim Start',
|
||||
background: 'Öffne im Hintergrund',
|
||||
},
|
||||
|
||||
sleep: {
|
||||
heading: 'Sleep',
|
||||
},
|
||||
|
||||
discord: {
|
||||
heading: 'Discord Rich Presence',
|
||||
enabled: 'Discord Rich Presence ist aktiviert.',
|
||||
disabled: 'Discord Rich Presence ist deaktiviert.',
|
||||
setup: 'Discord Rich Presence Setup',
|
||||
|
||||
user: 'Discord User',
|
||||
user_any: 'Zuerst gesehen',
|
||||
|
||||
friend_code: 'Freundescode',
|
||||
friend_code_help: 'Wenn du deinen Freundescode hinzufügst, wird ebenfalls dein User Icon in Discord angezeigt.',
|
||||
friend_code_self: 'Teile meinen Freundescode',
|
||||
friend_code_custom: 'Eigenen Freundescode festlegen',
|
||||
|
||||
inactive_presence: 'Zeige inaktive Aktivität',
|
||||
inactive_presence_help: 'Zeigt "Spielt nicht", wenn eine verbundene Konsole online ist, du aber nicht spielst.',
|
||||
|
||||
play_time: 'Spielzeit',
|
||||
play_time_hidden: 'Spielzeit niemals anzeigen',
|
||||
play_time_nintendo: 'Zeige Spielzeit wie sie auf der Nintendo Switch Konsole angezeigt wird',
|
||||
play_time_approximate_play_time: 'Zeige ungefähre Spielzeit (nächste 5 Stunden) an',
|
||||
play_time_approximate_play_time_since: 'Zeige ungefähre Spielzeit (nächste 5 Stunden) mit erstem Startdatum an',
|
||||
play_time_hour_play_time: 'Zeige ungefähre Spielzeit (nächste Stunde) an',
|
||||
play_time_hour_play_time_since: 'Zeige ungefähre Spielzeit (nächste Stunde) mit erstem Startdatum an',
|
||||
play_time_detailed_play_time: 'Zeige exakte Spielzeit an',
|
||||
play_time_detailed_play_time_since: 'Zeige exakte Spielzeit mit erstem Startdatum an',
|
||||
},
|
||||
|
||||
splatnet3: {
|
||||
heading: 'SplatNet 3',
|
||||
discord: 'Aktiviere die erweiterte Discord Rich Presence für Splatoon 3',
|
||||
discord_help_1: 'Benutzt SplatNet 3, um zusätzliche Informationen anzuzeigen, während du Splatoon 3 spielst. Du musst einen zweiten Nintendo Switch Account hinzufügen, welcher mit deinem Hauptaccount befreundet ist und Zugriff auf SplatNet 3 hat.',
|
||||
discord_help_2: 'Wenn du eine Presence URL benutzt, werden die zusätzlichen Informationen angezeigt, ohne diese Einstellung zu berücksichtigen.',
|
||||
},
|
||||
};
|
||||
|
||||
export const friend_window = {
|
||||
no_presence: 'Du hast keinen Zugriff auf die Aktivität von diesem User oder er war nie online.',
|
||||
|
||||
nsa_id: 'NSA ID',
|
||||
coral_id: 'Coral user ID',
|
||||
no_coral_user: 'Hat nie die Nintendo Switch Online App genutzt',
|
||||
|
||||
friends_since: 'Freunde seit: {{date, datetime}}',
|
||||
presence_updated_at: 'Aktivität aktualisiert: {{date, datetime}}',
|
||||
presence_logout_at: 'Zuletzt online: {{date, datetime}}',
|
||||
|
||||
presence_sharing: 'Dieser User kann deine Aktivität sehen.',
|
||||
presence_not_sharing: 'Dieser User kann deine Aktivität nicht sehen.',
|
||||
|
||||
discord_presence: 'Aktivität auf Discord teilen',
|
||||
close: 'Schließen',
|
||||
|
||||
presence_playing: 'Spielt {{game}}',
|
||||
presence_playing_nx: 'Spielt {{game}} (Nintendo Switch)',
|
||||
presence_playing_ounce: 'Spielt {{game}} (Nintendo Switch 2)',
|
||||
presence_offline: 'Offline',
|
||||
presence_last_seen: 'Zuletzt gesehen: {{since_logout}}',
|
||||
|
||||
game_played_for_h: 'Gespielt für $t(hours, {"count": {{hours}}})',
|
||||
game_played_for_hm: 'Gespielt für $t(hours, {"count": {{hours}}}), $t(minutes, {"count": {{minutes}}})',
|
||||
game_played_for_m: 'Gespielt für $t(minutes, {"count": {{minutes}}})',
|
||||
hours_one: '{{count}} Stunde',
|
||||
hours_other: '{{count}} Stunden',
|
||||
minutes_one: '{{count}} Minute',
|
||||
minutes_other: '{{count}} Minuten',
|
||||
|
||||
game_first_played: 'Zuerst gespielt am {{date, datetime}}',
|
||||
game_first_played_now: 'Zuerst gespielt jetzt',
|
||||
game_title_id: 'Titel ID',
|
||||
game_shop: 'Nintendo eShop',
|
||||
};
|
||||
|
||||
export const addfriend_window = {
|
||||
title: 'Freund hinzufügen',
|
||||
help: 'Gebe oder füge einen Freundescode oder eine Freundescode-URL ein, um eine Freundschaftsanfrage zu senden.',
|
||||
|
||||
lookup_error: 'Fehler beim Aufrufen des Freundescodes aufgetreten: {{message}}',
|
||||
|
||||
nsa_id: 'NSA ID',
|
||||
coral_id: 'Coral user ID',
|
||||
no_coral_user: 'Hat nie die Nintendo Switch Online App genutzt',
|
||||
|
||||
send_added: 'Du bist nun mit diesem User befreundet.',
|
||||
send_sent: 'Freundschaftsanfrage gesendet. {{user}} kann deine Freundschaftsanfrage über die Nintendo Switch Konsole annehmen oder dir eine Freundschaftsanfrage über die Nintendo Switch Online App oder nxapi senden.',
|
||||
send_sending: 'Sende Freundschaftsanfrage...',
|
||||
send_error: 'Fehler beim Senden der Freundschaftsanfrage aufgetreten: {{message}}',
|
||||
|
||||
already_friends: 'Du bist bereits mit diesem User befreundet',
|
||||
|
||||
close: 'Schließen',
|
||||
send: 'Anfrage senden',
|
||||
};
|
||||
|
||||
export const discordsetup_window = {
|
||||
title: 'Discord Rich Presence Setup',
|
||||
|
||||
mode_heading: '1. Wähle den Modus aus',
|
||||
mode_coral_friend: 'Wähle einen User, der mit dir befreundet ist, aus.',
|
||||
mode_url: 'Gebe eine URL ein, die deine Aktivität zurückgibt.',
|
||||
mode_none: 'Deaktivieren',
|
||||
|
||||
coral_user_heading: '2. Wähle den User aus',
|
||||
coral_user_help: 'Der User muss mit dir befreundet sein, um die Aktivität zu teilen.',
|
||||
coral_friend_heading: '3. Wähle einen Freund aus',
|
||||
coral_friend_help: 'Das ist der User, den du teilen möchtest.',
|
||||
|
||||
url_heading: '2. Gebe eine Presence-URL ein',
|
||||
url_help: 'Der Link muss eine HTTPS-URL sein, die ein JSON-Objekt mit einem User, Freund oder Aktivitätsschlüssel zurückgibt. Diese Funktion ist für nxapi\'s znc API Proxy vorgesehen.',
|
||||
|
||||
preferences_heading: 'Konfiguriere zusätzliche Optionen für die Discord Rich Presence',
|
||||
preferences: 'Einstellungen',
|
||||
|
||||
cancel: 'Abbrechen',
|
||||
save: 'Speichern',
|
||||
};
|
||||
|
||||
export const addaccountmanual_window = {
|
||||
title: 'Account hinzufügen',
|
||||
|
||||
authorise_heading: '1. Logge dich in deinen Nintendo Account ein.',
|
||||
authorise_help: 'Wähle noch keinen Account aus.',
|
||||
authorise_open: 'Öffne die Nintendo Account Authorisierung',
|
||||
|
||||
response_heading: '2. Gebe den Weiterleitungslink ein',
|
||||
response_help_1: 'Rechtsklick auf der "Externen Account verlinken" Seite, Rechtsklick auf "Diese Person auswählen" und den Link kopieren. Der Link sollte mit "{{url}}". beginnen',
|
||||
response_help_2: 'Wenn du einen Kinder-Account, welcher mit deinem Account verlinkt ist, hinzufügen möchtest, klicke auf \"Diese Person auswählen\". Wenn dann nur der Kinder-Account angezeigt wird, Rechtsklick auf \"Diese Person auswählen\" und den Link kopieren.',
|
||||
|
||||
cancel: 'Abbrechen',
|
||||
save: 'Account hinzufügen',
|
||||
};
|
||||
397
src/app/i18n/locale/en-gb.ts
Normal file
397
src/app/i18n/locale/en-gb.ts
Normal file
|
|
@ -0,0 +1,397 @@
|
|||
import { CREDITS_NOTICE, LICENCE_NOTICE, ZNCA_API_USE_TEXT } from '../../../common/constants.js';
|
||||
|
||||
export const app = {
|
||||
default_title: 'Nintendo Switch Online',
|
||||
|
||||
licence: LICENCE_NOTICE,
|
||||
credits: CREDITS_NOTICE,
|
||||
translation_credits: '{{language}} translation by {{authors, list}}.',
|
||||
};
|
||||
|
||||
export const app_menu = {
|
||||
preferences: 'Preferences',
|
||||
view: 'View',
|
||||
learn_more: 'Learn More',
|
||||
learn_more_github: 'Learn More (GitHub)',
|
||||
search_issues: 'Search Issues',
|
||||
export_logs: 'Export Logs',
|
||||
|
||||
refresh: 'Refresh',
|
||||
};
|
||||
|
||||
export const menu_app = {
|
||||
coral_heading: 'Nintendo Switch Online',
|
||||
na_id: 'Nintendo Account ID: {{id}}',
|
||||
coral_id: 'Coral ID: {{id}}',
|
||||
nsa_id: 'NSA ID: {{id}}',
|
||||
discord_presence_enable: 'Enable Discord Presence',
|
||||
user_notifications_enable: 'Enable notifications for this user\'s presence',
|
||||
friend_notifications_enable: 'Enable notifications for friends of this user\'s presence',
|
||||
refresh: 'Update now',
|
||||
add_friend: 'Add friend',
|
||||
web_services: 'Web services',
|
||||
|
||||
moon_heading: 'Nintendo Switch Parental Controls',
|
||||
|
||||
add_account: 'Add account',
|
||||
|
||||
show_main_window: 'Show main window',
|
||||
preferences: 'Preferences',
|
||||
quit: 'Quit',
|
||||
};
|
||||
|
||||
export const menus = {
|
||||
add_account: {
|
||||
add_account_coral: 'Add Nintendo Switch Online account',
|
||||
add_account_moon: 'Add Nintendo Switch Parental Controls account',
|
||||
},
|
||||
|
||||
friend_code: {
|
||||
share: 'Share',
|
||||
copy: 'Copy',
|
||||
friend_code_regenerable: 'Regenerate using a Nintendo Switch console',
|
||||
friend_code_regenerable_at: 'Can be regenerated at {{date, datetime}}',
|
||||
},
|
||||
|
||||
user: {
|
||||
na_id: 'Nintendo Account ID: {{id}}',
|
||||
coral_id: 'Coral ID: {{id}}',
|
||||
nsa_id: 'NSA ID: {{id}}',
|
||||
discord_disable: 'Disable Discord presence',
|
||||
discord_enabled_for: 'Discord presence enabled for {{name}}',
|
||||
discord_enabled_via: 'Discord presence enabled using {{name}}',
|
||||
discord_enable: 'Enable Discord presence for this user...',
|
||||
friend_notifications_enable: 'Enable friend notifications',
|
||||
refresh: 'Update now',
|
||||
add_friend: 'Add friend',
|
||||
remove_help: 'Use the nxapi command to remove this user',
|
||||
},
|
||||
|
||||
friend: {
|
||||
presence_online: 'Online',
|
||||
presence_online_nx: 'Online (Nintendo Switch)',
|
||||
presence_online_ounce: 'Online (Nintendo Switch 2)',
|
||||
game_first_played: 'First played: {{date, datetime}}',
|
||||
|
||||
game_play_time_h: 'Play time: $t(friend.hours, {"count": {{hours}}})',
|
||||
game_play_time_hm: 'Play time: $t(friend.hours, {"count": {{hours}}}), $t(friend.minutes, {"count": {{minutes}}})',
|
||||
game_play_time_m: 'Play time: $t(friend.minutes, {"count": {{minutes}}})',
|
||||
hours_one: '{{count}} hour',
|
||||
hours_other: '{{count}} hours',
|
||||
minutes_one: '{{count}} minute',
|
||||
minutes_other: '{{count}} minutes',
|
||||
|
||||
presence_inactive: 'Offline (console online)',
|
||||
presence_offline: 'Offline',
|
||||
presence_updated: 'Updated: {{date, datetime}}',
|
||||
presence_logout_time: 'Logout time: {{date, datetime}}',
|
||||
discord_presence_enable: 'Enable Discord Presence',
|
||||
},
|
||||
};
|
||||
|
||||
export const notifications = {
|
||||
playing: 'Playing {{name}}',
|
||||
offline: 'Offline',
|
||||
};
|
||||
|
||||
export const handle_uri = {
|
||||
friend_code_select: 'Select a user to add friends',
|
||||
web_service_select: 'Select a user to open this web service',
|
||||
web_service_invalid_title: 'Invalid web service',
|
||||
web_service_invalid_detail: 'The URL did not reference an existing web service.',
|
||||
cancel: 'Cancel',
|
||||
};
|
||||
|
||||
export const na_auth = {
|
||||
window: {
|
||||
title: 'Nintendo Account',
|
||||
},
|
||||
|
||||
znca_api_use: {
|
||||
title: 'Third-party API usage',
|
||||
|
||||
// This should be translated in other languages
|
||||
text: ZNCA_API_USE_TEXT,
|
||||
|
||||
ok: 'OK',
|
||||
cancel: 'Cancel',
|
||||
more_information: 'More information',
|
||||
},
|
||||
|
||||
notification_coral: {
|
||||
title: 'Nintendo Switch Online',
|
||||
body_existing: 'Already signed in as {{name}} (Nintendo Account {{na_name}} / {{na_username}})',
|
||||
body_authenticated: 'Authenticated as {{name}} (Nintendo Account {{na_name}} / {{na_username}})',
|
||||
body_reauthenticated: 'Reauthenticated to {{name}} (Nintendo Account {{na_name}} / {{na_username}})',
|
||||
},
|
||||
|
||||
notification_moon: {
|
||||
title: 'Nintendo Switch Parental Controls',
|
||||
body_existing: 'Already signed in as {{na_name}} ({{na_username}})',
|
||||
body_authenticated: 'Authenticated as {{na_name}} ({{na_username}})',
|
||||
body_reauthenticated: 'Reauthenticated to {{na_name}} ({{na_username}})',
|
||||
},
|
||||
|
||||
error: {
|
||||
title: 'Error adding account',
|
||||
},
|
||||
};
|
||||
|
||||
export const time_since = {
|
||||
default: {
|
||||
now: 'just now',
|
||||
seconds_one: '{{count}} second ago',
|
||||
seconds_other: '{{count}} seconds ago',
|
||||
minutes_one: '{{count}} minute ago',
|
||||
minutes_other: '{{count}} minutes ago',
|
||||
hours_one: '{{count}} hour ago',
|
||||
hours_other: '{{count}} hours ago',
|
||||
days_one: '{{count}} day ago',
|
||||
days_other: '{{count}} days ago',
|
||||
},
|
||||
|
||||
short: {
|
||||
now: 'Just now',
|
||||
seconds_one: '{{count}} sec',
|
||||
seconds_other: '{{count}} secs',
|
||||
minutes_one: '{{count}} min',
|
||||
minutes_other: '{{count}} mins',
|
||||
hours_one: '{{count}} hr',
|
||||
hours_other: '{{count}} hrs',
|
||||
days_one: '{{count}} day',
|
||||
days_other: '{{count}} days',
|
||||
},
|
||||
};
|
||||
|
||||
export const main_window = {
|
||||
sidebar: {
|
||||
discord_active: 'Discord Rich Presence active',
|
||||
discord_active_friend: 'Discord Rich Presence active: <0></0>',
|
||||
discord_not_active: 'Discord Rich Presence not active',
|
||||
discord_playing: 'Playing',
|
||||
discord_not_connected: 'Not connected to Discord',
|
||||
|
||||
add_user: 'Add user',
|
||||
discord_setup: 'Set up Discord Rich Presence',
|
||||
},
|
||||
|
||||
update: {
|
||||
update_available: 'Update available: {{name}}',
|
||||
download: 'Download',
|
||||
error: 'Error checking for updates: {{message}}',
|
||||
retry: 'Try again',
|
||||
},
|
||||
|
||||
main_section: {
|
||||
error: {
|
||||
title: 'Error loading data',
|
||||
message: 'An error occured while loading {{errors, list}} data.',
|
||||
message_friends: 'friends',
|
||||
message_webservices: 'game-specific services',
|
||||
message_event: 'voice chat',
|
||||
retry: 'Retry',
|
||||
view_details: 'View details',
|
||||
},
|
||||
|
||||
moon_only_user: {
|
||||
title: 'Nintendo Switch Online',
|
||||
desc_1: 'This user is signed in to the Nintendo Switch Parental Controls app, but not the Nintendo Switch Online app.',
|
||||
desc_2: 'Login to the Nintendo Switch Online app to view details here, or use the nxapi command to access Parental Controls data.',
|
||||
login: 'Login',
|
||||
},
|
||||
|
||||
section_error: 'Error updating data',
|
||||
},
|
||||
|
||||
discord_section: {
|
||||
title: 'Discord Rich Presence',
|
||||
|
||||
setup_with_existing_user: 'Use one of these accounts to set up Discord Rich Presence for this user: <0></0>.',
|
||||
add_user: 'Add a Nintendo Switch Online account with this user as a friend to set up Discord Rich Presence.',
|
||||
active_self: 'This user\'s presence is being shared to Discord.',
|
||||
active_friend: '<0></0>\'s presence is being shared to Discord using this account.',
|
||||
active_unknown: 'An unknown user\'s presence is being shared to Discord using this account.',
|
||||
active_via: 'This user\'s presence is being shared to Discord using <0></0>.',
|
||||
|
||||
setup: 'Setup',
|
||||
disable: 'Disable',
|
||||
},
|
||||
|
||||
friends_section: {
|
||||
title: 'Friends',
|
||||
add: 'Add',
|
||||
|
||||
no_friends: 'Add friends using a Nintendo Switch console.',
|
||||
friend_code: 'Your friend code: <0></0>',
|
||||
|
||||
presence_playing: 'Playing',
|
||||
presence_offline: 'Offline',
|
||||
},
|
||||
|
||||
webservices_section: {
|
||||
title: 'Game-specific services',
|
||||
},
|
||||
|
||||
event_section: {
|
||||
title: 'Voice chat',
|
||||
|
||||
members: '{{event}} in game, {{voip}} in voice chat',
|
||||
members_with_total: '{{event}} in game, {{voip}} in voice chat of {{total}} members',
|
||||
|
||||
app_start: 'Use the Nintendo Switch Online app on iOS or Android to start voice chat.',
|
||||
app_join: 'Use the Nintendo Switch Online app on iOS or Android to join voice chat.',
|
||||
|
||||
share: 'Share',
|
||||
},
|
||||
};
|
||||
|
||||
export const preferences_window = {
|
||||
title: 'Preferences',
|
||||
|
||||
startup: {
|
||||
heading: 'Startup',
|
||||
login: 'Open at login',
|
||||
background: 'Open in background',
|
||||
},
|
||||
|
||||
sleep: {
|
||||
heading: 'Sleep',
|
||||
},
|
||||
|
||||
discord: {
|
||||
heading: 'Discord Rich Presence',
|
||||
enabled: 'Discord Rich Presence is enabled.',
|
||||
disabled: 'Discord Rich Presence is disabled.',
|
||||
setup: 'Discord Rich Presence setup',
|
||||
|
||||
user: 'Discord user',
|
||||
user_any: 'First discovered',
|
||||
|
||||
friend_code: 'Friend code',
|
||||
friend_code_help: 'Adding your friend code will also show your Nintendo Switch user icon in Discord.',
|
||||
friend_code_self: 'Share my friend code',
|
||||
friend_code_custom: 'Set custom friend code',
|
||||
|
||||
inactive_presence: 'Show inactive presence',
|
||||
inactive_presence_help: 'Shows "Not playing" when a console linked to your account is online, but you are not selected in a game.',
|
||||
|
||||
play_time: 'Play time',
|
||||
play_time_hidden: 'Never show play time',
|
||||
play_time_nintendo: 'Show play time as it appears on a Nintendo Switch console',
|
||||
play_time_approximate_play_time: 'Show approximate play time (nearest 5 hours)',
|
||||
play_time_approximate_play_time_since: 'Show approximate play time (nearest 5 hours) with first played date',
|
||||
play_time_hour_play_time: 'Show approximate play time (nearest hour)',
|
||||
play_time_hour_play_time_since: 'Show approximate play time (nearest hour) with first played date',
|
||||
play_time_detailed_play_time: 'Show exact play time',
|
||||
play_time_detailed_play_time_since: 'Show exact play time with first played date',
|
||||
},
|
||||
|
||||
splatnet3: {
|
||||
heading: 'SplatNet 3',
|
||||
discord: 'Enable enhanced Discord Rich Presence for Splatoon 3',
|
||||
discord_help_1: 'Uses SplatNet 3 to retrieve additional presence information while playing Splatoon 3. You must be using a secondary Nintendo Account that is friends with your main account to fetch your presence, and the secondary account must be able to access SplatNet 3.',
|
||||
discord_help_2: 'When using a presence URL that returns Splatoon 3 data additional presence information will be shown regardless of this setting.',
|
||||
},
|
||||
|
||||
miscellaneous: {
|
||||
heading: 'Miscellaneous',
|
||||
show_error_alerts: 'Show error alerts',
|
||||
show_error_alerts_help: 'Shows an alert when an error occurs while updating presence. If this is disabled, nxapi will delay updates after errors.',
|
||||
},
|
||||
};
|
||||
|
||||
export const friend_window = {
|
||||
no_presence: 'You don\'t have access to this user\'s presence, or they have never been online.',
|
||||
|
||||
nsa_id: 'NSA ID',
|
||||
coral_id: 'Coral user ID',
|
||||
no_coral_user: 'Never used the Nintendo Switch Online app',
|
||||
|
||||
friends_since: 'Friends since {{date, datetime}}',
|
||||
presence_updated_at: 'Presence updated at {{date, datetime}}',
|
||||
presence_logout_at: 'Last online at {{date, datetime}}',
|
||||
|
||||
presence_sharing: 'This user can see your presence.',
|
||||
presence_not_sharing: 'This user can not see your presence.',
|
||||
|
||||
discord_presence: 'Share presence to Discord',
|
||||
close: 'Close',
|
||||
|
||||
presence_playing: 'Playing {{game}}',
|
||||
presence_playing_nx: 'Playing {{game}} (Nintendo Switch)',
|
||||
presence_playing_ounce: 'Playing {{game}} (Nintendo Switch 2)',
|
||||
presence_offline: 'Offline',
|
||||
presence_last_seen: 'Last seen {{since_logout}}',
|
||||
|
||||
game_played_for_h: 'Played for $t(hours, {"count": {{hours}}})',
|
||||
game_played_for_hm: 'Played for $t(hours, {"count": {{hours}}}), $t(minutes, {"count": {{minutes}}})',
|
||||
game_played_for_m: 'Played for $t(minutes, {"count": {{minutes}}})',
|
||||
hours_one: '{{count}} hour',
|
||||
hours_other: '{{count}} hours',
|
||||
minutes_one: '{{count}} minute',
|
||||
minutes_other: '{{count}} minutes',
|
||||
|
||||
game_first_played: 'First played {{date, datetime}}',
|
||||
game_first_played_now: 'First played now',
|
||||
game_title_id: 'Title ID',
|
||||
game_shop: 'Nintendo eShop',
|
||||
};
|
||||
|
||||
export const addfriend_window = {
|
||||
title: 'Add friend',
|
||||
help: 'Type or paste a friend code or friend code URL to send a friend request.',
|
||||
|
||||
lookup_error: 'Error looking up friend code: {{message}}',
|
||||
|
||||
nsa_id: 'NSA ID',
|
||||
coral_id: 'Coral user ID',
|
||||
no_coral_user: 'Never used the Nintendo Switch Online app',
|
||||
|
||||
send_added: 'You are now friends with this user.',
|
||||
send_sent: 'Friend request sent. {{user}} can accept your friend request using a Nintendo Switch console, or by sending you a friend request using the Nintendo Switch Online app or nxapi.',
|
||||
send_sending: 'Sending friend request...',
|
||||
send_error: 'Error sending friend request: {{message}}',
|
||||
|
||||
already_friends: 'You are already friends with this user.',
|
||||
|
||||
close: 'Close',
|
||||
send: 'Send friend request',
|
||||
};
|
||||
|
||||
export const discordsetup_window = {
|
||||
title: 'Discord Rich Presence setup',
|
||||
|
||||
mode_heading: '1. Select mode',
|
||||
mode_coral_friend: 'Select a user that is friends with the user you want to share',
|
||||
mode_url: 'Enter a URL that returns the presence data you want to share',
|
||||
mode_none: 'Disable',
|
||||
|
||||
coral_user_heading: '2. Select user',
|
||||
coral_user_help: 'This user must be friends with the user you want to share.',
|
||||
coral_friend_heading: '3. Select friend',
|
||||
coral_friend_help: 'This is the user you want to share.',
|
||||
|
||||
url_heading: '2. Enter presence URL',
|
||||
url_help: 'This must be a HTTPS URL that returns a JSON object with either a user, friend or presence key. This is intended to be used with nxapi\'s znc API proxy.',
|
||||
|
||||
preferences_heading: 'Configure additional options for Discord Rich Presence',
|
||||
preferences: 'Preferences',
|
||||
|
||||
cancel: 'Cancel',
|
||||
save: 'Save',
|
||||
};
|
||||
|
||||
export const addaccountmanual_window = {
|
||||
title: 'Add account',
|
||||
|
||||
authorise_heading: '1. Login to your Nintendo Account',
|
||||
authorise_help: 'Do not select an account yet.',
|
||||
authorise_open: 'Open Nintendo Account authorisation',
|
||||
|
||||
response_heading: '2. Enter the callback link',
|
||||
response_help_1: 'On the "Linking an External Account" page, right click "Select this person" and copy the link. It should start with "{{url}}".',
|
||||
response_help_2: 'If you are adding a child account linked to your account, click "Select this person" next to their account to sign in as the child account, then with only the child account showing right click "Select this person" and copy the link.',
|
||||
|
||||
cancel: 'Cancel',
|
||||
save: 'Add account',
|
||||
};
|
||||
387
src/app/i18n/locale/es-es.ts
Normal file
387
src/app/i18n/locale/es-es.ts
Normal file
|
|
@ -0,0 +1,387 @@
|
|||
import { CREDITS_NOTICE, LICENCE_NOTICE } from '../../../common/constants.js';
|
||||
|
||||
export const app = {
|
||||
default_title: 'Nintendo Switch Online',
|
||||
|
||||
licence: LICENCE_NOTICE,
|
||||
credits: CREDITS_NOTICE,
|
||||
translation_credits: 'Traducido al {{language}} por {{authors, list}}.',
|
||||
};
|
||||
|
||||
export const app_menu = {
|
||||
preferences: 'Preferencias',
|
||||
view: 'Ver',
|
||||
learn_more: 'Más Información',
|
||||
learn_more_github: 'Más Información (GitHub)',
|
||||
search_issues: 'Buscar Incidencias',
|
||||
|
||||
refresh: 'Actualizar',
|
||||
};
|
||||
|
||||
export const menu_app = {
|
||||
coral_heading: 'Nintendo Switch Online',
|
||||
na_id: 'Nintendo Account ID: {{id}}',
|
||||
coral_id: 'Coral ID: {{id}}',
|
||||
nsa_id: 'NSA ID: {{id}}',
|
||||
discord_presence_enable: 'Activar Discord Rich Presence',
|
||||
user_notifications_enable: 'Activar notificaciones para este usuario',
|
||||
friend_notifications_enable: 'Activar notificaciones para amigos de este usuario',
|
||||
refresh: 'Actualizar ahora',
|
||||
add_friend: 'Añadir amigo',
|
||||
web_services: 'Servicios web',
|
||||
|
||||
moon_heading: 'Control parental de Nintendo Switch',
|
||||
|
||||
add_account: 'Añadir cuenta',
|
||||
|
||||
show_main_window: 'Mostrar la ventana principal',
|
||||
preferences: 'Preferencias',
|
||||
quit: 'Cerrar',
|
||||
};
|
||||
|
||||
export const menus = {
|
||||
add_account: {
|
||||
add_account_coral: 'Añadir cuenta de Nintendo Switch Online',
|
||||
add_account_moon: 'Añadir cuenta de Control parental de Nintendo Switch',
|
||||
},
|
||||
|
||||
friend_code: {
|
||||
share: 'Compartir',
|
||||
copy: 'Copiar',
|
||||
friend_code_regenerable: 'Regenerar utilizando una consola Nintendo Switch',
|
||||
friend_code_regenerable_at: 'Se puede regenerar el {{date, datetime}}',
|
||||
},
|
||||
|
||||
user: {
|
||||
na_id: 'Nintendo Account ID: {{id}}',
|
||||
coral_id: 'Coral ID: {{id}}',
|
||||
nsa_id: 'NSA ID: {{id}}',
|
||||
discord_disable: 'Desactivar Discord Rich Presence',
|
||||
discord_enabled_for: 'Discord Rich Presence activado para {{name}}',
|
||||
discord_enabled_via: 'Discord Rich Presence activado utilizando {{name}}',
|
||||
discord_enable: 'Activar Discord Rich Presence para este usuario...',
|
||||
friend_notifications_enable: 'Activar notificaciones para amigos',
|
||||
refresh: 'Actualizar ahora',
|
||||
add_friend: 'Añadir amigo',
|
||||
remove_help: 'Utiliza el comando nxapi para eliminar a este usuario',
|
||||
},
|
||||
|
||||
friend: {
|
||||
presence_online: 'Online',
|
||||
presence_online_nx: 'Online (Nintendo Switch)',
|
||||
presence_online_ounce: 'Online (Nintendo Switch 2)',
|
||||
game_first_played: 'Jugado por primera vez: {{date, datetime}}',
|
||||
|
||||
game_play_time_h: 'Tiempo de juego: $t(friend.hours, {"count": {{hours}}})',
|
||||
game_play_time_hm: 'Tiempo de juego: $t(friend.hours, {"count": {{hours}}}), $t(friend.minutes, {"count": {{minutes}}})',
|
||||
game_play_time_m: 'Tiempo de juego: $t(friend.minutes, {"count": {{minutes}}})',
|
||||
hours_one: '{{count}} hora',
|
||||
hours_other: '{{count}} horas',
|
||||
minutes_one: '{{count}} minuto',
|
||||
minutes_other: '{{count}} minutos',
|
||||
|
||||
presence_inactive: 'Desconectado (consola conectada)',
|
||||
presence_offline: 'Desconectado',
|
||||
presence_updated: 'Actualizado: {{date, datetime}}',
|
||||
presence_logout_time: 'Hora de desconexión: {{date, datetime}}',
|
||||
discord_presence_enable: 'Activar Discord Rich Presence',
|
||||
},
|
||||
};
|
||||
|
||||
export const notifications = {
|
||||
playing: 'Jugando {{name}}',
|
||||
offline: 'Desconectado',
|
||||
};
|
||||
|
||||
export const handle_uri = {
|
||||
friend_code_select: 'Selecciona un usuario para añadir amigos',
|
||||
web_service_select: 'Selecciona un usuario para abrir este servicio web',
|
||||
web_service_invalid_title: 'Servicio web inválido',
|
||||
web_service_invalid_detail: 'La URL no hace referencia a un servicio web existente.',
|
||||
cancel: 'Cancelar',
|
||||
};
|
||||
|
||||
export const na_auth = {
|
||||
window: {
|
||||
title: 'Cuenta Nintendo',
|
||||
},
|
||||
|
||||
znca_api_use: {
|
||||
title: 'Uso de API de terceros',
|
||||
|
||||
ok: 'OK',
|
||||
cancel: 'Cancelar',
|
||||
more_information: 'Más Información',
|
||||
},
|
||||
|
||||
notification_coral: {
|
||||
title: 'Nintendo Switch Online',
|
||||
body_existing: 'Ya has iniciado sesión como {{name}} (Nintendo Account {{na_name}} / {{na_username}})',
|
||||
body_authenticated: 'Autenticado como {{name}} (Nintendo Account {{na_name}} / {{na_username}})',
|
||||
body_reauthenticated: 'Reautenticado como {{name}} (Nintendo Account {{na_name}} / {{na_username}})',
|
||||
},
|
||||
|
||||
notification_moon: {
|
||||
title: 'Control parental de Nintendo Switch',
|
||||
body_existing: 'Ya has iniciado sesión como {{na_name}} ({{na_username}})',
|
||||
body_authenticated: 'Autenticado como {{na_name}} ({{na_username}})',
|
||||
body_reauthenticated: 'Reautenticado como {{na_name}} ({{na_username}})',
|
||||
},
|
||||
|
||||
error: {
|
||||
title: 'Error añadiendo cuenta',
|
||||
},
|
||||
};
|
||||
|
||||
export const time_since = {
|
||||
default: {
|
||||
now: 'ahora',
|
||||
seconds_one: 'Hace {{count}} segundo',
|
||||
seconds_other: 'Hace {{count}} segundos',
|
||||
minutes_one: 'Hace {{count}} minuto',
|
||||
minutes_other: 'Hace {{count}} minutos',
|
||||
hours_one: 'Hace {{count}} hora',
|
||||
hours_other: 'Hace {{count}} horas',
|
||||
days_one: 'Hace {{count}} día',
|
||||
days_other: 'Hace {{count}} días',
|
||||
},
|
||||
|
||||
short: {
|
||||
now: 'Ahora',
|
||||
seconds_one: '{{count}} seg',
|
||||
seconds_other: '{{count}} seg',
|
||||
minutes_one: '{{count}} min',
|
||||
minutes_other: '{{count}} min',
|
||||
hours_one: '{{count}} h',
|
||||
hours_other: '{{count}} h',
|
||||
days_one: '{{count}} día',
|
||||
days_other: '{{count}} días',
|
||||
},
|
||||
};
|
||||
|
||||
export const main_window = {
|
||||
sidebar: {
|
||||
discord_active: 'Discord Rich Presence activo',
|
||||
discord_active_friend: 'Discord Rich Presence activo: <0></0>',
|
||||
discord_not_active: 'Discord Rich Presence no está activo',
|
||||
discord_playing: 'Jugando',
|
||||
discord_not_connected: 'No conectado a Discord',
|
||||
|
||||
add_user: 'Añadir usuario',
|
||||
discord_setup: 'Configurar Discord Rich Presence',
|
||||
},
|
||||
|
||||
update: {
|
||||
update_available: 'Actualización disponible: {{name}}',
|
||||
download: 'Descargar',
|
||||
error: 'Error buscando actualizaciones: {{message}}',
|
||||
retry: 'Intentar de nuevo',
|
||||
},
|
||||
|
||||
main_section: {
|
||||
error: {
|
||||
title: 'Error cargando datos',
|
||||
message: 'Se produjo un error cargando los datos {{errors, list}}.',
|
||||
message_friends: 'amigos',
|
||||
message_webservices: 'servicios específicos de juegos',
|
||||
message_event: 'chat de voz',
|
||||
retry: 'Reintentar',
|
||||
view_details: 'Ver detalles',
|
||||
},
|
||||
|
||||
moon_only_user: {
|
||||
title: 'Nintendo Switch Online',
|
||||
desc_1: 'Este usuario ha iniciado sesión a la aplicación de Control parental de Nintendo Switch, pero no en la aplicación de Nintendo Switch Online.',
|
||||
desc_2: 'Inicia sesión en la aplicación de Nintendo Switch Online para ver los detalles aquí, o utiliza el comando nxapi para acceder a los datos de Control Parental.',
|
||||
login: 'Iniciar Sesión',
|
||||
},
|
||||
|
||||
section_error: 'Error actualizando datos',
|
||||
},
|
||||
|
||||
discord_section: {
|
||||
title: 'Discord Rich Presence',
|
||||
|
||||
setup_with_existing_user: 'Utiliza una de estas cuentas para configurar Discord Rich Presence para este usuario: <0></0>.',
|
||||
add_user: 'Añade una cuenta de Nintendo Switch Online con este usuario como amigo para configurar Discord Rich Presence.',
|
||||
active_self: 'Compartiendo el estado de este usuario.',
|
||||
active_friend: 'El estado de <0></0> se está compartiendo a Discord utilizando esta cuenta.',
|
||||
active_unknown: 'El estado de un usuario desconocido se está compartiendo a Discord utilizando esta cuenta.',
|
||||
active_via: 'El estado de este usuario se está compartiendo a Discord utilizando <0></0>.',
|
||||
|
||||
setup: 'Configurar',
|
||||
disable: 'Desactivar',
|
||||
},
|
||||
|
||||
friends_section: {
|
||||
title: 'Amigos',
|
||||
add: 'Añadir',
|
||||
|
||||
no_friends: 'Añade amigos utilizando una consola Nintendo Switch.',
|
||||
friend_code: 'Tu código de amigo: <0></0>',
|
||||
|
||||
presence_playing: 'Jugando',
|
||||
presence_offline: 'Desconectado',
|
||||
},
|
||||
|
||||
webservices_section: {
|
||||
title: 'Servicios específicos de juegos',
|
||||
},
|
||||
|
||||
event_section: {
|
||||
title: 'Chat de voz',
|
||||
|
||||
members: '{{event}} jugando, {{voip}} en chat de voz',
|
||||
members_with_total: '{{event}} jugando, {{voip}} en chat de voz de {{total}} miembros',
|
||||
|
||||
app_start: 'Utiliza la aplicación de Nintendo Switch Online en iOS o Android para empezar un chat de voz.',
|
||||
app_join: 'Utiliza la aplicación de Nintendo Switch Online en iOS o Android para unirte un chat de voz.',
|
||||
|
||||
share: 'Compartir',
|
||||
},
|
||||
};
|
||||
|
||||
export const preferences_window = {
|
||||
title: 'Preferencias',
|
||||
|
||||
startup: {
|
||||
heading: 'Inicio',
|
||||
login: 'Abrir al iniciar sesión',
|
||||
background: 'Abrir en segundo plano',
|
||||
},
|
||||
|
||||
sleep: {
|
||||
heading: 'Sleep',
|
||||
},
|
||||
|
||||
discord: {
|
||||
heading: 'Discord Rich Presence',
|
||||
enabled: 'Discord Rich Presence está activado.',
|
||||
disabled: 'Discord Rich Presence está desactivado.',
|
||||
setup: 'Configuración de Discord Rich Presence',
|
||||
|
||||
user: 'Usuario de Discord',
|
||||
user_any: 'El primero que encuentre',
|
||||
|
||||
friend_code: 'Código de amigo',
|
||||
friend_code_help: 'Añadir tu código de amigo también enseñará tu icono de usuario de Nintendo Switch en Discord.',
|
||||
friend_code_self: 'Compartir mi código de amigo',
|
||||
friend_code_custom: 'Personalizar código de amigo',
|
||||
|
||||
inactive_presence: 'Mostrar inactividad',
|
||||
inactive_presence_help: 'Muestra "No está jugando" cuando una consola vinculada con tu cuenta está en línea, pero tú no estás jugando.',
|
||||
|
||||
play_time: 'Tiempo de juego',
|
||||
play_time_hidden: 'Nunca mostrar el tiempo de juego',
|
||||
play_time_nintendo: 'Mostrar el tiempo de juego como aparece en la consola Nintendo Switch',
|
||||
play_time_approximate_play_time: 'Mostrar tiempo de juego aproximado (5 horas más cercanas)',
|
||||
play_time_approximate_play_time_since: 'Mostrar tiempo de juego aproximado (5 horas más cercanas) con fecha de la primera partida',
|
||||
play_time_hour_play_time: 'Mostrar tiempo de juego aproximado (hora más cercana)',
|
||||
play_time_hour_play_time_since: 'Mostrar tiempo de juego aproximado (hora más cercana) con fecha de la primera partida',
|
||||
play_time_detailed_play_time: 'Mostrar tiempo de juego exacto',
|
||||
play_time_detailed_play_time_since: 'Mostrar tiempo de juego exacto con fecha de la primera partida',
|
||||
},
|
||||
|
||||
splatnet3: {
|
||||
heading: 'SplatNet 3',
|
||||
discord: 'Activar Discord Rich Presence ampliado para Splatoon 3',
|
||||
discord_help_1: 'Utiliza SplatNet 3 para mostrar información adicional mientras juegas Splatoon 3. Deberás utilizar una cuenta Nintendo secundaria que esté añadida como amigo en tu cuenta principal y tenga acceso a SplatNet 3.',
|
||||
discord_help_2: 'Si utilizas una URL que devuelva datos de Splatoon 3 se mostrará la información adicional sin tener en cuenta esta opción.',
|
||||
},
|
||||
};
|
||||
|
||||
export const friend_window = {
|
||||
no_presence: 'No tienes acceso al estado de este usuario, o nunca se ha conectado.',
|
||||
|
||||
nsa_id: 'NSA ID',
|
||||
coral_id: 'Coral user ID',
|
||||
no_coral_user: 'Nunca ha utilizado la aplicación de Nintendo Switch Online',
|
||||
|
||||
friends_since: 'Amigos desde: {{date, datetime}}',
|
||||
presence_updated_at: 'Estado actualizado: {{date, datetime}}',
|
||||
presence_logout_at: 'Última vez online: {{date, datetime}}',
|
||||
|
||||
presence_sharing: 'Este usuario puede ver tu estado.',
|
||||
presence_not_sharing: 'Este usuario no puede ver tu estado.',
|
||||
|
||||
discord_presence: 'Compartir estado\nen Discord',
|
||||
close: 'Cerrar',
|
||||
|
||||
presence_playing: 'Jugando {{game}}',
|
||||
presence_playing_nx: 'Jugando {{game}} (Nintendo Switch)',
|
||||
presence_playing_ounce: 'Jugando {{game}} (Nintendo Switch 2)',
|
||||
presence_offline: 'Desconectado',
|
||||
presence_last_seen: 'Visto por última vez: {{since_logout}}',
|
||||
|
||||
game_played_for_h: 'Jugado durante: $t(hours, {"count": {{hours}}})',
|
||||
game_played_for_hm: 'Jugado durante: $t(hours, {"count": {{hours}}}), $t(minutes, {"count": {{minutes}}})',
|
||||
game_played_for_m: 'Jugado durante: $t(minutes, {"count": {{minutes}}})',
|
||||
hours_one: '{{count}} hora',
|
||||
hours_other: '{{count}} horas',
|
||||
minutes_one: '{{count}} minuto',
|
||||
minutes_other: '{{count}} minutos',
|
||||
|
||||
game_first_played: 'Jugado por primera vez: {{date, datetime}}',
|
||||
game_first_played_now: 'Jugado por primera vez: ahora',
|
||||
game_title_id: 'Title ID',
|
||||
game_shop: 'Nintendo eShop',
|
||||
};
|
||||
|
||||
export const addfriend_window = {
|
||||
title: 'Añadir amigo',
|
||||
help: 'Escribe o pega un código de amigo o una URL de código de amigo para enviar una solicitud de amistad.',
|
||||
|
||||
lookup_error: 'Se produjo un error al buscar el código de amigo: {{message}}',
|
||||
|
||||
nsa_id: 'NSA ID',
|
||||
coral_id: 'Coral user ID',
|
||||
no_coral_user: 'Nunca ha utilizado la aplicación de Nintendo Switch Online',
|
||||
|
||||
send_added: 'Ahora eres amigo de este usuario.',
|
||||
send_sent: 'Solicitud de amistad enviada. {{user}} puede aceptar tu solicitud de amistad utilizando una consola Nintendo Switch, o enviándote una solicitud de amistad utilizando la aplicación de Nintendo Switch Online o nxapi.',
|
||||
send_sending: 'Enviando solicitud de amistad...',
|
||||
send_error: 'Se produjo un error al enviar la solicitud de amistad: {{message}}',
|
||||
|
||||
already_friends: 'Ya eres amigo de este usuario.',
|
||||
|
||||
close: 'Cerrar',
|
||||
send: 'Enviar solicitud de amistad',
|
||||
};
|
||||
|
||||
export const discordsetup_window = {
|
||||
title: 'Configuración de Discord Rich Presence',
|
||||
|
||||
mode_heading: '1. Selecciona un modo',
|
||||
mode_coral_friend: 'Selecciona un usuario que sea amigo del usuario que quieres compartir',
|
||||
mode_url: 'Introduce una URL que devuelva el estado que quieres compartir',
|
||||
mode_none: 'Desactivar',
|
||||
|
||||
coral_user_heading: '2. Selecciona un usuario',
|
||||
coral_user_help: 'Este usuario tiene que ser amigo del usuario que quieres compartir.',
|
||||
coral_friend_heading: '3. Selecciona un amigo',
|
||||
coral_friend_help: 'Este es el usuario que quieres compartir.',
|
||||
|
||||
url_heading: '2. Ingresa una URL de estado',
|
||||
url_help: 'Esta URL tiene que utilizar HTTPS y devolver un objeto JSON con una clave de usuario, amigo o estado. Esta función está diseñada para ser utilizada con el proxy de la API znc de nxapi.',
|
||||
|
||||
preferences_heading: 'Configura opciones adicionales para Discord Rich Presence',
|
||||
preferences: 'Preferencias',
|
||||
|
||||
cancel: 'Cancelar',
|
||||
save: 'Guardar',
|
||||
};
|
||||
|
||||
export const addaccountmanual_window = {
|
||||
title: 'Añadir cuenta',
|
||||
|
||||
authorise_heading: '1. Inicia sesión en tu cuenta Nintendo',
|
||||
authorise_help: 'Aún no elijas una cuenta.',
|
||||
authorise_open: 'Abrir la autorización de la cuenta Nintendo',
|
||||
|
||||
response_heading: '2. Introduce el enlace de callback',
|
||||
response_help_1: 'En la pagina de "Vincular una cuenta externa", dale click derecho a "Elegir a esta persona" y copia el link. El link debería de empezar con "{{url}}".',
|
||||
response_help_2: 'Si deseas agregar una cuenta infantil vinculada a tu cuenta, haz clic en "Elegir a esta persona". Si solo se muestra la cuenta infantil, haz clic derecho en "Elegir esta persona" y copia el enlace.',
|
||||
|
||||
cancel: 'Cancelar',
|
||||
save: 'Añadir cuenta',
|
||||
};
|
||||
354
src/app/i18n/locale/ja-jp.ts
Normal file
354
src/app/i18n/locale/ja-jp.ts
Normal file
|
|
@ -0,0 +1,354 @@
|
|||
import { CREDITS_NOTICE, LICENCE_NOTICE } from '../../../common/constants.js';
|
||||
|
||||
export const app = {
|
||||
default_title: 'Nintendo Switch Online',
|
||||
|
||||
licence: LICENCE_NOTICE,
|
||||
credits: CREDITS_NOTICE,
|
||||
translation_credits: 'Japanese translation by hilot06.',
|
||||
};
|
||||
|
||||
export const app_menu = {
|
||||
preferences: '設定',
|
||||
view: '表示',
|
||||
learn_more: 'もっと知る',
|
||||
learn_more_github: 'GitHubでもっと知る',
|
||||
search_issues: 'Issuesの検索',
|
||||
|
||||
refresh: '更新',
|
||||
};
|
||||
|
||||
export const menu_app = {
|
||||
coral_heading: 'Nintendo Switch Online',
|
||||
na_id: 'ニンテンドーアカウントのID: {{id}}',
|
||||
coral_id: 'Coral ID: {{id}}',
|
||||
nsa_id: 'NSA ID: {{id}}',
|
||||
discord_presence_enable: 'Discord Presenceを有効にする',
|
||||
user_notifications_enable: 'このユーザーの通知を有効にする',
|
||||
friend_notifications_enable: 'フレンド通知を有効にする',
|
||||
refresh: '今すぐアップデート',
|
||||
add_friend: 'フレンドを追加',
|
||||
web_services: 'Webサービス',
|
||||
|
||||
moon_heading: 'NintendoみまもりSwitch',
|
||||
|
||||
add_account: 'アカウントを追加',
|
||||
|
||||
show_main_window: 'メイン画面を表示',
|
||||
preferences: '設定',
|
||||
quit: '終了',
|
||||
};
|
||||
|
||||
export const menus = {
|
||||
add_account: {
|
||||
add_account_coral: 'Nintendo Switch Online アカウントを追加',
|
||||
add_account_moon: 'NintendoみまもりSwitch アカウントを追加',
|
||||
},
|
||||
|
||||
friend_code: {
|
||||
share: '共有',
|
||||
copy: 'コピー',
|
||||
friend_code_regenerable: 'Nintendo Switch本体を使ってフレンドコードを再発行',
|
||||
friend_code_regenerable_at: '{{date, datetime}}から再発行できます',
|
||||
},
|
||||
|
||||
user: {
|
||||
na_id: 'ニンテンドーアカウントのID: {{id}}',
|
||||
coral_id: 'Coral ID: {{id}}',
|
||||
nsa_id: 'NSA ID: {{id}}',
|
||||
discord_disable: 'Discord Rich Presenceが無効',
|
||||
discord_enabled_for: '{{name}}のDiscord Rich Presenceが有効',
|
||||
discord_enabled_via: '{{name}}を経由したDiscord Rich Presenceが有効',
|
||||
discord_enable: 'このユーザーに対してDiscord Rich Presenceを有効化する...',
|
||||
friend_notifications_enable: 'フレンド通知を有効化',
|
||||
refresh: '今すぐアップデート',
|
||||
add_friend: 'フレンドを追加',
|
||||
remove_help: 'このユーザーを削除するには、nxapiコマンドを使用してください。',
|
||||
},
|
||||
|
||||
friend: {
|
||||
presence_online: 'オンライン',
|
||||
presence_online_nx: 'オンライン (Nintendo Switch)',
|
||||
presence_online_ounce: 'オンライン (Nintendo Switch 2)',
|
||||
game_first_played: '初めてあそんだ日: {{date, datetime}}',
|
||||
|
||||
game_play_time_h: 'プレイ時間: $t(friend.hours, {"count": {{hours}}})',
|
||||
game_play_time_hm: 'プレイ時間: $t(friend.hours, {"count": {{hours}}}), $t(friend.minutes, {"count": {{minutes}}})',
|
||||
game_play_time_m: 'プレイ時間: $t(friend.minutes, {"count": {{minutes}}})',
|
||||
hours_one: '{{count}}時間',
|
||||
hours_other: '{{count}}時間',
|
||||
minutes_one: '{{count}}分',
|
||||
minutes_other: '{{count}}分',
|
||||
|
||||
presence_inactive: 'オンライン (ゲーム未起動)',
|
||||
presence_offline: 'オフライン',
|
||||
presence_updated: '更新日時: {{date, datetime}}',
|
||||
presence_logout_time: 'オフラインになった日時: {{date, datetime}}',
|
||||
discord_presence_enable: 'Discord Rich Presenceを有効化',
|
||||
},
|
||||
};
|
||||
|
||||
export const notifications = {
|
||||
playing: '{{name}} をプレイ中',
|
||||
offline: 'オフライン',
|
||||
};
|
||||
|
||||
export const handle_uri = {
|
||||
friend_code_select: 'フレンドを追加するユーザーを選択',
|
||||
web_service_select: 'このWebサービスを開くユーザーを選択',
|
||||
web_service_invalid_title: '無効なWebサービス',
|
||||
web_service_invalid_detail: 'そのURLは既存のWebサービスを参照していません。',
|
||||
cancel: 'キャンセル',
|
||||
};
|
||||
|
||||
export const time_since = {
|
||||
default: {
|
||||
now: 'たった今',
|
||||
seconds_one: '{{count}}秒前',
|
||||
seconds_other: '{{count}}秒前',
|
||||
minutes_one: '{{count}}分前',
|
||||
minutes_other: '{{count}}分前',
|
||||
hours_one: '{{count}}時間前',
|
||||
hours_other: '{{count}}時間前',
|
||||
days_one: '{{count}}日前',
|
||||
days_other: '{{count}}日前',
|
||||
},
|
||||
|
||||
short: {
|
||||
now: '今',
|
||||
seconds_one: '{{count}}秒',
|
||||
seconds_other: '{{count}}秒',
|
||||
minutes_one: '{{count}}分',
|
||||
minutes_other: '{{count}}分',
|
||||
hours_one: '{{count}}時間',
|
||||
hours_other: '{{count}}時間',
|
||||
days_one: '{{count}}日',
|
||||
days_other: '{{count}}日',
|
||||
},
|
||||
};
|
||||
|
||||
export const main_window = {
|
||||
sidebar: {
|
||||
discord_active: 'Discord Rich Presenceが動作中',
|
||||
discord_active_friend: 'Discord Rich Presenceが動作中: <0></0>',
|
||||
discord_not_active: 'Discord Rich Presenceは動作していません',
|
||||
discord_playing: 'プレイ中',
|
||||
|
||||
add_user: 'ユーザーを追加',
|
||||
discord_setup: 'Discord Rich Presenceを設定',
|
||||
},
|
||||
|
||||
update: {
|
||||
update_available: 'アップデートが利用可能: {{name}}',
|
||||
download: 'ダウンロード',
|
||||
error: 'アップデートの確認に失敗しました: {{message}}',
|
||||
retry: 'やり直す',
|
||||
},
|
||||
|
||||
main_section: {
|
||||
error: {
|
||||
title: 'データ読み込みエラー',
|
||||
message: '{{errors, list}} データの読み込み中にエラーが発生しました。.',
|
||||
message_friends: 'フレンド',
|
||||
message_webservices: 'ゲーム固有サービス',
|
||||
message_event: 'ボイスチャット',
|
||||
retry: 'やり直す',
|
||||
view_details: '詳細を表示',
|
||||
},
|
||||
|
||||
moon_only_user: {
|
||||
title: 'Nintendo Switch Online',
|
||||
desc_1: 'このユーザーはNintendo Switch Onlineのアプリではなく、NintendoみまもりSwitchのアプリにサインインしています。',
|
||||
desc_2: '詳細を確認するには、こちらからNintendo Switch Onlineのアプリにログインするか、nxapiのコマンドを使ってNintendoみまもりSwitchのデータを閲覧してください。',
|
||||
login: 'ログイン',
|
||||
},
|
||||
|
||||
section_error: 'データ更新エラー',
|
||||
},
|
||||
|
||||
discord_section: {
|
||||
title: 'Discord Rich Presence',
|
||||
|
||||
setup_with_existing_user: 'この中からDiscord Rich Presenceの表示に使うアカウントを選択: <0></0>.',
|
||||
add_user: 'このユーザーのNintendo Switch Onlineアカウントをフレンドとして追加し、Discord Rich Presenceを設定します。',
|
||||
active_self: 'このユーザーの情報をDiscordで表示',
|
||||
active_friend: '<0></0>の情報をこのアカウントを使ってDiscordで表示',
|
||||
active_unknown: '不明なユーザーの情報が、このアカウントを使ってDiscordで表示されます。',
|
||||
active_via: 'このユーザーの情報は<0></0>を使ってDiscordで表示されます。',
|
||||
|
||||
setup: 'セットアップ',
|
||||
disable: '無効化',
|
||||
},
|
||||
|
||||
friends_section: {
|
||||
title: 'フレンド',
|
||||
add: '追加する',
|
||||
|
||||
no_friends: 'Nintendo Switch本体を使ってフレンドを追加してください。',
|
||||
friend_code: 'あなたのフレンドコード: <0></0>',
|
||||
|
||||
presence_playing: 'プレイ中',
|
||||
presence_offline: 'オフライン',
|
||||
},
|
||||
|
||||
webservices_section: {
|
||||
title: 'ゲーム固有サービス',
|
||||
},
|
||||
|
||||
event_section: {
|
||||
title: 'ボイスチャット',
|
||||
|
||||
members: 'ゲーム: {{event}} 人 / ボイスチャット: {{voip}} 人',
|
||||
members_with_total: 'ゲーム: {{event}} 人 / ボイスチャット: {{voip}} 人 / 計 {{total}} 人',
|
||||
|
||||
app_start: 'スマホのNintendo Switch Onlineアプリを使ってボイスチャットを開始してください。',
|
||||
app_join: 'スマホのNintendo Switch Onlineアプリを使ってボイスチャットに参加してください。',
|
||||
|
||||
share: '共有する',
|
||||
},
|
||||
};
|
||||
|
||||
export const preferences_window = {
|
||||
title: '設定',
|
||||
|
||||
startup: {
|
||||
heading: 'スタートアップ',
|
||||
login: 'Windowsにログインした時に開く',
|
||||
background: 'バックグラウンドで開く',
|
||||
},
|
||||
|
||||
sleep: {
|
||||
heading: 'スリープ',
|
||||
},
|
||||
|
||||
discord: {
|
||||
heading: 'Discord Rich Presence',
|
||||
enabled: 'Discord Rich Presenceは有効です。',
|
||||
disabled: 'Discord Rich Presenceは無効です。',
|
||||
setup: 'Discord Rich Presenceのセットアップ',
|
||||
|
||||
user: 'Discordユーザー',
|
||||
user_any: '最初に見つかったユーザーを使う',
|
||||
|
||||
friend_code: 'フレンドコード',
|
||||
friend_code_help: 'フレンドコードを追加すると、DiscordにNintendo Switch上のユーザーアイコンも表示されます。',
|
||||
friend_code_self: 'フレンドコードを共有',
|
||||
friend_code_custom: 'カスタムフレンドコードを設定',
|
||||
|
||||
inactive_presence: '本体を起動している時にプレゼンスを表示',
|
||||
inactive_presence_help: 'ゲームはしていないがNintendo Switch本体を起動している時、「Not playing」を表示します。',
|
||||
|
||||
play_time: 'プレイ時間',
|
||||
play_time_hidden: 'プレイ時間を表示しない',
|
||||
play_time_nintendo: 'Nintendo Switch本体と同じようにプレイ時間を表示する',
|
||||
play_time_approximate_play_time: '5時間刻みのプレイ時間を表示',
|
||||
play_time_approximate_play_time_since: '5時間刻みのプレイ時間を初プレイの日時と一緒に表示',
|
||||
play_time_hour_play_time: '1時間刻みのプレイ時間を表示',
|
||||
play_time_hour_play_time_since: '1時間刻みのプレイ時間を初プレイの日時と一緒に表示',
|
||||
play_time_detailed_play_time: '正確なプレイ時間を表示',
|
||||
play_time_detailed_play_time_since: '正確なプレイ時間を初プレイの日時と一緒に表示',
|
||||
},
|
||||
|
||||
splatnet3: {
|
||||
heading: 'イカリング3',
|
||||
discord: 'スプラトゥーン3向けのDiscord Rich Presenceを有効にする',
|
||||
discord_help_1: 'スプラトゥーン3をプレイ中に、イカリング3を使って追加の情報を取得・表示します。メインアカウントとフレンドであるサブアカウントを用意し、サブアカウントがイカリング3にアクセスできる必要があります。',
|
||||
discord_help_2: 'Discord Presenceに設定したURLからイカリング3のデータが返ってくる場合は、この設定に関係なく追加の情報が取得・表示されます。',
|
||||
},
|
||||
};
|
||||
|
||||
export const friend_window = {
|
||||
no_presence: 'このユーザーのプレイ情報を表示する権限がないか、このユーザーがオンラインになったことがありません。',
|
||||
|
||||
nsa_id: 'NSA ID',
|
||||
coral_id: 'CoralユーザーID',
|
||||
no_coral_user: 'Nintendo Switch Onlineアプリ未使用',
|
||||
|
||||
friends_since: 'フレンドになった日: {{date, datetime}}',
|
||||
presence_updated_at: '状態の最終更新: {{date, datetime}}',
|
||||
presence_logout_at: '最終オンライン: {{date, datetime}}',
|
||||
|
||||
presence_sharing: 'このユーザーはあなたのプレイ情報を見られます。',
|
||||
presence_not_sharing: 'このユーザーはあなたのプレイ情報を見られません。',
|
||||
|
||||
discord_presence: 'Discordでプレイ情報をシェア',
|
||||
close: '閉じる',
|
||||
|
||||
presence_playing: '{{game}}をプレイ中',
|
||||
presence_playing_nx: '{{game}}をプレイ中 (Nintendo Switch)',
|
||||
presence_playing_ounce: '{{game}}をプレイ中 (Nintendo Switch 2)',
|
||||
presence_offline: 'オフライン',
|
||||
presence_last_seen: '最終ログイン: {{since_logout}}',
|
||||
|
||||
game_played_for_h: '$t(hours, {"count": {{hours}}}) 経過',
|
||||
game_played_for_hm: '$t(hours, {"count": {{hours}}}), $t(minutes, {"count": {{minutes}}}) 経過',
|
||||
game_played_for_m: '$t(minutes, {"count": {{minutes}}}) 経過',
|
||||
hours_one: '{{count}}時間',
|
||||
hours_other: '{{count}}時間',
|
||||
minutes_one: '{{count}}分',
|
||||
minutes_other: '{{count}}分',
|
||||
|
||||
game_first_played: '{{date, datetime}}にはじめてプレイ',
|
||||
game_first_played_now: '初プレイ中',
|
||||
game_title_id: 'ゲームID',
|
||||
game_shop: 'ニンテンドー eショップ',
|
||||
};
|
||||
|
||||
export const addfriend_window = {
|
||||
title: 'フレンドを追加',
|
||||
help: 'フレンド申請を送るには、フレンドコードかフレンドコードURLを入力してください。',
|
||||
|
||||
lookup_error: 'フレンドコードを見つけられません: {{message}}',
|
||||
|
||||
nsa_id: 'NSA ID',
|
||||
coral_id: 'Coral user ID',
|
||||
no_coral_user: 'Nintendo Switch Onlineアプリ未使用',
|
||||
|
||||
send_added: 'このユーザーはフレンドです。',
|
||||
send_sent: 'フレンド申請を送信しました。 {{user}}はNintendo Switchを使ってフレンド申請を許可するか、Nintendo Switch Onlineやnxapiを使ってフレンド申請を送れます。',
|
||||
send_sending: 'フレンド申請を送信中...',
|
||||
send_error: 'フレンド申請の送信に失敗しました: {{message}}',
|
||||
|
||||
already_friends: 'すでにこのユーザーはフレンドです。',
|
||||
|
||||
close: '閉じる',
|
||||
send: 'フレンド申請を送信',
|
||||
};
|
||||
|
||||
export const discordsetup_window = {
|
||||
title: 'Discord Rich Presence 設定',
|
||||
|
||||
mode_heading: '1. モードを選択',
|
||||
mode_coral_friend: 'フレンドのプレイ情報を共有する',
|
||||
mode_url: 'URLを入力して返ってくるデータを共有する',
|
||||
mode_none: '無効',
|
||||
|
||||
coral_user_heading: '2. ユーザーを選択',
|
||||
coral_user_help: 'このユーザーは、プレイ情報を共有するユーザーとフレンド同士である必要があります。',
|
||||
coral_friend_heading: '3. フレンドを選択',
|
||||
coral_friend_help: 'このユーザーのプレイ情報を共有します。',
|
||||
|
||||
url_heading: '2. プレイ情報URLを入力',
|
||||
url_help: 'このURLは、ユーザー・フレンド・プレゼンスキーのいずれかを含んだJSONファイルを返すHTTPSのURLでなければなりません。このオプションは、nxapiのznc APIプロキシを使うことを想定しています。',
|
||||
|
||||
preferences_heading: 'Discord Rich Presenceの追加設定を表示',
|
||||
preferences: '設定',
|
||||
|
||||
cancel: 'キャンセル',
|
||||
save: '保存する',
|
||||
};
|
||||
|
||||
export const addaccountmanual_window = {
|
||||
title: 'アカウントを追加',
|
||||
|
||||
authorise_heading: '1. ニンテンドーアカウントにログイン',
|
||||
authorise_help: 'まだアカウントを選択しないでください',
|
||||
authorise_open: 'ニンテンドーアカウントのログインページを開く',
|
||||
|
||||
response_heading: '2. コールバックリンクを入力',
|
||||
response_help_1: '「アカウントを連携」ページに表示される「この人にする」を右クリックし、リンクをコピーしてください。コピーされたリンクは「{{url}}」から始まります。',
|
||||
response_help_2: 'おとなアカウントに紐づいているこどもアカウントを追加する場合は、こどもアカウントの「この人にする」を押してこどもアカウントにサインインしてから、こどもアカウントのみが表示された状態の「この人にする」ボタンのリンクをコピーしてください。',
|
||||
|
||||
cancel: 'キャンセル',
|
||||
save: 'アカウントを追加',
|
||||
};
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
import { i18n } from 'i18next';
|
||||
import { GITHUB_MIRROR_URL, GITLAB_URL, ISSUES_URL } from '../../common/constants.js';
|
||||
import { BrowserWindow, Menu, MenuItem, shell } from './electron.js';
|
||||
import { app, BrowserWindow, Menu, MenuItem, shell } from 'electron';
|
||||
import { App } from './index.js';
|
||||
import { createLogArchive } from './support.js';
|
||||
|
||||
let appinstance: App | null;
|
||||
|
||||
|
|
@ -8,90 +10,113 @@ export function setAppInstance(app: App) {
|
|||
appinstance = app;
|
||||
}
|
||||
|
||||
const menu_app = new MenuItem({
|
||||
role: 'appMenu',
|
||||
submenu: [
|
||||
{ role: 'about' },
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: 'Preferences',
|
||||
accelerator: 'CommandOrControl+,',
|
||||
click: () => {
|
||||
appinstance?.showPreferencesWindow();
|
||||
function createAppMenuItems(i18n?: i18n) {
|
||||
const menu_app = new MenuItem({
|
||||
role: 'appMenu',
|
||||
submenu: [
|
||||
{ role: 'about' },
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: i18n?.t('app_menu:preferences') ?? 'Preferences',
|
||||
accelerator: 'CommandOrControl+,',
|
||||
click: () => {
|
||||
appinstance?.showPreferencesWindow();
|
||||
},
|
||||
},
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{ role: 'services' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'hide' },
|
||||
{ role: 'hideOthers' },
|
||||
{ role: 'unhide' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'quit' },
|
||||
],
|
||||
});
|
||||
{ type: 'separator' },
|
||||
{ role: 'services' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'hide' },
|
||||
{ role: 'hideOthers' },
|
||||
{ role: 'unhide' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'quit' },
|
||||
],
|
||||
});
|
||||
|
||||
const menu_file = new MenuItem({role: 'fileMenu'});
|
||||
const menu_edit = new MenuItem({role: 'editMenu'});
|
||||
const menu_file = new MenuItem({role: 'fileMenu'});
|
||||
const menu_edit = new MenuItem({role: 'editMenu'});
|
||||
|
||||
const menu_view = new MenuItem({
|
||||
label: 'View',
|
||||
submenu: [
|
||||
{ role: 'reload' },
|
||||
{ role: 'forceReload' },
|
||||
{ role: 'toggleDevTools' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'resetZoom' },
|
||||
{ role: 'zoomIn' },
|
||||
{ role: 'zoomOut' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'togglefullscreen' },
|
||||
],
|
||||
});
|
||||
const menu_window = new MenuItem({role: 'windowMenu'});
|
||||
|
||||
const menu_window = new MenuItem({role: 'windowMenu'});
|
||||
|
||||
const menu_help = new MenuItem({
|
||||
role: 'help',
|
||||
submenu: [
|
||||
{
|
||||
label: 'Learn More',
|
||||
click: async () => {
|
||||
await shell.openExternal(GITLAB_URL);
|
||||
},
|
||||
},
|
||||
{
|
||||
label: 'Learn More (GitHub)',
|
||||
click: async () => {
|
||||
await shell.openExternal(GITHUB_MIRROR_URL);
|
||||
},
|
||||
},
|
||||
{
|
||||
label: 'Search Issues',
|
||||
click: async () => {
|
||||
await shell.openExternal(ISSUES_URL);
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
export const app_menu = Menu.buildFromTemplate([
|
||||
...(process.platform === 'darwin' ? [menu_app] : []),
|
||||
menu_file,
|
||||
menu_edit,
|
||||
menu_view,
|
||||
menu_window,
|
||||
menu_help,
|
||||
]);
|
||||
|
||||
export function createWindowMenu(window: BrowserWindow) {
|
||||
const menu_view = new MenuItem({
|
||||
label: 'View',
|
||||
const menu_help = new MenuItem({
|
||||
role: 'help',
|
||||
submenu: [
|
||||
{
|
||||
label: 'Refresh',
|
||||
label: i18n?.t('app_menu:learn_more') ?? 'Learn More',
|
||||
click: async () => {
|
||||
await shell.openExternal(GITLAB_URL);
|
||||
},
|
||||
},
|
||||
{
|
||||
label: i18n?.t('app_menu:learn_more_github') ?? 'Learn More (GitHub)',
|
||||
click: async () => {
|
||||
await shell.openExternal(GITHUB_MIRROR_URL);
|
||||
},
|
||||
},
|
||||
{
|
||||
label: i18n?.t('app_menu:search_issues') ?? 'Search Issues',
|
||||
click: async () => {
|
||||
await shell.openExternal(ISSUES_URL);
|
||||
},
|
||||
},
|
||||
{
|
||||
label: i18n?.t('app_menu:export_logs') ?? 'Export Logs',
|
||||
click: () => {
|
||||
createLogArchive();
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return {menu_app, menu_file, menu_edit, menu_window, menu_help};
|
||||
}
|
||||
|
||||
function createAppMenu(i18n?: i18n) {
|
||||
const {menu_app, menu_file, menu_edit, menu_window, menu_help} = createAppMenuItems(i18n);
|
||||
|
||||
const menu_view = new MenuItem({
|
||||
label: i18n?.t('app_menu:view') ?? 'View',
|
||||
submenu: [
|
||||
{ role: 'reload' },
|
||||
{ role: 'forceReload' },
|
||||
{ role: 'toggleDevTools' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'resetZoom' },
|
||||
{ role: 'zoomIn' },
|
||||
{ role: 'zoomOut' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'togglefullscreen' },
|
||||
],
|
||||
});
|
||||
|
||||
return Menu.buildFromTemplate([
|
||||
...(process.platform === 'darwin' ? [menu_app] : []),
|
||||
menu_file,
|
||||
menu_edit,
|
||||
menu_view,
|
||||
menu_window,
|
||||
menu_help,
|
||||
]);
|
||||
}
|
||||
|
||||
let app_menu = createAppMenu();
|
||||
|
||||
const menu_window_supports_refresh = new WeakSet<BrowserWindow>();
|
||||
|
||||
export function createWindowMenu(window: BrowserWindow, i18n = appinstance?.i18n) {
|
||||
menu_window_supports_refresh.add(window);
|
||||
|
||||
const {menu_app, menu_file, menu_edit, menu_window, menu_help} = createAppMenuItems(i18n);
|
||||
|
||||
const menu_view = new MenuItem({
|
||||
label: i18n?.t('app_menu:view') ?? 'View',
|
||||
submenu: [
|
||||
{
|
||||
id: 'window_refresh',
|
||||
label: i18n?.t('app_menu:refresh') ?? 'Refresh',
|
||||
click: (menuItem, browserWindow, event) => {
|
||||
if (browserWindow === window) {
|
||||
if (browserWindow && menu_window_supports_refresh.has(browserWindow)) {
|
||||
browserWindow.webContents.send('nxapi:window:refresh');
|
||||
} else {
|
||||
browserWindow?.webContents.reload();
|
||||
|
|
@ -119,3 +144,30 @@ export function createWindowMenu(window: BrowserWindow) {
|
|||
menu_help,
|
||||
]);
|
||||
}
|
||||
|
||||
const menus = new WeakMap<BrowserWindow, Menu>();
|
||||
|
||||
app.on('browser-window-focus', (event, window) => {
|
||||
Menu.setApplicationMenu(menus.get(window) ?? app_menu);
|
||||
});
|
||||
app.on('browser-window-blur', (event, window) => {
|
||||
if (!BrowserWindow.getFocusedWindow()) {
|
||||
Menu.setApplicationMenu(app_menu);
|
||||
}
|
||||
});
|
||||
|
||||
export function setWindowMenu(window: BrowserWindow, menu: Menu) {
|
||||
menus.set(window, menu);
|
||||
if (window.isFocused()) Menu.setApplicationMenu(app_menu);
|
||||
}
|
||||
|
||||
export function updateMenuLanguage(i18n: i18n) {
|
||||
app_menu = createAppMenu(i18n);
|
||||
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (!menus.has(window)) continue;
|
||||
menus.set(window, createWindowMenu(window, i18n));
|
||||
}
|
||||
|
||||
Menu.setApplicationMenu(menus.get(BrowserWindow.getFocusedWindow()!) ?? app_menu);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,37 +0,0 @@
|
|||
import { createRequire } from 'node:module';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const electron = require('electron');
|
||||
|
||||
export const app = electron.app;
|
||||
export const BrowserWindow = electron.BrowserWindow;
|
||||
export const clipboard = electron.clipboard;
|
||||
export const dialog = electron.dialog;
|
||||
export const ipcMain = electron.ipcMain;
|
||||
export const Menu = electron.Menu;
|
||||
export const MenuItem = electron.MenuItem;
|
||||
export const nativeImage = electron.nativeImage;
|
||||
export const nativeTheme = electron.nativeTheme;
|
||||
export const Notification = electron.Notification;
|
||||
export const session = electron.session;
|
||||
export const ShareMenu = electron.ShareMenu;
|
||||
export const shell = electron.shell;
|
||||
export const systemPreferences = electron.systemPreferences;
|
||||
export const Tray = electron.Tray;
|
||||
|
||||
export type BrowserWindow = import('electron').BrowserWindow;
|
||||
export type BrowserWindowConstructorOptions = import('electron').BrowserWindowConstructorOptions;
|
||||
export type IpcMain = import('electron').IpcMain;
|
||||
export type IpcMainInvokeEvent = import('electron').IpcMainInvokeEvent;
|
||||
export type KeyboardEvent = import('electron').KeyboardEvent;
|
||||
export type LoginItemSettings = import('electron').LoginItemSettings;
|
||||
export type LoginItemSettingsOptions = import('electron').LoginItemSettingsOptions;
|
||||
export type Menu = import('electron').Menu;
|
||||
export type MenuItem = import('electron').MenuItem;
|
||||
export type MessageBoxOptions = import('electron').MessageBoxOptions;
|
||||
export type Notification = import('electron').Notification;
|
||||
export type Settings = import('electron').Settings;
|
||||
export type ShareMenu = import('electron').ShareMenu;
|
||||
export type SharingItem = import('electron').SharingItem;
|
||||
export type Tray = import('electron').Tray;
|
||||
export type WebContents = import('electron').WebContents;
|
||||
|
|
@ -1,25 +1,31 @@
|
|||
import { app, BrowserWindow, dialog, ipcMain, LoginItemSettingsOptions } from './electron.js';
|
||||
import { app, BrowserWindow, ipcMain, Notification, session, Settings } from 'electron';
|
||||
import process from 'node:process';
|
||||
import * as path from 'node:path';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import createDebug from 'debug';
|
||||
import { setGlobalDispatcher } from 'undici';
|
||||
import * as persist from 'node-persist';
|
||||
import { init as initGlobals } from '../../common/globals.js';
|
||||
import { i18n } from 'i18next';
|
||||
import MenuApp from './menu.js';
|
||||
import { handleOpenWebServiceUri } from './webservices.js';
|
||||
import { EmbeddedPresenceMonitor, PresenceMonitorManager } from './monitor.js';
|
||||
import { createWindow } from './windows.js';
|
||||
import { createModalWindow, createWindow } from './windows.js';
|
||||
import { sendToAllWindows, setupIpc } from './ipc.js';
|
||||
import { askUserForUri, buildElectronProxyAgent, showErrorDialog } from './util.js';
|
||||
import { setAppInstance, updateMenuLanguage } from './app-menu.js';
|
||||
import { checkZncaApiUseAllowed, handleAuthUri } from './na-auth.js';
|
||||
import { DiscordPresenceConfiguration, LoginItem, LoginItemOptions, WindowType } from '../common/types.js';
|
||||
import { initStorage, paths } from '../../util/storage.js';
|
||||
import { init as initGlobals } from '../../common/globals.js';
|
||||
import { CREDITS_NOTICE, GITLAB_URL, LICENCE_NOTICE } from '../../common/constants.js';
|
||||
import { checkUpdates, UpdateCacheData } from '../../common/update.js';
|
||||
import Users, { CoralUser } from '../../common/users.js';
|
||||
import { setupIpc } from './ipc.js';
|
||||
import createDebug from '../../util/debug.js';
|
||||
import { dev, dir, git, release, version } from '../../util/product.js';
|
||||
import { addUserAgent } from '../../util/useragent.js';
|
||||
import { askUserForUri } from './util.js';
|
||||
import { setAppInstance } from './app-menu.js';
|
||||
import { handleAuthUri } from './na-auth.js';
|
||||
import { CREDITS_NOTICE, GITLAB_URL, LICENCE_NOTICE } from '../../common/constants.js';
|
||||
import { initStorage, paths } from '../../util/storage.js';
|
||||
import { ClientAssertionProvider, NXAPI_AUTH_APP_CLIENT_ID, NXAPI_AUTH_APP_SCOPE, setClientAssertionProvider } from '../../util/nxapi-auth.js';
|
||||
import createI18n, { languages } from '../i18n/index.js';
|
||||
import { CoralApiInterface } from '../../api/coral.js';
|
||||
import { StatusUpdateIdentifierSymbol, StatusUpdateMonitor, StatusUpdateNotify, StatusUpdateResult, StatusUpdateSubscriber } from '../../common/status.js';
|
||||
|
||||
const debug = createDebug('app:main');
|
||||
|
||||
|
|
@ -29,7 +35,7 @@ export const protocol_registration_options = dev && process.platform === 'win32'
|
|||
path.join(dir, 'dist', 'app', 'app-entry.cjs'),
|
||||
],
|
||||
} : null;
|
||||
export const login_item_options: LoginItemSettingsOptions = {
|
||||
export const login_item_options: Settings = {
|
||||
path: process.execPath,
|
||||
args: dev ? [
|
||||
path.join(dir, 'dist', 'app', 'app-entry.cjs'),
|
||||
|
|
@ -45,10 +51,17 @@ enum LoginItemType {
|
|||
NOT_SUPPORTED,
|
||||
}
|
||||
const login_item_type: LoginItemType =
|
||||
process.platform === 'darwin' ? LoginItemType.NATIVE :
|
||||
process.platform === 'darwin' ?
|
||||
// macOS 13+ does not support open as hidden
|
||||
parseInt(process.getSystemVersion().split('.', 1)[0]) >= 13 ?
|
||||
LoginItemType.NATIVE_PARTIAL : LoginItemType.NATIVE :
|
||||
process.platform === 'win32' ? LoginItemType.NATIVE_PARTIAL :
|
||||
LoginItemType.NOT_SUPPORTED;
|
||||
|
||||
const was_opened_at_login = process.platform === 'darwin' ?
|
||||
app.getLoginItemSettings(login_item_options).wasOpenedAtLogin :
|
||||
process.argv.includes('--app-open-at-login=1');
|
||||
|
||||
debug('Protocol registration options', protocol_registration_options);
|
||||
debug('Login item registration options', LoginItemType[login_item_type], login_item_options);
|
||||
|
||||
|
|
@ -56,9 +69,10 @@ export class App {
|
|||
readonly store: Store;
|
||||
readonly monitors: PresenceMonitorManager;
|
||||
readonly updater = new Updater();
|
||||
readonly statusupdates = new StatusUpdateMonitor();
|
||||
menu: MenuApp | null = null;
|
||||
|
||||
constructor(storage: persist.LocalStorage) {
|
||||
constructor(storage: persist.LocalStorage, readonly i18n: i18n) {
|
||||
this.store = new Store(this, storage);
|
||||
this.monitors = new PresenceMonitorManager(this);
|
||||
}
|
||||
|
|
@ -99,22 +113,55 @@ export class App {
|
|||
return this.preferences_window;
|
||||
}
|
||||
|
||||
const window = createWindow(WindowType.PREFERENCES, {}, {
|
||||
show: false,
|
||||
maximizable: false,
|
||||
minimizable: false,
|
||||
width: 580,
|
||||
height: 400,
|
||||
minWidth: 580,
|
||||
maxWidth: 580,
|
||||
minHeight: 400,
|
||||
maxHeight: 400,
|
||||
});
|
||||
const window = createModalWindow(WindowType.PREFERENCES, {});
|
||||
|
||||
window.on('closed', () => this.preferences_window = null);
|
||||
|
||||
return this.preferences_window = window;
|
||||
}
|
||||
|
||||
static async createI18n() {
|
||||
const i18n = createI18n();
|
||||
|
||||
const language = this.detectSystemLanguage();
|
||||
debug('Initialising i18n with language %s', language);
|
||||
|
||||
await i18n.init({lng: language ?? undefined});
|
||||
await i18n.loadNamespaces(['app', 'app_menu', 'menus', 'handle_uri', 'na_auth']);
|
||||
|
||||
return i18n;
|
||||
}
|
||||
|
||||
static detectSystemLanguage() {
|
||||
const preferred = app.getPreferredSystemLanguages().map(l => l.toLowerCase());
|
||||
const supported = Object.keys(languages).map(l => l.toLowerCase());
|
||||
|
||||
debug('prefers %O, supports %O', preferred, supported);
|
||||
|
||||
for (const language of preferred) {
|
||||
if (supported.some(l => language.startsWith(l) || l.startsWith(language))) return language;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function setAboutPanelOptions(i18n?: i18n) {
|
||||
const language = i18n ? languages[i18n.resolvedLanguage as keyof typeof languages] : undefined;
|
||||
|
||||
app.setAboutPanelOptions({
|
||||
applicationName: 'nxapi-app',
|
||||
applicationVersion: process.platform === 'darwin' ? version : version +
|
||||
(!release ? '-' + (git?.revision.substr(0, 8) ?? '?') : ''),
|
||||
version: git?.revision.substr(0, 8) ?? '?',
|
||||
authors: ['Ellie'],
|
||||
website: GITLAB_URL,
|
||||
credits: (i18n?.t('app:credits') ?? CREDITS_NOTICE) +
|
||||
(language?.authors.length ? '\n\n' + i18n!.t('app:translation_credits', {
|
||||
language: language.name, authors: language.authors.map(a => a[0]),
|
||||
}) : ''),
|
||||
copyright: i18n?.t('app:licence') ?? LICENCE_NOTICE,
|
||||
});
|
||||
}
|
||||
|
||||
export async function init() {
|
||||
|
|
@ -128,37 +175,64 @@ export async function init() {
|
|||
initGlobals();
|
||||
addUserAgent('nxapi-app (Chromium ' + process.versions.chrome + '; Electron ' + process.versions.electron + ')');
|
||||
|
||||
app.setAboutPanelOptions({
|
||||
applicationName: 'nxapi-app',
|
||||
applicationVersion: process.platform === 'darwin' ? version : version +
|
||||
(!release ? '-' + (git?.revision.substr(0, 8) ?? '?') : ''),
|
||||
version: git?.revision.substr(0, 8) ?? '?',
|
||||
authors: ['Samuel Elliott'],
|
||||
website: GITLAB_URL,
|
||||
credits: CREDITS_NOTICE,
|
||||
copyright: LICENCE_NOTICE,
|
||||
if (NXAPI_AUTH_APP_CLIENT_ID) {
|
||||
setClientAssertionProvider(new ClientAssertionProvider(NXAPI_AUTH_APP_CLIENT_ID, undefined,
|
||||
NXAPI_AUTH_APP_SCOPE));
|
||||
}
|
||||
|
||||
setAboutPanelOptions();
|
||||
|
||||
const agent = buildElectronProxyAgent({
|
||||
session: session.defaultSession,
|
||||
});
|
||||
setGlobalDispatcher(agent);
|
||||
|
||||
const storage = await initStorage(process.env.NXAPI_DATA_PATH ?? paths.data);
|
||||
const appinstance = new App(storage);
|
||||
app.configureHostResolver({enableBuiltInResolver: false});
|
||||
|
||||
const [storage, i18n] = await Promise.all([
|
||||
initStorage(process.env.NXAPI_DATA_PATH ?? paths.data),
|
||||
App.createI18n(),
|
||||
]);
|
||||
|
||||
const appinstance = new App(storage, i18n);
|
||||
// @ts-expect-error
|
||||
globalThis.app = appinstance;
|
||||
|
||||
setAboutPanelOptions(i18n);
|
||||
setAppInstance(appinstance);
|
||||
updateMenuLanguage(i18n);
|
||||
setupIpc(appinstance, ipcMain);
|
||||
|
||||
app.configureHostResolver({enableBuiltInResolver: false});
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
app.setAppUserModelId('uk.org.fancy.nxapi.app');
|
||||
}
|
||||
|
||||
import('../../common/remote-config.js').then(m => {
|
||||
if (!m.default.status_update_url) return;
|
||||
appinstance.statusupdates.addSource(m.default.status_update_url);
|
||||
}).catch(err => {
|
||||
debug('error adding status update source from remote config', err);
|
||||
});
|
||||
|
||||
appinstance.statusupdates.subscribe({
|
||||
onUpdate: data => sendToAllWindows('nxapi:statusupdates', data),
|
||||
});
|
||||
|
||||
appinstance.statusupdates.subscribe(new StatusUpdateNotificationSubscriber(appinstance));
|
||||
|
||||
appinstance.store.restoreMonitorState(appinstance.monitors);
|
||||
|
||||
const menu = new MenuApp(appinstance);
|
||||
appinstance.menu = menu;
|
||||
|
||||
i18n.on('languageChanged', language => {
|
||||
debug('Language changed', language);
|
||||
|
||||
sendToAllWindows('nxapi:app:update-language', language);
|
||||
i18n.loadNamespaces('app').then(() => setAboutPanelOptions(i18n));
|
||||
i18n.loadNamespaces('app_menu').then(() => updateMenuLanguage(i18n));
|
||||
});
|
||||
|
||||
app.on('second-instance', (event, command_line, working_directory, additional_data) => {
|
||||
debug('Second instance', command_line, working_directory, additional_data);
|
||||
|
||||
|
|
@ -204,7 +278,7 @@ export async function init() {
|
|||
|
||||
const should_hide =
|
||||
login_item_type === LoginItemType.NATIVE ? app.getLoginItemSettings(login_item_options).wasOpenedAsHidden :
|
||||
process.argv.includes('--app-open-at-login=1') && (await appinstance.store.getLoginItem()).startup_hidden;
|
||||
was_opened_at_login && (await appinstance.store.getLoginItem()).startup_hidden;
|
||||
|
||||
if (!should_hide) {
|
||||
appinstance.showMainWindow();
|
||||
|
|
@ -220,44 +294,93 @@ function tryHandleUrl(app: App, url: string) {
|
|||
}
|
||||
|
||||
if (url.match(/^com\.nintendo\.znca:\/\/(znca\/)?game\/(\d+)\/?($|\?|\#)/i)) {
|
||||
handleOpenWebServiceUri(app.store, url);
|
||||
handleOpenWebServiceUri(app, url);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (url.match(/^com\.nintendo\.znca:\/\/(znca\/)?friendcode\/(\d{4}-\d{4}-\d{4})\/([A-Za-z0-9]{10})($|\?|\#)/i)) {
|
||||
handleOpenFriendCodeUri(app.store, url);
|
||||
handleOpenFriendCodeUri(app, url);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function handleOpenFriendCodeUri(store: Store, uri: string) {
|
||||
export async function handleOpenFriendCodeUri(app: App, uri: string) {
|
||||
const match = uri.match(/^com\.nintendo\.znca:\/\/(znca\/)friendcode\/(\d{4}-\d{4}-\d{4})\/([A-Za-z0-9]{10})($|\?|\#)/i);
|
||||
if (!match) return;
|
||||
|
||||
const friendcode = match[2];
|
||||
const hash = match[3];
|
||||
|
||||
const selected_user = await askUserForUri(store, uri, 'Select a user to add friends');
|
||||
const selected_user = await askUserForUri(app, uri, app.i18n.t('handle_uri:friend_code_select'));
|
||||
if (!selected_user) return;
|
||||
|
||||
createWindow(WindowType.ADD_FRIEND, {
|
||||
createModalWindow(WindowType.ADD_FRIEND, {
|
||||
user: selected_user[1].user.id,
|
||||
friendcode,
|
||||
}, {
|
||||
// show: false,
|
||||
maximizable: false,
|
||||
minimizable: false,
|
||||
width: 560,
|
||||
height: 300,
|
||||
minWidth: 450,
|
||||
maxWidth: 700,
|
||||
minHeight: 300,
|
||||
maxHeight: 300,
|
||||
});
|
||||
}
|
||||
|
||||
interface StatusUpdateNotificationsCache {
|
||||
notified: {
|
||||
id: string;
|
||||
notified_at: number;
|
||||
}[];
|
||||
}
|
||||
|
||||
class StatusUpdateNotificationSubscriber implements StatusUpdateSubscriber {
|
||||
constructor(readonly app: App) {
|
||||
//
|
||||
}
|
||||
|
||||
_cache: StatusUpdateNotificationsCache | null = null;
|
||||
_cache_updated = false;
|
||||
_load_cache: Promise<StatusUpdateNotificationsCache> | null = null;
|
||||
|
||||
async getNotificationsCache() {
|
||||
if (this._cache) return this._cache;
|
||||
if (this._load_cache) return this._load_cache;
|
||||
|
||||
return this._load_cache = this.app.store.storage.getItem('StatusUpdateNotifications')
|
||||
.then(c => this._cache = (c as StatusUpdateNotificationsCache ?? {notified: []}))
|
||||
.finally(() => this._load_cache = null);
|
||||
}
|
||||
|
||||
async onUpdate(data: StatusUpdateResult) {
|
||||
if (this._cache && this._cache_updated) {
|
||||
await this.app.store.storage.setItem('StatusUpdateNotifications', this._cache);
|
||||
}
|
||||
}
|
||||
|
||||
async onInitialUpdate(data: StatusUpdateResult) {
|
||||
await Promise.all(data.map(s => this.onNewStatusUpdate(s)));
|
||||
}
|
||||
|
||||
async onNewStatusUpdate(status_update: StatusUpdateResult[0]) {
|
||||
if (status_update.notify === StatusUpdateNotify.NO) return;
|
||||
|
||||
const cache = await this.getNotificationsCache();
|
||||
const id = status_update[StatusUpdateIdentifierSymbol];
|
||||
|
||||
if (cache.notified.find(s => s.id === id)) {
|
||||
debug('skipping status update notification, already notified', id);
|
||||
return;
|
||||
}
|
||||
|
||||
const notification = new Notification({
|
||||
title: status_update.title,
|
||||
body: status_update.notification_content ?? status_update.content,
|
||||
silent: status_update.notify === StatusUpdateNotify.SILENT,
|
||||
});
|
||||
|
||||
notification.show();
|
||||
|
||||
cache.notified.push({id, notified_at: Date.now()});
|
||||
this._cache_updated = true;
|
||||
}
|
||||
}
|
||||
|
||||
class Updater {
|
||||
private _cache: UpdateCacheData | null = null;
|
||||
private _check: Promise<UpdateCacheData | null> | null = null;
|
||||
|
|
@ -291,7 +414,7 @@ interface SavedMonitorState {
|
|||
}
|
||||
|
||||
export class Store extends EventEmitter {
|
||||
readonly users: Users<CoralUser>;
|
||||
readonly users: Users<CoralUser<CoralApiInterface>>;
|
||||
|
||||
constructor(
|
||||
readonly app: App,
|
||||
|
|
@ -301,6 +424,32 @@ export class Store extends EventEmitter {
|
|||
|
||||
// ratelimit = false, as most users.get calls are triggered by user interaction (or at startup)
|
||||
this.users = Users.coral(this, process.env.ZNC_PROXY_URL, false);
|
||||
|
||||
this.setAskZncaApiConsent();
|
||||
}
|
||||
|
||||
private _znca_api_use_consent_promise: Promise<void> | null = null;
|
||||
|
||||
private setAskZncaApiConsent() {
|
||||
// @ts-expect-error
|
||||
const get_user = this.users._get;
|
||||
|
||||
// @ts-expect-error
|
||||
this.users._get = async token => {
|
||||
if (!this._znca_api_use_consent_promise) {
|
||||
this._znca_api_use_consent_promise = checkZncaApiUseAllowed(this.app)
|
||||
// Don't clear _znca_api_use_consent_promise on completion as if successful this
|
||||
// doesn't need to be called again anyway
|
||||
.catch(err => {
|
||||
this._znca_api_use_consent_promise = null;
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
|
||||
await this._znca_api_use_consent_promise;
|
||||
|
||||
return get_user.call(null, token);
|
||||
};
|
||||
}
|
||||
|
||||
async getLoginItem(): Promise<LoginItem> {
|
||||
|
|
@ -316,7 +465,6 @@ export class Store extends EventEmitter {
|
|||
}
|
||||
|
||||
const startup_options: SavedStartupOptions | undefined = await this.storage.getItem('StartupOptions');
|
||||
const was_opened_at_login = process.argv.includes('--app-open-at-login=1');
|
||||
|
||||
if (login_item_type === LoginItemType.NATIVE_PARTIAL) {
|
||||
// Partial native support
|
||||
|
|
@ -368,11 +516,11 @@ export class Store extends EventEmitter {
|
|||
};
|
||||
|
||||
for (const monitor of monitors.monitors) {
|
||||
if (monitor instanceof EmbeddedPresenceMonitor && !users.has(monitor.data.user.id)) {
|
||||
users.add(monitor.data?.user.id);
|
||||
if (monitor instanceof EmbeddedPresenceMonitor && !users.has(monitor.user.data.user.id)) {
|
||||
users.add(monitor.user.data.user.id);
|
||||
|
||||
state.users.push({
|
||||
id: monitor.data?.user.id,
|
||||
id: monitor.user.data.user.id,
|
||||
user_notifications: monitor.user_notifications,
|
||||
friend_notifications: monitor.friend_notifications,
|
||||
});
|
||||
|
|
@ -429,7 +577,7 @@ export class Store extends EventEmitter {
|
|||
await monitors.start(user.id, monitor => {
|
||||
monitor.presence_user = state.discord_presence && 'na_id' in state.discord_presence.source &&
|
||||
state.discord_presence.source.na_id === user.id ?
|
||||
state.discord_presence.source.friend_nsa_id ?? monitor.data.nsoAccount.user.nsaId : null;
|
||||
state.discord_presence.source.friend_nsa_id ?? monitor.user.data.nsoAccount.user.nsaId : null;
|
||||
monitor.user_notifications = user.user_notifications;
|
||||
monitor.friend_notifications = user.friend_notifications;
|
||||
|
||||
|
|
@ -443,10 +591,9 @@ export class Store extends EventEmitter {
|
|||
} catch (err) {
|
||||
debug('Error restoring monitor for user %s', user.id, err);
|
||||
|
||||
const {response} = await dialog.showMessageBox({
|
||||
const {response} = await showErrorDialog({
|
||||
message: (err instanceof Error ? err.name : 'Error') + ' restoring monitor for user ' + user.id,
|
||||
detail: err instanceof Error ? err.stack ?? err.message : err as any,
|
||||
type: 'error',
|
||||
error: err,
|
||||
buttons: ['OK', 'Retry'],
|
||||
defaultId: 1,
|
||||
});
|
||||
|
|
@ -472,10 +619,10 @@ export class Store extends EventEmitter {
|
|||
} catch (err) {
|
||||
debug('Error restoring monitor for presence URL %s', state.discord_presence.source.url, err);
|
||||
|
||||
const {response} = await dialog.showMessageBox({
|
||||
message: (err instanceof Error ? err.name : 'Error') + ' restoring monitor for presence URL ' + state.discord_presence.source.url,
|
||||
detail: err instanceof Error ? err.stack ?? err.message : err as any,
|
||||
type: 'error',
|
||||
const {response} = await showErrorDialog({
|
||||
message: (err instanceof Error ? err.name : 'Error') + ' restoring monitor for presence URL ' +
|
||||
state.discord_presence.source.url,
|
||||
error: err,
|
||||
buttons: ['OK', 'Retry'],
|
||||
defaultId: 1,
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,32 +1,59 @@
|
|||
import { app, BrowserWindow, clipboard, dialog, IpcMain, KeyboardEvent, Menu, MenuItem, Settings, ShareMenu, SharingItem, shell, systemPreferences } from './electron.js';
|
||||
import * as util from 'node:util';
|
||||
import createDebug from 'debug';
|
||||
import { BrowserWindow, clipboard, IpcMain, IpcMainInvokeEvent, KeyboardEvent, Menu, MenuItem, ShareMenu, SharingItem, shell, systemPreferences } from 'electron';
|
||||
import { User } from 'discord-rpc';
|
||||
import openWebService, { QrCodeReaderOptions, WebServiceIpc, WebServiceValidationError } from './webservices.js';
|
||||
import { createWindow, getWindowConfiguration } from './windows.js';
|
||||
import { DiscordPresenceConfiguration, DiscordPresenceSource, LoginItemOptions, WindowType } from '../common/types.js';
|
||||
import { CurrentUser, Friend, Game, PresenceState, WebService } from '../../api/coral-types.js';
|
||||
import createDebug from '../../util/debug.js';
|
||||
import { ErrorDescription, ErrorDescriptionSymbol, HasErrorDescription } from '../../util/errors.js';
|
||||
import { Jwt } from '../../util/jwt.js';
|
||||
import openWebService, { handleOpenWebServiceError, QrCodeReaderOptions, WebServiceIpc, WebServiceValidationError } from './webservices.js';
|
||||
import { createModalWindow, getWindowConfiguration, setWindowHeight } from './windows.js';
|
||||
import { askAddNsoAccount, askAddPctlAccount } from './na-auth.js';
|
||||
import { App, login_item_options } from './index.js';
|
||||
import { NintendoAccountUser } from '../../api/na.js';
|
||||
import { hrduration } from '../../util/misc.js';
|
||||
import { App } from './index.js';
|
||||
import { EmbeddedPresenceMonitor } from './monitor.js';
|
||||
import { DiscordPresenceConfiguration, DiscordPresenceSource, DiscordStatus, LoginItemOptions, WindowType } from '../common/types.js';
|
||||
import { CurrentUser, CurrentUserFriendCodeLink, Friend, Game, PresencePlatform, PresenceState, WebService } from '../../api/coral-types.js';
|
||||
import { NintendoAccountSessionTokenJwtPayload, NintendoAccountUser } from '../../api/na.js';
|
||||
import { DiscordPresence } from '../../discord/types.js';
|
||||
import { getDiscordRpcClients } from '../../discord/rpc.js';
|
||||
import { defaultTitle } from '../../discord/titles.js';
|
||||
import { default_client } from '../../discord/titles.js';
|
||||
import type { FriendProps } from '../browser/friend/index.js';
|
||||
import type { DiscordSetupProps } from '../browser/discord/index.js';
|
||||
import type { AddFriendProps } from '../browser/add-friend/index.js';
|
||||
import { EmbeddedPresenceMonitor } from './monitor.js';
|
||||
import { CoralUser } from '../../common/users.js';
|
||||
import { MembershipRequiredError } from '../../common/auth/util.js';
|
||||
import { showErrorDialog } from './util.js';
|
||||
|
||||
const debug = createDebug('app:main:ipc');
|
||||
|
||||
const shown_modal_windows = new WeakSet<BrowserWindow>();
|
||||
export type CachedErrorKey = 'user' | 'announcements' | 'friends' | 'webservices' | 'activeevent' | 'friendcodeurl' | 'friendrequests-received' | 'friendrequests-sent';
|
||||
const cached_errors = new Map<string, Map<CachedErrorKey, Error>>();
|
||||
|
||||
function createErrorHandler(user: CoralUser<any>, key: CachedErrorKey): (err: Error) => void
|
||||
function createErrorHandler(na_session_token: string, key: CachedErrorKey): (err: Error) => void
|
||||
function createErrorHandler(user: CoralUser<any> | string, key: CachedErrorKey) {
|
||||
if (typeof user === 'string') {
|
||||
const [jwt, sig] = Jwt.decode<NintendoAccountSessionTokenJwtPayload>(user);
|
||||
user = jwt.payload.sub;
|
||||
} else {
|
||||
user = user.data.user.id;
|
||||
}
|
||||
|
||||
return (err: Error) => {
|
||||
let errors = cached_errors.get(user);
|
||||
if (!errors) cached_errors.set(user, errors = new Map());
|
||||
|
||||
errors.set(key, err);
|
||||
|
||||
throw err;
|
||||
};
|
||||
}
|
||||
|
||||
export function setupIpc(appinstance: App, ipcMain: IpcMain) {
|
||||
const store = appinstance.store;
|
||||
const storage = appinstance.store.storage;
|
||||
const t = appinstance.i18n.getFixedT(null, 'menus');
|
||||
|
||||
ipcMain.on('nxapi:browser:getwindowdata', e => e.returnValue = getWindowConfiguration(e.sender));
|
||||
ipcMain.on('nxapi:app:language', e => e.returnValue = appinstance.i18n.resolvedLanguage ?? appinstance.i18n.language);
|
||||
ipcMain.on('nxapi:window:focused', e => e.returnValue = e.sender.isFocused());
|
||||
|
||||
let accent_colour = systemPreferences.getAccentColor?.() || undefined;
|
||||
|
||||
|
|
@ -40,153 +67,163 @@ export function setupIpc(appinstance: App, ipcMain: IpcMain) {
|
|||
sendToAllWindows('nxapi:systemPreferences:accent-colour', accent_colour);
|
||||
});
|
||||
|
||||
ipcMain.handle('nxapi:systemPreferences:getloginitem', () => appinstance.store.getLoginItem());
|
||||
ipcMain.handle('nxapi:systemPreferences:setloginitem', (e, settings: LoginItemOptions) => appinstance.store.setLoginItem(settings));
|
||||
const handle = (channel: string, listener: (event: IpcMainInvokeEvent, ...args: any[]) => unknown) => ipcMain.handle('nxapi:' + channel, async (event, ...args) => {
|
||||
try {
|
||||
return {result: await listener.call(null, event, ...args)};
|
||||
} catch (err) {
|
||||
debug('Error invoking IPC method', channel, err);
|
||||
|
||||
ipcMain.handle('nxapi:update:get', () => appinstance.updater.cache ?? appinstance.updater.check());
|
||||
ipcMain.handle('nxapi:update:check', () => appinstance.updater.check());
|
||||
if (!(err instanceof Error)) err = new Error(ErrorDescription.getErrorDescription(err));
|
||||
|
||||
const description = err instanceof HasErrorDescription ? err[ErrorDescriptionSymbol] : null;
|
||||
|
||||
return {
|
||||
error_type: (err as Error).constructor.name,
|
||||
message: (err as Error).message,
|
||||
type: description?.type,
|
||||
description: ErrorDescription.getErrorDescription(err),
|
||||
data: err,
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
handle('systemPreferences:getloginitem', () => appinstance.store.getLoginItem());
|
||||
handle('systemPreferences:setloginitem', (e, settings: LoginItemOptions) => appinstance.store.setLoginItem(settings));
|
||||
|
||||
handle('preferences:getshowerroralerts', () => storage.getItem('ShowErrorAlertsPreference').then(s => s ?? false));
|
||||
handle('preferences:setshowerroralerts', (e, show: boolean) => storage.setItem('ShowErrorAlertsPreference', show));
|
||||
|
||||
handle('update:get', () => appinstance.updater.cache ?? appinstance.updater.check());
|
||||
handle('update:check', () => appinstance.updater.check());
|
||||
handle('statusupdates:get', () => appinstance.statusupdates.cache ?? []);
|
||||
handle('statusupdates:refresh', () => appinstance.statusupdates.forceUpdate());
|
||||
|
||||
setTimeout(async () => {
|
||||
const update = await appinstance.updater.check();
|
||||
if (update) sendToAllWindows('nxapi:update:latest', update);
|
||||
}, 60 * 60 * 1000);
|
||||
|
||||
ipcMain.handle('nxapi:accounts:list', () => storage.getItem('NintendoAccountIds'));
|
||||
ipcMain.handle('nxapi:accounts:add-coral', () => askAddNsoAccount(store.storage).then(u => u?.data.user.id));
|
||||
ipcMain.handle('nxapi:accounts:add-moon', () => askAddPctlAccount(store.storage).then(u => u?.data.user.id));
|
||||
handle('accounts:list', () => storage.getItem('NintendoAccountIds'));
|
||||
handle('accounts:add-coral', () => askAddNsoAccount(appinstance).then(u => u?.data.user.id));
|
||||
handle('accounts:add-moon', () => askAddPctlAccount(appinstance).then(u => u?.data.user.id));
|
||||
|
||||
ipcMain.handle('nxapi:coral:gettoken', (e, id: string) => storage.getItem('NintendoAccountToken.' + id));
|
||||
ipcMain.handle('nxapi:coral:getcachedtoken', (e, token: string) => storage.getItem('NsoToken.' + token));
|
||||
ipcMain.handle('nxapi:coral:announcements', (e, token: string) => store.users.get(token).then(u => u.announcements.result));
|
||||
ipcMain.handle('nxapi:coral:friends', (e, token: string) => store.users.get(token).then(u => u.getFriends()));
|
||||
ipcMain.handle('nxapi:coral:webservices', (e, token: string) => store.users.get(token).then(u => u.getWebServices()));
|
||||
ipcMain.handle('nxapi:coral:openwebservice', (e, webservice: WebService, token: string, qs?: string) =>
|
||||
handle('coral:gettoken', (e, id: string) => storage.getItem('NintendoAccountToken.' + id));
|
||||
handle('coral:getcachedtoken', (e, token: string) => storage.getItem('NsoToken.' + token));
|
||||
handle('coral:announcements', (e, token: string) => store.users.get(token).then(u => u.announcements.result));
|
||||
handle('coral:friends', (e, token: string) => store.users.get(token).then(u => u.getFriends())
|
||||
.catch(createErrorHandler(token, 'friends')));
|
||||
handle('coral:webservices', (e, token: string) => store.users.get(token).then(u => u.getWebServices())
|
||||
.catch(createErrorHandler(token, 'webservices')));
|
||||
handle('coral:openwebservice', (e, webservice: WebService, token: string, qs?: string) =>
|
||||
store.users.get(token).then(u => openWebService(store, token, u.nso, u.data, webservice, qs)
|
||||
.catch(err => err instanceof WebServiceValidationError ? dialog.showMessageBox(BrowserWindow.fromWebContents(e.sender)!, {
|
||||
type: 'error',
|
||||
message: (err instanceof Error ? err.name : 'Error') + ' opening web service',
|
||||
detail: (err instanceof Error ? err.stack ?? err.message : err) + '\n\n' + util.inspect({
|
||||
webservice: {
|
||||
id: webservice.id,
|
||||
name: webservice.name,
|
||||
uri: webservice.uri,
|
||||
},
|
||||
qs,
|
||||
user_na_id: u.data.user.id,
|
||||
user_nsa_id: u.data.nsoAccount.user.nsaId,
|
||||
user_coral_id: u.data.nsoAccount.user.id,
|
||||
}, {compact: true}),
|
||||
}) : null)));
|
||||
ipcMain.handle('nxapi:coral:activeevent', (e, token: string) => store.users.get(token).then(u => u.getActiveEvent()));
|
||||
ipcMain.handle('nxapi:coral:friendcodeurl', (e, token: string) => store.users.get(token).then(u => u.nso.getFriendCodeUrl()));
|
||||
ipcMain.handle('nxapi:coral:friendcode', (e, token: string, friendcode: string, hash?: string) => store.users.get(token).then(u => u.nso.getUserByFriendCode(friendcode, hash)));
|
||||
ipcMain.handle('nxapi:coral:addfriend', (e, token: string, nsaid: string) => store.users.get(token).then(u => u.addFriend(nsaid)));
|
||||
.catch(err => err instanceof WebServiceValidationError || err instanceof MembershipRequiredError ?
|
||||
handleOpenWebServiceError(err, webservice, qs, u.data, BrowserWindow.fromWebContents(e.sender)!) :
|
||||
null)));
|
||||
handle('coral:activeevent', (e, token: string) => store.users.get(token).then(u => u.getActiveEvent()
|
||||
.then(e => e ?? {}))
|
||||
.catch(createErrorHandler(token, 'activeevent')));
|
||||
handle('coral:friendcodeurl', (e, token: string) => store.users.get(token).then(u => u.nso.getFriendCodeUrl())
|
||||
.catch(createErrorHandler(token, 'friendcodeurl')));
|
||||
handle('coral:friendrequests:received', (e, token: string) => store.users.get(token).then(u => u.getReceivedFriendRequests())
|
||||
.catch(createErrorHandler(token, 'friendrequests-received')));
|
||||
handle('coral:friendrequests:sent', (e, token: string) => store.users.get(token).then(u => u.getSentFriendRequests())
|
||||
.catch(createErrorHandler(token, 'friendrequests-sent')));
|
||||
handle('coral:friendcode', (e, token: string, friendcode: string, hash?: string) => store.users.get(token).then(u => u.nso.getUserByFriendCode(friendcode, hash)));
|
||||
handle('coral:addfriend', (e, token: string, nsaid: string) => store.users.get(token).then(u => u.addFriend(nsaid)));
|
||||
|
||||
ipcMain.handle('nxapi:window:showpreferences', () => appinstance.showPreferencesWindow().id);
|
||||
ipcMain.handle('nxapi:window:showfriend', (e, props: FriendProps) => createWindow(WindowType.FRIEND, props, {
|
||||
parent: BrowserWindow.fromWebContents(e.sender) ?? undefined,
|
||||
modal: true,
|
||||
show: false,
|
||||
maximizable: false,
|
||||
minimizable: false,
|
||||
width: 560,
|
||||
height: 300,
|
||||
minWidth: 450,
|
||||
maxWidth: 700,
|
||||
minHeight: 300,
|
||||
maxHeight: 300,
|
||||
}).id);
|
||||
ipcMain.handle('nxapi:window:discord', (e, props: DiscordSetupProps) => createWindow(WindowType.DISCORD_PRESENCE, props, {
|
||||
parent: BrowserWindow.fromWebContents(e.sender) ?? undefined,
|
||||
modal: true,
|
||||
show: false,
|
||||
maximizable: false,
|
||||
minimizable: false,
|
||||
width: 560,
|
||||
height: 300,
|
||||
minWidth: 450,
|
||||
maxWidth: 700,
|
||||
minHeight: 300,
|
||||
maxHeight: 300,
|
||||
}).id);
|
||||
ipcMain.handle('nxapi:window:addfriend', (e, props: AddFriendProps) => createWindow(WindowType.ADD_FRIEND, props, {
|
||||
parent: BrowserWindow.fromWebContents(e.sender) ?? undefined,
|
||||
modal: true,
|
||||
show: false,
|
||||
maximizable: false,
|
||||
minimizable: false,
|
||||
width: 560,
|
||||
height: 300,
|
||||
minWidth: 450,
|
||||
maxWidth: 700,
|
||||
minHeight: 300,
|
||||
maxHeight: 300,
|
||||
}).id);
|
||||
ipcMain.handle('nxapi:window:setheight', (e, height: number) => {
|
||||
const window = BrowserWindow.fromWebContents(e.sender)!;
|
||||
const [curWidth, curHeight] = window.getSize();
|
||||
const [curContentWidth, curContentHeight] = window.getContentSize();
|
||||
const [minWidth, minHeight] = window.getMinimumSize();
|
||||
const [maxWidth, maxHeight] = window.getMaximumSize();
|
||||
if (height !== curContentHeight && curHeight === minHeight && curHeight === maxHeight) {
|
||||
window.setMinimumSize(minWidth, height + (curHeight - curContentHeight));
|
||||
window.setMaximumSize(maxWidth, height + (curHeight - curContentHeight));
|
||||
handle('coral:showlasterrors', async (e, token: string, keys: CachedErrorKey | CachedErrorKey[]) => {
|
||||
const [jwt, sig] = Jwt.decode<NintendoAccountSessionTokenJwtPayload>(token);
|
||||
const user = jwt.payload.sub;
|
||||
const errors = cached_errors.get(user);
|
||||
if (!errors?.size) return;
|
||||
|
||||
if (typeof keys === 'string') keys = [keys];
|
||||
|
||||
const show = new Set<Error>();
|
||||
|
||||
for (const key of keys) {
|
||||
if (!errors.has(key)) continue;
|
||||
show.add(errors.get(key)!);
|
||||
}
|
||||
window.setContentSize(curContentWidth, height);
|
||||
|
||||
if (!shown_modal_windows.has(window)) {
|
||||
window.show();
|
||||
shown_modal_windows.add(window);
|
||||
for (const error of show) {
|
||||
showErrorDialog({
|
||||
message: 'Error loading data',
|
||||
error,
|
||||
app: appinstance,
|
||||
window: BrowserWindow.fromWebContents(e.sender) ?? undefined,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('nxapi:discord:config', () => appinstance.monitors.getDiscordPresenceConfiguration());
|
||||
ipcMain.handle('nxapi:discord:setconfig', (e, config: DiscordPresenceConfiguration | null) => appinstance.monitors.setDiscordPresenceConfiguration(config));
|
||||
ipcMain.handle('nxapi:discord:options', () => appinstance.monitors.getActiveDiscordPresenceOptions() ?? appinstance.store.getSavedDiscordPresenceOptions());
|
||||
ipcMain.handle('nxapi:discord:savedoptions', () => appinstance.store.getSavedDiscordPresenceOptions());
|
||||
ipcMain.handle('nxapi:discord:setoptions', (e, options: Omit<DiscordPresenceConfiguration, 'source'>) => appinstance.monitors.setDiscordPresenceOptions(options));
|
||||
ipcMain.handle('nxapi:discord:source', () => appinstance.monitors.getDiscordPresenceSource());
|
||||
ipcMain.handle('nxapi:discord:setsource', (e, source: DiscordPresenceSource | null) => appinstance.monitors.setDiscordPresenceSource(source));
|
||||
ipcMain.handle('nxapi:discord:presence', () => appinstance.monitors.getDiscordPresence());
|
||||
ipcMain.handle('nxapi:discord:user', () => appinstance.monitors.getActiveDiscordPresenceMonitor()?.discord.rpc?.client.user ?? null);
|
||||
ipcMain.handle('nxapi:discord:users', async () => {
|
||||
handle('window:showpreferences', () => appinstance.showPreferencesWindow().id);
|
||||
handle('window:showfriend', (e, props: FriendProps) =>
|
||||
createModalWindow(WindowType.FRIEND, props, e.sender).id);
|
||||
handle('window:discord', (e, props: DiscordSetupProps) =>
|
||||
createModalWindow(WindowType.DISCORD_PRESENCE, props).id);
|
||||
handle('window:addfriend', (e, props: AddFriendProps) =>
|
||||
createModalWindow(WindowType.ADD_FRIEND, props, e.sender).id);
|
||||
handle('window:setheight', (e, height: number) => {
|
||||
const window = BrowserWindow.fromWebContents(e.sender)!;
|
||||
setWindowHeight(window, height);
|
||||
});
|
||||
|
||||
handle('discord:config', () => appinstance.monitors.getDiscordPresenceConfiguration());
|
||||
handle('discord:setconfig', (e, config: DiscordPresenceConfiguration | null) => appinstance.monitors.setDiscordPresenceConfiguration(config));
|
||||
handle('discord:options', () => appinstance.monitors.getActiveDiscordPresenceOptions() ?? appinstance.store.getSavedDiscordPresenceOptions());
|
||||
handle('discord:savedoptions', () => appinstance.store.getSavedDiscordPresenceOptions());
|
||||
handle('discord:setoptions', (e, options: Omit<DiscordPresenceConfiguration, 'source'>) => appinstance.monitors.setDiscordPresenceOptions(options));
|
||||
handle('discord:source', () => appinstance.monitors.getDiscordPresenceSource());
|
||||
handle('discord:setsource', (e, source: DiscordPresenceSource | null) => appinstance.monitors.setDiscordPresenceSource(source));
|
||||
handle('discord:presence', () => appinstance.monitors.getDiscordPresence());
|
||||
handle('discord:status', () => appinstance.monitors.getDiscordStatus());
|
||||
handle('discord:showerror', () => appinstance.monitors.showDiscordPresenceLastUpdateError());
|
||||
handle('discord:user', () => appinstance.monitors.getActiveDiscordPresenceMonitor()?.discord.rpc?.client.user ?? null);
|
||||
handle('discord:users', async () => {
|
||||
const users: User[] = [];
|
||||
|
||||
for (const client of await getDiscordRpcClients()) {
|
||||
await client.connect(defaultTitle.client);
|
||||
if (client.user && !users.find(u => u.id === client.user!.id)) users.push(client.user);
|
||||
try {
|
||||
await client.connect(default_client);
|
||||
if (client.user && !users.find(u => u.id === client.user!.id)) users.push(client.user);
|
||||
} finally {
|
||||
await client.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
return users;
|
||||
});
|
||||
|
||||
ipcMain.handle('nxapi:moon:gettoken', (e, id: string) => storage.getItem('NintendoAccountToken-pctl.' + id));
|
||||
ipcMain.handle('nxapi:moon:getcachedtoken', (e, token: string) => storage.getItem('MoonToken.' + token));
|
||||
handle('moon:gettoken', (e, id: string) => storage.getItem('NintendoAccountToken-pctl.' + id));
|
||||
handle('moon:getcachedtoken', (e, token: string) => storage.getItem('MoonToken.' + token));
|
||||
|
||||
ipcMain.handle('nxapi:misc:open-url', (e, url: string) => shell.openExternal(url));
|
||||
ipcMain.handle('nxapi:misc:share', (e, item: SharingItem) =>
|
||||
handle('misc:open-url', (e, url: string) => shell.openExternal(url));
|
||||
handle('misc:share', (e, item: SharingItem) =>
|
||||
new ShareMenu(item).popup({window: BrowserWindow.fromWebContents(e.sender)!}));
|
||||
|
||||
ipcMain.handle('nxapi:menu:user', (e, user: NintendoAccountUser, nso?: CurrentUser, moon?: boolean) =>
|
||||
handle('menu:user', (e, user: NintendoAccountUser, nso?: CurrentUser<true> | CurrentUser<false>, moon?: boolean) =>
|
||||
(buildUserMenu(appinstance, user, nso, moon, BrowserWindow.fromWebContents(e.sender) ?? undefined)
|
||||
.popup({window: BrowserWindow.fromWebContents(e.sender)!}), undefined));
|
||||
ipcMain.handle('nxapi:menu:add-user', e => (Menu.buildFromTemplate([
|
||||
new MenuItem({label: 'Add Nintendo Switch Online account', click:
|
||||
handle('menu:add-user', e => (Menu.buildFromTemplate([
|
||||
new MenuItem({label: t('add_account.add_account_coral')!, click:
|
||||
(item: MenuItem, window: BrowserWindow | undefined, event: KeyboardEvent) =>
|
||||
askAddNsoAccount(storage, !event.shiftKey)}),
|
||||
new MenuItem({label: 'Add Nintendo Switch Parental Controls account', click:
|
||||
askAddNsoAccount(appinstance, !event.shiftKey)}),
|
||||
new MenuItem({label: t('add_account.add_account_moon')!, click:
|
||||
(item: MenuItem, window: BrowserWindow | undefined, event: KeyboardEvent) =>
|
||||
askAddPctlAccount(storage, !event.shiftKey)}),
|
||||
askAddPctlAccount(appinstance, !event.shiftKey)}),
|
||||
]).popup({window: BrowserWindow.fromWebContents(e.sender)!}), undefined));
|
||||
ipcMain.handle('nxapi:menu:friend-code', (e, fc: CurrentUser['links']['friendCode']) => (Menu.buildFromTemplate([
|
||||
handle('menu:friend-code', (e, fc: CurrentUserFriendCodeLink) => (Menu.buildFromTemplate([
|
||||
new MenuItem({label: 'SW-' + fc.id, enabled: false}),
|
||||
new MenuItem({label: 'Share', role: 'shareMenu', sharingItem: {texts: ['SW-' + fc.id]}}),
|
||||
new MenuItem({label: 'Copy', click: () => clipboard.writeText('SW-' + fc.id)}),
|
||||
new MenuItem({label: t('friend_code.share')!, role: 'shareMenu', sharingItem: {texts: ['SW-' + fc.id]}}),
|
||||
new MenuItem({label: t('friend_code.copy')!, click: () => clipboard.writeText('SW-' + fc.id)}),
|
||||
new MenuItem({type: 'separator'}),
|
||||
new MenuItem({label: fc.regenerable ? 'Regenerate using a Nintendo Switch console' :
|
||||
'Can be regenerated at ' + new Date(fc.regenerableAt * 1000).toLocaleString('en-GB'), enabled: false}),
|
||||
new MenuItem({label: fc.regenerable ? t('friend_code.friend_code_regenerable')! :
|
||||
t('friend_code.friend_code_regenerable_at', {
|
||||
date: new Date(fc.regenerableAt * 1000),
|
||||
formatParams: { date: { dateStyle: 'short', timeStyle: 'medium' } },
|
||||
})!, enabled: false}),
|
||||
]).popup({window: BrowserWindow.fromWebContents(e.sender)!}), undefined));
|
||||
ipcMain.handle('nxapi:menu:friend', (e, user: NintendoAccountUser, nso: CurrentUser, friend: Friend) =>
|
||||
handle('menu:friend', (e, user: NintendoAccountUser, nso: CurrentUser<true> | CurrentUser<false>, friend: Friend) =>
|
||||
(buildFriendMenu(appinstance, user, nso, friend)
|
||||
.popup({window: BrowserWindow.fromWebContents(e.sender)!}), undefined));
|
||||
|
||||
|
|
@ -203,93 +240,75 @@ export function setupIpc(appinstance: App, ipcMain: IpcMain) {
|
|||
ipcMain.handle('nxapi:webserviceapi:copyToClipboard', (e, data: string) => webserviceipc.copyToClipboard(e, data));
|
||||
ipcMain.handle('nxapi:webserviceapi:downloadImages', (e, data: string) => webserviceipc.downloadImages(e, data));
|
||||
ipcMain.handle('nxapi:webserviceapi:completeLoading', e => webserviceipc.completeLoading(e));
|
||||
ipcMain.handle('nxapi:webserviceapi:clearUnreadFlag', e => webserviceipc.clearUnreadFlag(e));
|
||||
|
||||
store.on('update-nintendo-accounts', () => sendToAllWindows('nxapi:accounts:shouldrefresh'));
|
||||
store.on('update-discord-presence-source', () => sendToAllWindows('nxapi:discord:shouldrefresh'));
|
||||
store.on('update-discord-presence', (p: DiscordPresence) => sendToAllWindows('nxapi:discord:presence', p));
|
||||
store.on('update-discord-user', (u: User) => sendToAllWindows('nxapi:discord:user', u));
|
||||
store.on('update-discord-status', (s: DiscordStatus | null) => sendToAllWindows('nxapi:discord:status', s));
|
||||
}
|
||||
|
||||
function sendToAllWindows(channel: string, ...args: any[]) {
|
||||
export function sendToAllWindows(channel: string, ...args: any[]) {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
window.webContents.send(channel, ...args);
|
||||
}
|
||||
}
|
||||
|
||||
function buildUserMenu(app: App, user: NintendoAccountUser, nso?: CurrentUser, moon?: boolean, window?: BrowserWindow) {
|
||||
function buildUserMenu(app: App, user: NintendoAccountUser, nso?: CurrentUser<true> | CurrentUser<false>, moon?: boolean, window?: BrowserWindow) {
|
||||
const t = app.i18n.getFixedT(null, 'menus', 'user');
|
||||
const dm = app.monitors.getActiveDiscordPresenceMonitor();
|
||||
const monitor = app.monitors.monitors.find(m => m instanceof EmbeddedPresenceMonitor && m.data.user.id === user.id);
|
||||
const monitor = app.monitors.monitors.find(m => m instanceof EmbeddedPresenceMonitor &&
|
||||
m.user.data.user.id === user.id);
|
||||
|
||||
return Menu.buildFromTemplate([
|
||||
new MenuItem({label: 'Nintendo Account ID: ' + user.id, enabled: false}),
|
||||
new MenuItem({label: t('na_id', {id: user.id})!, enabled: false}),
|
||||
...(nso ? [
|
||||
new MenuItem({label: 'Coral ID: ' + nso.id, enabled: false}),
|
||||
new MenuItem({label: 'NSA ID: ' + nso.nsaId, enabled: false}),
|
||||
new MenuItem({label: t('coral_id', {id: nso.id})!, enabled: false}),
|
||||
new MenuItem({label: t('nsa_id', {id: nso.nsaId})!, enabled: false}),
|
||||
new MenuItem({type: 'separator'}),
|
||||
...(monitor?.presence_user === nso.nsaId ? [
|
||||
new MenuItem({label: 'Disable Discord presence',
|
||||
new MenuItem({label: t('discord_disable')!,
|
||||
click: () => app.menu?.setActiveDiscordPresenceUser(null)}),
|
||||
] : monitor?.presence_user ? [
|
||||
new MenuItem({label: 'Discord presence enabled for ' +
|
||||
new MenuItem({label: t('discord_enabled_for', {name:
|
||||
monitor.user?.friends.result.friends.find(f => f.nsaId === monitor.presence_user)?.name ??
|
||||
monitor.presence_user,
|
||||
monitor.presence_user})!,
|
||||
enabled: false}),
|
||||
new MenuItem({label: 'Disable Discord presence',
|
||||
new MenuItem({label: t('discord_disable')!,
|
||||
click: () => app.menu?.setActiveDiscordPresenceUser(null)}),
|
||||
] : dm?.presence_user === nso.nsaId ? [
|
||||
new MenuItem({label: 'Discord presence enabled using ' +
|
||||
dm.data.user.nickname +
|
||||
(dm.data.user.nickname!== dm.data.nsoAccount.user.name ? '/' + dm.data.nsoAccount.user.name : ''),
|
||||
new MenuItem({label: t('discord_enabled_via', {name:
|
||||
dm.user.data.user.nickname +
|
||||
(dm.user.data.user.nickname !== dm.user.data.nsoAccount.user.name ?
|
||||
'/' + dm.user.data.nsoAccount.user.name : '')})!,
|
||||
enabled: false}),
|
||||
new MenuItem({label: 'Disable Discord presence',
|
||||
new MenuItem({label: t('discord_disable')!,
|
||||
click: () => app.menu?.setActiveDiscordPresenceUser(null)}),
|
||||
] : [
|
||||
new MenuItem({label: 'Enable Discord presence for this user...',
|
||||
click: () => createWindow(WindowType.DISCORD_PRESENCE, {
|
||||
new MenuItem({label: t('discord_enable')!,
|
||||
click: () => createModalWindow(WindowType.DISCORD_PRESENCE, {
|
||||
friend_nsa_id: nso.nsaId,
|
||||
}, {
|
||||
parent: window,
|
||||
modal: true,
|
||||
show: false,
|
||||
maximizable: false,
|
||||
minimizable: false,
|
||||
width: 560,
|
||||
height: 300,
|
||||
minWidth: 450,
|
||||
maxWidth: 700,
|
||||
minHeight: 300,
|
||||
maxHeight: 300,
|
||||
})}),
|
||||
}, window)}),
|
||||
]),
|
||||
new MenuItem({label: 'Enable friend notifications', type: 'checkbox',
|
||||
new MenuItem({label: t('friend_notifications_enable')!, type: 'checkbox',
|
||||
checked: monitor?.friend_notifications,
|
||||
click: () => app.menu?.setFriendNotificationsActive(user.id, !monitor?.friend_notifications)}),
|
||||
new MenuItem({label: 'Update now', enabled: !!monitor,
|
||||
new MenuItem({label: t('refresh')!, enabled: !!monitor,
|
||||
click: () => monitor?.skipIntervalInCurrentLoop(true)}),
|
||||
new MenuItem({type: 'separator'}),
|
||||
new MenuItem({label: 'Add friend',
|
||||
click: () => createWindow(WindowType.ADD_FRIEND, {
|
||||
new MenuItem({label: t('add_friend')!,
|
||||
click: () => createModalWindow(WindowType.ADD_FRIEND, {
|
||||
user: user.id,
|
||||
}, {
|
||||
parent: window,
|
||||
modal: true,
|
||||
show: false,
|
||||
maximizable: false,
|
||||
minimizable: false,
|
||||
width: 560,
|
||||
height: 300,
|
||||
minWidth: 450,
|
||||
maxWidth: 700,
|
||||
minHeight: 300,
|
||||
maxHeight: 300,
|
||||
})}),
|
||||
}, window)}),
|
||||
] : []),
|
||||
new MenuItem({type: 'separator'}),
|
||||
new MenuItem({label: 'Use the nxapi command to remove this user', enabled: false}),
|
||||
new MenuItem({label: t('remove_help')!, enabled: false}),
|
||||
]);
|
||||
}
|
||||
|
||||
function buildFriendMenu(app: App, user: NintendoAccountUser, nso: CurrentUser, friend: Friend) {
|
||||
function buildFriendMenu(app: App, user: NintendoAccountUser, nso: CurrentUser<true> | CurrentUser<false>, friend: Friend) {
|
||||
const t = app.i18n.getFixedT(null, 'menus', 'friend');
|
||||
const discord_presence_source = app.monitors.getDiscordPresenceSource();
|
||||
const discord_presence_active = !!discord_presence_source && 'na_id' in discord_presence_source &&
|
||||
discord_presence_source.na_id === user.id && discord_presence_source.friend_nsa_id === friend.nsaId;
|
||||
|
|
@ -297,34 +316,62 @@ function buildFriendMenu(app: App, user: NintendoAccountUser, nso: CurrentUser,
|
|||
return Menu.buildFromTemplate([
|
||||
...(!friend.presence.updatedAt ? [
|
||||
] : friend.presence.state === PresenceState.ONLINE || friend.presence.state === PresenceState.PLAYING ? [
|
||||
new MenuItem({label: 'Online', enabled: false}),
|
||||
new MenuItem({label: t(
|
||||
'platform' in friend.presence ?
|
||||
friend.presence.platform === PresencePlatform.NX ? 'presence_online_nx' :
|
||||
friend.presence.platform === PresencePlatform.OUNCE ? 'presence_online_ounce' :
|
||||
'presence_online' :
|
||||
'presence_online')!, enabled: false}),
|
||||
...('name' in friend.presence.game ? [
|
||||
new MenuItem({label: friend.presence.game.name, click: () =>
|
||||
shell.openExternal((friend.presence.game as Game).shopUri)}),
|
||||
...(friend.presence.game.sysDescription ? [
|
||||
new MenuItem({label: friend.presence.game.sysDescription, enabled: false}),
|
||||
] : []),
|
||||
new MenuItem({label: 'First played: ' + new Date(friend.presence.game.firstPlayedAt * 1000).toLocaleString('en-GB'), enabled: false}),
|
||||
new MenuItem({label: 'Play time: ' + hrduration(friend.presence.game.totalPlayTime), enabled: false}),
|
||||
new MenuItem({label: t('game_first_played', {
|
||||
date: new Date(friend.presence.game.firstPlayedAt * 1000),
|
||||
formatParams: { date: { dateStyle: 'short', timeStyle: 'medium' } },
|
||||
})!, enabled: false}),
|
||||
new MenuItem({label: friend.presence.game.totalPlayTime >= 60 ?
|
||||
friend.presence.game.totalPlayTime % 60 ?
|
||||
t('game_play_time_hm', {hours: Math.floor(friend.presence.game.totalPlayTime / 60),
|
||||
minutes: friend.presence.game.totalPlayTime % 60})! :
|
||||
t('game_play_time_h', {hours: friend.presence.game.totalPlayTime / 60})! :
|
||||
t('game_play_time_m', {minutes: friend.presence.game.totalPlayTime})!, enabled: false}),
|
||||
] : []),
|
||||
new MenuItem({label: 'Updated: ' + new Date(friend.presence.updatedAt * 1000).toLocaleString('en-GB'), enabled: false}),
|
||||
new MenuItem({label: t('presence_updated', {
|
||||
date: new Date(friend.presence.updatedAt * 1000),
|
||||
formatParams: { date: { dateStyle: 'short', timeStyle: 'medium' } },
|
||||
})!, enabled: false}),
|
||||
new MenuItem({type: 'separator'}),
|
||||
] : friend.presence.state === PresenceState.INACTIVE ? [
|
||||
new MenuItem({label: 'Offline (console online)', enabled: false}),
|
||||
new MenuItem({label: t('presence_inactive')!, enabled: false}),
|
||||
...(friend.presence.logoutAt ? [
|
||||
new MenuItem({label: 'Logout time: ' + new Date(friend.presence.logoutAt * 1000).toLocaleString('en-GB'), enabled: false}),
|
||||
new MenuItem({label: t('presence_logout_time', {
|
||||
date: new Date(friend.presence.logoutAt * 1000),
|
||||
formatParams: { date: { dateStyle: 'short', timeStyle: 'medium' } },
|
||||
})!, enabled: false}),
|
||||
] : []),
|
||||
new MenuItem({label: 'Updated: ' + new Date(friend.presence.updatedAt * 1000).toLocaleString('en-GB'), enabled: false}),
|
||||
new MenuItem({label: t('presence_updated', {
|
||||
date: new Date(friend.presence.updatedAt * 1000),
|
||||
formatParams: { date: { dateStyle: 'short', timeStyle: 'medium' } },
|
||||
})!, enabled: false}),
|
||||
new MenuItem({type: 'separator'}),
|
||||
] : [
|
||||
new MenuItem({label: 'Offline', enabled: false}),
|
||||
...(friend.presence.logoutAt ? [
|
||||
new MenuItem({label: 'Logout time: ' + new Date(friend.presence.logoutAt * 1000).toLocaleString('en-GB'), enabled: false}),
|
||||
new MenuItem({label: t('presence_logout_time', {
|
||||
date: new Date(friend.presence.logoutAt * 1000),
|
||||
formatParams: { date: { dateStyle: 'short', timeStyle: 'medium' } },
|
||||
})!, enabled: false}),
|
||||
] : []),
|
||||
new MenuItem({label: 'Updated: ' + new Date(friend.presence.updatedAt * 1000).toLocaleString('en-GB'), enabled: false}),
|
||||
new MenuItem({label: t('presence_updated', {
|
||||
date: new Date(friend.presence.updatedAt * 1000),
|
||||
formatParams: { date: { dateStyle: 'short', timeStyle: 'medium' } },
|
||||
})!, enabled: false}),
|
||||
new MenuItem({type: 'separator'}),
|
||||
]),
|
||||
new MenuItem({label: 'Enable Discord Presence', type: 'checkbox', checked: discord_presence_active, click: () =>
|
||||
new MenuItem({label: t('discord_presence_enable')!, type: 'checkbox', checked: discord_presence_active, click: () =>
|
||||
app.monitors.setDiscordPresenceSource(discord_presence_active ? null :
|
||||
{na_id: user.id, friend_nsa_id: friend.nsaId})}),
|
||||
]);
|
||||
|
|
|
|||
|
|
@ -1,22 +1,25 @@
|
|||
import { app, dialog, Menu, Tray, nativeImage, MenuItem, BrowserWindow, KeyboardEvent } from './electron.js';
|
||||
import { app, Menu, Tray, nativeImage, MenuItem, BrowserWindow, KeyboardEvent } from 'electron';
|
||||
import path from 'node:path';
|
||||
import * as util from 'node:util';
|
||||
import createDebug from 'debug';
|
||||
import { askAddNsoAccount, askAddPctlAccount } from './na-auth.js';
|
||||
import { App } from './index.js';
|
||||
import openWebService, { handleOpenWebServiceError, WebServiceValidationError } from './webservices.js';
|
||||
import { EmbeddedPresenceMonitor, EmbeddedProxyPresenceMonitor } from './monitor.js';
|
||||
import { createModalWindow } from './windows.js';
|
||||
import { WindowType } from '../common/types.js';
|
||||
import { CoralApiInterface } from '../../api/coral.js';
|
||||
import { WebService } from '../../api/coral-types.js';
|
||||
import openWebService, { WebServiceValidationError } from './webservices.js';
|
||||
import { SavedToken } from '../../common/auth/coral.js';
|
||||
import { SavedMoonToken } from '../../common/auth/moon.js';
|
||||
import { dev, dir } from '../../util/product.js';
|
||||
import { EmbeddedPresenceMonitor, EmbeddedProxyPresenceMonitor } from './monitor.js';
|
||||
import { createWindow } from './windows.js';
|
||||
import { WindowType } from '../common/types.js';
|
||||
import CoralApi from '../../api/coral.js';
|
||||
import { CachedWebServicesList } from '../../common/users.js';
|
||||
import createDebug from '../../util/debug.js';
|
||||
import { dev, dir, git } from '../../util/product.js';
|
||||
import { MembershipRequiredError } from '../../common/auth/util.js';
|
||||
import { languages } from '../i18n/index.js';
|
||||
|
||||
const debug = createDebug('app:main:menu');
|
||||
|
||||
const show_force_language_menu = dev || git?.branch?.match(/^(i18n$|trans-)/);
|
||||
|
||||
export default class MenuApp {
|
||||
tray: Tray;
|
||||
|
||||
|
|
@ -36,13 +39,18 @@ export default class MenuApp {
|
|||
this.updateMenu();
|
||||
});
|
||||
this.updateMenu();
|
||||
|
||||
app.i18n.on('languageChanged', language => this.updateMenu());
|
||||
}
|
||||
|
||||
async updateMenu() {
|
||||
await this.app.i18n.loadNamespaces('menu_app');
|
||||
const t = this.app.i18n.getFixedT(null, 'menu_app');
|
||||
|
||||
const menu = new Menu();
|
||||
|
||||
const ids = await this.app.store.storage.getItem('NintendoAccountIds') as string[] | undefined;
|
||||
menu.append(new MenuItem({label: 'Nintendo Switch Online', enabled: false}));
|
||||
menu.append(new MenuItem({label: t('coral_heading')!, enabled: false}));
|
||||
|
||||
const discord_presence_monitor = this.getActiveDiscordPresenceMonitor();
|
||||
|
||||
|
|
@ -53,35 +61,36 @@ export default class MenuApp {
|
|||
if (!data) continue;
|
||||
|
||||
const monitor = this.app.monitors.monitors.find(m => m instanceof EmbeddedPresenceMonitor &&
|
||||
m.data.user.id === data.user.id);
|
||||
const discord_presence_active = discord_presence_monitor instanceof EmbeddedPresenceMonitor &&
|
||||
discord_presence_monitor?.data?.user.id === data.user.id;
|
||||
m.user.data.user.id === data.user.id);
|
||||
const discord_presence_active = discord_presence_monitor &&
|
||||
discord_presence_monitor instanceof EmbeddedPresenceMonitor &&
|
||||
discord_presence_monitor.user.data.user.id === data.user.id;
|
||||
|
||||
const webservices = await this.getWebServiceItems(data.user.language, token);
|
||||
|
||||
const item = new MenuItem({
|
||||
label: data.nsoAccount.user.name,
|
||||
submenu: [
|
||||
{label: 'Nintendo Account ID: ' + data.user.id, enabled: false},
|
||||
{label: 'Coral ID: ' + data.nsoAccount.user.id, enabled: false},
|
||||
{label: 'NSA ID: ' + data.nsoAccount.user.nsaId, enabled: false},
|
||||
{label: t('na_id', {id: data.user.id})!, enabled: false},
|
||||
{label: t('coral_id', {id: data.nsoAccount.user.id})!, enabled: false},
|
||||
{label: t('nsa_id', {id: data.nsoAccount.user.nsaId})!, enabled: false},
|
||||
{type: 'separator'},
|
||||
{label: 'Enable Discord Presence', type: 'checkbox', checked: discord_presence_active,
|
||||
{label: t('discord_presence_enable')!, type: 'checkbox', checked: discord_presence_active,
|
||||
enabled: discord_presence_active,
|
||||
click: () => this.setActiveDiscordPresenceUser(discord_presence_active ? null : data.user.id)},
|
||||
{label: 'Enable notifications for this user\'s presence', type: 'checkbox',
|
||||
{label: t('user_notifications_enable')!, type: 'checkbox',
|
||||
checked: monitor?.user_notifications,
|
||||
enabled: !!monitor?.user_notifications,
|
||||
click: () => this.setUserNotificationsActive(data.user.id, !monitor?.user_notifications)},
|
||||
{label: 'Enable notifications for friends of this user\'s presence', type: 'checkbox',
|
||||
{label: t('friend_notifications_enable')!, type: 'checkbox',
|
||||
checked: monitor?.friend_notifications,
|
||||
click: () => this.setFriendNotificationsActive(data.user.id, !monitor?.friend_notifications)},
|
||||
{label: 'Update now', enabled: !!monitor, click: () => monitor?.skipIntervalInCurrentLoop(true)},
|
||||
{label: t('refresh')!, enabled: !!monitor, click: () => monitor?.skipIntervalInCurrentLoop(true)},
|
||||
{type: 'separator'},
|
||||
{label: 'Add friend', click: () => this.showAddFriendWindow(data.user.id)},
|
||||
{label: t('add_friend')!, click: () => this.showAddFriendWindow(data.user.id)},
|
||||
...(webservices.length ? [
|
||||
{type: 'separator'},
|
||||
{label: 'Web services', enabled: false},
|
||||
{label: t('web_services')!, enabled: false},
|
||||
...webservices as any,
|
||||
] : []),
|
||||
],
|
||||
|
|
@ -90,9 +99,9 @@ export default class MenuApp {
|
|||
menu.append(item);
|
||||
}
|
||||
|
||||
menu.append(new MenuItem({label: 'Add account', click: this.addNsoAccount}));
|
||||
menu.append(new MenuItem({label: t('add_account')!, click: this.addNsoAccount}));
|
||||
menu.append(new MenuItem({type: 'separator'}));
|
||||
menu.append(new MenuItem({label: 'Nintendo Switch Parental Controls', enabled: false}));
|
||||
menu.append(new MenuItem({label: t('moon_heading')!, enabled: false}));
|
||||
|
||||
for (const id of ids ?? []) {
|
||||
const token = await this.app.store.storage.getItem('NintendoAccountToken-pctl.' + id) as string | undefined;
|
||||
|
|
@ -103,31 +112,39 @@ export default class MenuApp {
|
|||
const item = new MenuItem({
|
||||
label: data.user.nickname,
|
||||
submenu: [
|
||||
{label: 'Nintendo Account ID: ' + data.user.id, enabled: false},
|
||||
{label: t('na_id', {id: data.user.id})!, enabled: false},
|
||||
],
|
||||
});
|
||||
|
||||
menu.append(item);
|
||||
}
|
||||
|
||||
menu.append(new MenuItem({label: 'Add account', click: this.addPctlAccount}));
|
||||
menu.append(new MenuItem({label: t('add_account')!, click: this.addPctlAccount}));
|
||||
|
||||
menu.append(new MenuItem({type: 'separator'}));
|
||||
menu.append(new MenuItem({label: 'Show main window', click: () => this.app.showMainWindow()}));
|
||||
menu.append(new MenuItem({label: 'Preferences', click: () => this.app.showPreferencesWindow()}));
|
||||
menu.append(new MenuItem({label: t('show_main_window')!, click: () => this.app.showMainWindow()}));
|
||||
menu.append(new MenuItem({label: t('preferences')!, click: () => this.app.showPreferencesWindow()}));
|
||||
if (show_force_language_menu) menu.append(new MenuItem({label: 'Language', submenu: Menu.buildFromTemplate([
|
||||
...this.app.i18n.options.supportedLngs || ['cimode'],
|
||||
].map(l => new MenuItem({
|
||||
label: languages[l as keyof typeof languages]?.name ?? l,
|
||||
type: 'checkbox',
|
||||
checked: (this.app.i18n.resolvedLanguage ?? this.app.i18n.language).toLowerCase() === l.toLowerCase(),
|
||||
click: () => this.app.i18n.changeLanguage(l),
|
||||
})))}));
|
||||
if (dev) menu.append(new MenuItem({label: 'Dump notifications state', click: () => {
|
||||
debug('Accounts', this.app.monitors.notifications.accounts);
|
||||
debug('Friends', this.app.monitors.notifications.onlinefriends);
|
||||
}}));
|
||||
menu.append(new MenuItem({label: 'Quit', click: () => app.quit()}));
|
||||
menu.append(new MenuItem({label: t('quit')!, click: () => app.quit()}));
|
||||
|
||||
this.tray.setContextMenu(menu);
|
||||
}
|
||||
|
||||
addNsoAccount = (item: MenuItem, window: BrowserWindow | undefined, event: KeyboardEvent) =>
|
||||
askAddNsoAccount(this.app.store.storage, !event.shiftKey);
|
||||
askAddNsoAccount(this.app, !event.shiftKey);
|
||||
addPctlAccount = (item: MenuItem, window: BrowserWindow | undefined, event: KeyboardEvent) =>
|
||||
askAddPctlAccount(this.app.store.storage, !event.shiftKey);
|
||||
askAddPctlAccount(this.app, !event.shiftKey);
|
||||
|
||||
protected webservices = new Map</** language */ string, WebService[]>();
|
||||
|
||||
|
|
@ -155,11 +172,7 @@ export default class MenuApp {
|
|||
|
||||
await this.openWebService(token, nso, data, webservice);
|
||||
} catch (err) {
|
||||
dialog.showMessageBox({
|
||||
type: 'error',
|
||||
message: (err instanceof Error ? err.name : 'Error') + ' opening web service',
|
||||
detail: '' + (err instanceof Error ? err.stack ?? err.message : err),
|
||||
});
|
||||
handleOpenWebServiceError(err, webservice);
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
|
@ -168,26 +181,13 @@ export default class MenuApp {
|
|||
return items;
|
||||
}
|
||||
|
||||
async openWebService(token: string, nso: CoralApi, data: SavedToken, webservice: WebService) {
|
||||
async openWebService(token: string, coral: CoralApiInterface, data: SavedToken, webservice: WebService) {
|
||||
try {
|
||||
await openWebService(this.app.store, token, nso, data, webservice);
|
||||
await openWebService(this.app.store, token, coral, data, webservice);
|
||||
} catch (err) {
|
||||
if (!(err instanceof WebServiceValidationError)) return;
|
||||
if (!(err instanceof WebServiceValidationError) && !(err instanceof MembershipRequiredError)) return;
|
||||
|
||||
dialog.showMessageBox({
|
||||
type: 'error',
|
||||
message: (err instanceof Error ? err.name : 'Error') + ' opening web service',
|
||||
detail: (err instanceof Error ? err.stack ?? err.message : err) + '\n\n' + util.inspect({
|
||||
webservice: {
|
||||
id: webservice.id,
|
||||
name: webservice.name,
|
||||
uri: webservice.uri,
|
||||
},
|
||||
user_na_id: data.user.id,
|
||||
user_nsa_id: data.nsoAccount.user.nsaId,
|
||||
user_coral_id: data.nsoAccount.user.id,
|
||||
}, {compact: true}),
|
||||
});
|
||||
handleOpenWebServiceError(err, webservice, undefined, data);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -205,7 +205,7 @@ export default class MenuApp {
|
|||
const monitor = this.getActiveDiscordPresenceMonitor();
|
||||
|
||||
if (monitor) {
|
||||
if (monitor instanceof EmbeddedPresenceMonitor && monitor.data.user.id === id) return;
|
||||
if (monitor instanceof EmbeddedPresenceMonitor && monitor.user.data.user.id === id) return;
|
||||
|
||||
monitor.discord.updatePresenceForDiscord(null);
|
||||
|
||||
|
|
@ -213,7 +213,7 @@ export default class MenuApp {
|
|||
monitor.presence_user = null;
|
||||
|
||||
if (!monitor.user_notifications && !monitor.friend_notifications) {
|
||||
this.app.monitors.stop(monitor.data.user.id);
|
||||
this.app.monitors.stop(monitor.user.data.user.id);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -223,7 +223,7 @@ export default class MenuApp {
|
|||
}
|
||||
|
||||
if (id) await this.app.monitors.start(id, monitor => {
|
||||
monitor.presence_user = monitor.data.nsoAccount.user.nsaId;
|
||||
monitor.presence_user = monitor.user.data.nsoAccount.user.nsaId;
|
||||
monitor.skipIntervalInCurrentLoop();
|
||||
});
|
||||
|
||||
|
|
@ -231,13 +231,14 @@ export default class MenuApp {
|
|||
}
|
||||
|
||||
async setUserNotificationsActive(id: string, active: boolean) {
|
||||
const monitor = this.app.monitors.monitors.find(m => m instanceof EmbeddedPresenceMonitor && m.data.user.id === id);
|
||||
const monitor = this.app.monitors.monitors.find(m => m instanceof EmbeddedPresenceMonitor &&
|
||||
m.user.data.user.id === id);
|
||||
|
||||
if (monitor?.user_notifications && !active) {
|
||||
monitor.user_notifications = false;
|
||||
|
||||
if (!monitor.presence_user && !monitor.friend_notifications) {
|
||||
this.app.monitors.stop(monitor.data.user.id);
|
||||
this.app.monitors.stop(monitor.user.data.user.id);
|
||||
}
|
||||
|
||||
monitor.skipIntervalInCurrentLoop();
|
||||
|
|
@ -252,13 +253,14 @@ export default class MenuApp {
|
|||
}
|
||||
|
||||
async setFriendNotificationsActive(id: string, active: boolean) {
|
||||
const monitor = this.app.monitors.monitors.find(m => m instanceof EmbeddedPresenceMonitor && m.data.user.id === id);
|
||||
const monitor = this.app.monitors.monitors.find(m => m instanceof EmbeddedPresenceMonitor &&
|
||||
m.user.data.user.id === id);
|
||||
|
||||
if (monitor?.friend_notifications && !active) {
|
||||
monitor.friend_notifications = false;
|
||||
|
||||
if (!monitor.presence_user && !monitor.user_notifications) {
|
||||
this.app.monitors.stop(monitor.data.user.id);
|
||||
this.app.monitors.stop(monitor.user.data.user.id);
|
||||
}
|
||||
|
||||
monitor.skipIntervalInCurrentLoop();
|
||||
|
|
@ -286,18 +288,8 @@ export default class MenuApp {
|
|||
}
|
||||
|
||||
showAddFriendWindow(user: string) {
|
||||
createWindow(WindowType.ADD_FRIEND, {
|
||||
createModalWindow(WindowType.ADD_FRIEND, {
|
||||
user,
|
||||
}, {
|
||||
show: false,
|
||||
maximizable: false,
|
||||
minimizable: false,
|
||||
width: 560,
|
||||
height: 300,
|
||||
minWidth: 450,
|
||||
maxWidth: 700,
|
||||
minHeight: 300,
|
||||
maxHeight: 300,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,26 +1,35 @@
|
|||
import { dialog, Notification } from './electron.js';
|
||||
import createDebug from 'debug';
|
||||
import { CurrentUser, Friend, Game, CoralErrorResponse } from '../../api/coral-types.js';
|
||||
import { Notification } from 'electron';
|
||||
import { i18n } from 'i18next';
|
||||
import { LocalStorage } from 'node-persist';
|
||||
import { App } from './index.js';
|
||||
import { showErrorDialog, tryGetNativeImageFromUrl } from './util.js';
|
||||
import { DiscordPresenceConfiguration, DiscordPresenceExternalMonitorsConfiguration, DiscordPresenceSource, DiscordStatus } from '../common/types.js';
|
||||
import { CurrentUser, Friend, CoralError, PresenceGame } from '../../api/coral-types.js';
|
||||
import { ErrorResponse } from '../../api/util.js';
|
||||
import { ZncDiscordPresence, ZncProxyDiscordPresence } from '../../common/presence.js';
|
||||
import { NotificationManager } from '../../common/notify.js';
|
||||
import createDebug from '../../util/debug.js';
|
||||
import { LoopResult } from '../../util/loop.js';
|
||||
import { tryGetNativeImageFromUrl } from './util.js';
|
||||
import { App } from './index.js';
|
||||
import { DiscordPresenceConfiguration, DiscordPresenceExternalMonitorsConfiguration, DiscordPresenceSource } from '../common/types.js';
|
||||
import { DiscordPresence, DiscordPresencePlayTime, ErrorResult } from '../../discord/types.js';
|
||||
import { DiscordRpcClient } from '../../discord/rpc.js';
|
||||
import SplatNet3Monitor, { getConfigFromAppConfig as getSplatNet3MonitorConfigFromAppConfig } from '../../discord/monitor/splatoon3.js';
|
||||
import { ErrorDescription } from '../../util/errors.js';
|
||||
import { CoralApiInterface, CoralErrorResponse } from '../../api/coral.js';
|
||||
import { NintendoAccountAuthErrorResponse, NintendoAccountErrorResponse } from '../../api/na.js';
|
||||
import { InvalidNintendoAccountTokenError } from '../../common/auth/na.js';
|
||||
import { CoralUser } from '../../common/users.js';
|
||||
|
||||
const debug = createDebug('app:main:monitor');
|
||||
|
||||
export class PresenceMonitorManager {
|
||||
monitors: (EmbeddedPresenceMonitor | EmbeddedProxyPresenceMonitor)[] = [];
|
||||
notifications = new ElectronNotificationManager();
|
||||
notifications: NotificationManager;
|
||||
|
||||
constructor(
|
||||
public app: App
|
||||
) {}
|
||||
) {
|
||||
this.notifications = new ElectronNotificationManager(app.i18n);
|
||||
}
|
||||
|
||||
async start(id: string, callback?: (monitor: EmbeddedPresenceMonitor, firstRun: boolean) => Promise<void> | void) {
|
||||
debug('Starting monitor', id);
|
||||
|
|
@ -30,18 +39,21 @@ export class PresenceMonitorManager {
|
|||
|
||||
const user = await this.app.store.users.get(token);
|
||||
|
||||
const existing = this.monitors.find(m => m instanceof EmbeddedPresenceMonitor && m.data.user.id === user.data.user.id);
|
||||
const existing = this.monitors.find(m => m instanceof EmbeddedPresenceMonitor &&
|
||||
m.user.data.user.id === user.data.user.id);
|
||||
|
||||
if (existing) {
|
||||
await callback?.call(null, existing as EmbeddedPresenceMonitor, false);
|
||||
return existing;
|
||||
}
|
||||
|
||||
const i = new EmbeddedPresenceMonitor(this.app.store.storage, token, user.nso, user.data, user);
|
||||
const i = new EmbeddedPresenceMonitor(user, this.app.store.storage, token);
|
||||
|
||||
i.notifications = this.notifications;
|
||||
i.presence_user = null;
|
||||
i.user_notifications = false;
|
||||
i.friend_notifications = false;
|
||||
i.discord_preconnect = true;
|
||||
|
||||
i.discord.onUpdateActivity = (presence: DiscordPresence | null) => {
|
||||
this.app.store.emit('update-discord-presence', presence ? {...presence, config: undefined} : null);
|
||||
|
|
@ -50,14 +62,16 @@ export class PresenceMonitorManager {
|
|||
this.app.store.emit('update-discord-user', client?.user ?? null);
|
||||
};
|
||||
i.discord.onMonitorError = async (monitor, instance, err) => {
|
||||
const {response} = await dialog.showMessageBox({
|
||||
const {response} = await showErrorDialog({
|
||||
message: err.name + ' in external monitor ' + monitor.name,
|
||||
detail: err.stack ?? err.message,
|
||||
type: 'error',
|
||||
error: err,
|
||||
buttons: ['OK', 'Retry', 'Stop'],
|
||||
defaultId: 0,
|
||||
});
|
||||
|
||||
const show_error_alerts: boolean = await this.app.store.storage.getItem('ShowErrorAlertsPreference') ?? false;
|
||||
if (!show_error_alerts) return ErrorResult.DEFER;
|
||||
|
||||
if (response === 1) {
|
||||
return ErrorResult.RETRY;
|
||||
}
|
||||
|
|
@ -68,6 +82,19 @@ export class PresenceMonitorManager {
|
|||
return ErrorResult.IGNORE;
|
||||
};
|
||||
|
||||
i.discord.onUpdateError = err => {
|
||||
const status: DiscordStatus = {
|
||||
error_message: err instanceof Error ?
|
||||
err.name + ': ' + err.message :
|
||||
ErrorDescription.getErrorDescription(err),
|
||||
};
|
||||
this.app.store.emit('update-discord-status', status);
|
||||
};
|
||||
i.discord.onUpdateSuccess = () => {
|
||||
const status: DiscordStatus = {error_message: null};
|
||||
this.app.store.emit('update-discord-status', status);
|
||||
};
|
||||
|
||||
i.onError = err => this.handleError(i, err);
|
||||
|
||||
this.monitors.push(i);
|
||||
|
|
@ -87,7 +114,9 @@ export class PresenceMonitorManager {
|
|||
|
||||
const i = new EmbeddedProxyPresenceMonitor(presence_url);
|
||||
|
||||
i.status_updates = this.app.statusupdates;
|
||||
i.notifications = this.notifications;
|
||||
i.discord_preconnect = true;
|
||||
|
||||
i.discord.onUpdateActivity = (presence: DiscordPresence | null) => {
|
||||
this.app.store.emit('update-discord-presence', presence ? {...presence, config: undefined} : null);
|
||||
|
|
@ -96,6 +125,19 @@ export class PresenceMonitorManager {
|
|||
this.app.store.emit('update-discord-user', client?.user ?? null);
|
||||
};
|
||||
|
||||
i.discord.onUpdateError = err => {
|
||||
const status: DiscordStatus = {
|
||||
error_message: err instanceof Error ?
|
||||
err.name + ': ' + err.message :
|
||||
ErrorDescription.getErrorDescription(err),
|
||||
};
|
||||
this.app.store.emit('update-discord-status', status);
|
||||
};
|
||||
i.discord.onUpdateSuccess = () => {
|
||||
const status: DiscordStatus = {error_message: null};
|
||||
this.app.store.emit('update-discord-status', status);
|
||||
};
|
||||
|
||||
i.onError = err => this.handleError(i, err);
|
||||
|
||||
this.monitors.push(i);
|
||||
|
|
@ -108,7 +150,7 @@ export class PresenceMonitorManager {
|
|||
async stop(id: string) {
|
||||
let index;
|
||||
while ((index = this.monitors.findIndex(m =>
|
||||
(m instanceof EmbeddedPresenceMonitor && m.data.user.id === id) ||
|
||||
(m instanceof EmbeddedPresenceMonitor && m.user.data.user.id === id) ||
|
||||
(m instanceof EmbeddedProxyPresenceMonitor && m.presence_url === id)
|
||||
)) >= 0) {
|
||||
const i = this.monitors[index];
|
||||
|
|
@ -118,6 +160,11 @@ export class PresenceMonitorManager {
|
|||
i.disable();
|
||||
|
||||
if (i instanceof EmbeddedPresenceMonitor) this.notifications.removeAccount(id);
|
||||
|
||||
if (i instanceof EmbeddedProxyPresenceMonitor) {
|
||||
i.status_update_source?.cancel();
|
||||
i.status_update_source = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -243,8 +290,8 @@ export class PresenceMonitorManager {
|
|||
return monitor instanceof EmbeddedProxyPresenceMonitor ? {
|
||||
url: monitor.presence_url,
|
||||
} : {
|
||||
na_id: monitor.data.user.id,
|
||||
friend_nsa_id: monitor.presence_user === monitor.data.nsoAccount.user.nsaId ? undefined :
|
||||
na_id: monitor.user.data.user.id,
|
||||
friend_nsa_id: monitor.presence_user === monitor.user.data.nsoAccount.user.nsaId ? undefined :
|
||||
monitor.presence_user ?? undefined,
|
||||
};
|
||||
}
|
||||
|
|
@ -257,11 +304,11 @@ export class PresenceMonitorManager {
|
|||
|
||||
if (source && 'na_id' in source &&
|
||||
existing && existing instanceof EmbeddedPresenceMonitor &&
|
||||
existing.data.user.id === source.na_id &&
|
||||
existing.presence_user !== (source.friend_nsa_id ?? existing.data.nsoAccount.user.nsaId)
|
||||
existing.user.data.user.id === source.na_id &&
|
||||
existing.presence_user !== (source.friend_nsa_id ?? existing.user.data.nsoAccount.user.nsaId)
|
||||
) {
|
||||
await this.start(source.na_id, monitor => {
|
||||
monitor.presence_user = source.friend_nsa_id ?? monitor.data.nsoAccount.user.nsaId;
|
||||
monitor.presence_user = source.friend_nsa_id ?? monitor.user.data.nsoAccount.user.nsaId;
|
||||
this.setDiscordPresenceSourceCopyConfiguration(monitor, existing);
|
||||
callback?.call(null, monitor);
|
||||
monitor.discord.refreshExternalMonitorsConfig();
|
||||
|
|
@ -274,7 +321,7 @@ export class PresenceMonitorManager {
|
|||
|
||||
if (existing) {
|
||||
if (source && (
|
||||
('na_id' in source && existing instanceof EmbeddedPresenceMonitor && existing.data.user.id === source.na_id) ||
|
||||
('na_id' in source && existing instanceof EmbeddedPresenceMonitor && existing.user.data.user.id === source.na_id) ||
|
||||
('url' in source && existing instanceof EmbeddedProxyPresenceMonitor && existing.presence_url === source.url)
|
||||
)) {
|
||||
callback?.call(null, existing);
|
||||
|
|
@ -287,7 +334,7 @@ export class PresenceMonitorManager {
|
|||
existing.presence_user = null;
|
||||
|
||||
if (!existing.user_notifications && !existing.friend_notifications) {
|
||||
this.stop(existing.data.user.id);
|
||||
this.stop(existing.user.data.user.id);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -298,7 +345,7 @@ export class PresenceMonitorManager {
|
|||
|
||||
if (source && 'na_id' in source) {
|
||||
await this.start(source.na_id, async monitor => {
|
||||
monitor.presence_user = source.friend_nsa_id ?? monitor.data.nsoAccount.user.nsaId;
|
||||
monitor.presence_user = source.friend_nsa_id ?? monitor.user.data.nsoAccount.user.nsaId;
|
||||
if (existing) this.setDiscordPresenceSourceCopyConfiguration(monitor, existing);
|
||||
else await this.setDiscordPresenceSourceRestoreSavedConfiguration(monitor);
|
||||
callback?.call(null, monitor);
|
||||
|
|
@ -316,6 +363,8 @@ export class PresenceMonitorManager {
|
|||
this.app.store.saveMonitorState(this);
|
||||
this.app.menu?.updateMenu();
|
||||
this.app.store.emit('update-discord-presence-source', source);
|
||||
} else {
|
||||
this.app.store.emit('update-discord-status', null);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -344,12 +393,18 @@ export class PresenceMonitorManager {
|
|||
|
||||
async handleError(
|
||||
monitor: EmbeddedPresenceMonitor | EmbeddedProxyPresenceMonitor,
|
||||
err: ErrorResponse<CoralErrorResponse> | NodeJS.ErrnoException
|
||||
err: ErrorResponse<CoralError> | NodeJS.ErrnoException
|
||||
): Promise<LoopResult> {
|
||||
const {response} = await dialog.showMessageBox({
|
||||
if (monitor instanceof EmbeddedProxyPresenceMonitor || checkShouldIgnorePresenceMonitorError(err)) {
|
||||
return LoopResult.OK;
|
||||
}
|
||||
|
||||
const show_error_alerts: boolean = await this.app.store.storage.getItem('ShowErrorAlertsPreference') ?? false;
|
||||
if (!show_error_alerts) return LoopResult.DEFER_NEXT_UPDATE;
|
||||
|
||||
const {response} = await showErrorDialog({
|
||||
message: err.name + ' updating presence monitor',
|
||||
detail: err.stack ?? err.message,
|
||||
type: 'error',
|
||||
error: err,
|
||||
buttons: ['OK', 'Retry'],
|
||||
defaultId: 0,
|
||||
});
|
||||
|
|
@ -360,13 +415,43 @@ export class PresenceMonitorManager {
|
|||
|
||||
return LoopResult.OK;
|
||||
}
|
||||
|
||||
async getDiscordStatus(): Promise<DiscordStatus | null> {
|
||||
const monitor = this.getActiveDiscordPresenceMonitor();
|
||||
if (!monitor) return null;
|
||||
|
||||
return {
|
||||
error_message: monitor.discord.last_update_error ?
|
||||
monitor.discord.last_update_error instanceof Error ?
|
||||
monitor.discord.last_update_error.name + ': ' + monitor.discord.last_update_error.message :
|
||||
ErrorDescription.getErrorDescription(monitor.discord.last_update_error) : null,
|
||||
};
|
||||
}
|
||||
|
||||
async showDiscordPresenceLastUpdateError() {
|
||||
const monitor = this.getActiveDiscordPresenceMonitor();
|
||||
const error = monitor?.discord.last_update_error;
|
||||
if (!error) return;
|
||||
|
||||
await showErrorDialog({
|
||||
message: error.name + ' updating presence monitor',
|
||||
error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export class EmbeddedPresenceMonitor extends ZncDiscordPresence {
|
||||
notifications = new ElectronNotificationManager();
|
||||
onError?: (error: ErrorResponse<CoralErrorResponse> | NodeJS.ErrnoException) =>
|
||||
onError?: (error: ErrorResponse<CoralError> | NodeJS.ErrnoException) =>
|
||||
Promise<LoopResult | void> | LoopResult | void = undefined;
|
||||
|
||||
constructor(
|
||||
user: CoralUser<CoralApiInterface>,
|
||||
storage: LocalStorage,
|
||||
readonly token: string,
|
||||
) {
|
||||
super(user, storage);
|
||||
}
|
||||
|
||||
enable() {
|
||||
if (this._running !== 0) return;
|
||||
this._run();
|
||||
|
|
@ -401,13 +486,13 @@ export class EmbeddedPresenceMonitor extends ZncDiscordPresence {
|
|||
|
||||
await this.onStop?.();
|
||||
|
||||
debug('Monitor for user %s finished', this.data.nsoAccount.user.name);
|
||||
debug('Monitor for user %s finished', this.user.data.nsoAccount.user.name);
|
||||
} finally {
|
||||
this._running = 0;
|
||||
}
|
||||
}
|
||||
|
||||
async handleError(err: ErrorResponse<CoralErrorResponse> | NodeJS.ErrnoException): Promise<LoopResult> {
|
||||
async handleError(err: ErrorResponse<CoralError> | NodeJS.ErrnoException): Promise<LoopResult> {
|
||||
try {
|
||||
return await super.handleError(err);
|
||||
} catch (err: any) {
|
||||
|
|
@ -422,8 +507,8 @@ export class EmbeddedPresenceMonitor extends ZncDiscordPresence {
|
|||
}
|
||||
|
||||
export class EmbeddedProxyPresenceMonitor extends ZncProxyDiscordPresence {
|
||||
notifications = new ElectronNotificationManager();
|
||||
onError?: (error: ErrorResponse<CoralErrorResponse> | NodeJS.ErrnoException) =>
|
||||
notifications: NotificationManager | null = null;
|
||||
onError?: (error: ErrorResponse<CoralError> | NodeJS.ErrnoException) =>
|
||||
Promise<LoopResult | void> | LoopResult | void = undefined;
|
||||
|
||||
enable() {
|
||||
|
|
@ -466,7 +551,7 @@ export class EmbeddedProxyPresenceMonitor extends ZncProxyDiscordPresence {
|
|||
}
|
||||
}
|
||||
|
||||
async handleError(err: ErrorResponse<CoralErrorResponse> | NodeJS.ErrnoException): Promise<LoopResult> {
|
||||
async handleError(err: ErrorResponse<CoralError> | NodeJS.ErrnoException): Promise<LoopResult> {
|
||||
try {
|
||||
return await super.handleError(err);
|
||||
} catch (err: any) {
|
||||
|
|
@ -481,44 +566,80 @@ export class EmbeddedProxyPresenceMonitor extends ZncProxyDiscordPresence {
|
|||
}
|
||||
|
||||
export class ElectronNotificationManager extends NotificationManager {
|
||||
async onFriendOnline(friend: CurrentUser | Friend, prev?: CurrentUser | Friend, naid?: string, ir?: boolean) {
|
||||
const currenttitle = friend.presence.game as Game;
|
||||
t: ReturnType<i18n['getFixedT']>;
|
||||
|
||||
constructor(i18n: i18n) {
|
||||
super();
|
||||
|
||||
this.t = i18n.getFixedT(null, 'notifications');
|
||||
}
|
||||
|
||||
async onFriendOnline(friend: CurrentUser<false> | Friend, prev?: CurrentUser<false> | Friend, naid?: string, ir?: boolean) {
|
||||
const currenttitle = friend.presence.game as PresenceGame;
|
||||
|
||||
new Notification({
|
||||
title: friend.name,
|
||||
body: 'Playing ' + currenttitle.name +
|
||||
(currenttitle.sysDescription ? '\n' + currenttitle.sysDescription : ''),
|
||||
icon: await tryGetNativeImageFromUrl(friend.imageUri),
|
||||
body: this.t('playing', {name: currenttitle.name +
|
||||
(currenttitle.sysDescription ? '\n' + currenttitle.sysDescription : '')})!,
|
||||
icon: await tryGetNativeImageFromUrl(friend.image2Uri),
|
||||
}).show();
|
||||
}
|
||||
|
||||
async onFriendOffline(friend: CurrentUser | Friend, prev?: CurrentUser | Friend, naid?: string, ir?: boolean) {
|
||||
async onFriendOffline(friend: CurrentUser<false> | Friend, prev?: CurrentUser<false> | Friend, naid?: string, ir?: boolean) {
|
||||
new Notification({
|
||||
title: friend.name,
|
||||
body: 'Offline',
|
||||
icon: await tryGetNativeImageFromUrl(friend.imageUri),
|
||||
body: this.t('offline')!,
|
||||
icon: await tryGetNativeImageFromUrl(friend.image2Uri),
|
||||
}).show();
|
||||
}
|
||||
|
||||
async onFriendPlayingChangeTitle(friend: CurrentUser | Friend, prev?: CurrentUser | Friend, naid?: string, ir?: boolean) {
|
||||
const currenttitle = friend.presence.game as Game;
|
||||
async onFriendPlayingChangeTitle(friend: CurrentUser<false> | Friend, prev?: CurrentUser<false> | Friend, naid?: string, ir?: boolean) {
|
||||
const currenttitle = friend.presence.game as PresenceGame;
|
||||
|
||||
new Notification({
|
||||
title: friend.name,
|
||||
body: 'Playing ' + currenttitle.name +
|
||||
(currenttitle.sysDescription ? '\n' + currenttitle.sysDescription : ''),
|
||||
icon: await tryGetNativeImageFromUrl(friend.imageUri),
|
||||
body: this.t('playing', {name: currenttitle.name +
|
||||
(currenttitle.sysDescription ? '\n' + currenttitle.sysDescription : '')})!,
|
||||
icon: await tryGetNativeImageFromUrl(friend.image2Uri),
|
||||
}).show();
|
||||
}
|
||||
|
||||
async onFriendTitleStateChange(friend: CurrentUser | Friend, prev?: CurrentUser | Friend, naid?: string, ir?: boolean) {
|
||||
const currenttitle = friend.presence.game as Game;
|
||||
async onFriendTitleStateChange(friend: CurrentUser<false> | Friend, prev?: CurrentUser<false> | Friend, naid?: string, ir?: boolean) {
|
||||
const currenttitle = friend.presence.game as PresenceGame;
|
||||
|
||||
new Notification({
|
||||
title: friend.name,
|
||||
body: 'Playing ' + currenttitle.name +
|
||||
(currenttitle.sysDescription ? '\n' + currenttitle.sysDescription : ''),
|
||||
icon: await tryGetNativeImageFromUrl(friend.imageUri),
|
||||
body: this.t('playing', {name: currenttitle.name +
|
||||
(currenttitle.sysDescription ? '\n' + currenttitle.sysDescription : '')})!,
|
||||
icon: await tryGetNativeImageFromUrl(friend.image2Uri),
|
||||
}).show();
|
||||
}
|
||||
}
|
||||
|
||||
function checkShouldIgnorePresenceMonitorError(err: Error): boolean {
|
||||
// Invalid session token, the user needs to sign in again
|
||||
if (err instanceof InvalidNintendoAccountTokenError) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Received error getting a Nintendo Account token; usually this means
|
||||
// the session token is invalid and the user needs to sign in again
|
||||
if (err instanceof NintendoAccountAuthErrorResponse && err.data) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Received error getting Nintendo Account user data
|
||||
// This can only happen once when the app starts and there isn't a cached token
|
||||
if (err instanceof NintendoAccountErrorResponse && err.data) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Received error from Coral (see CoralStatus in src/api/coral-types.ts)
|
||||
// This usually should either not happen (e.g. BAD_REQUEST), is something the
|
||||
// user needs to do (e.g. NSA_NOT_LINKED or UPGRADE_REQUIRED), or is permanent
|
||||
if (err instanceof CoralErrorResponse && err.data) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,51 +1,23 @@
|
|||
import { app, BrowserWindow, dialog, MessageBoxOptions, Notification, session, shell } from 'electron';
|
||||
import process from 'node:process';
|
||||
import * as crypto from 'node:crypto';
|
||||
import createDebug from 'debug';
|
||||
import * as persist from 'node-persist';
|
||||
import { app, BrowserWindow, dialog, MessageBoxOptions, Notification, session, shell } from './electron.js';
|
||||
import { getNintendoAccountSessionToken, NintendoAccountSessionToken } from '../../api/na.js';
|
||||
import { ZNCA_CLIENT_ID } from '../../api/coral.js';
|
||||
import { ZNMA_CLIENT_ID } from '../../api/moon.js';
|
||||
import { getToken, SavedToken } from '../../common/auth/coral.js';
|
||||
import { getPctlToken, SavedMoonToken } from '../../common/auth/moon.js';
|
||||
import { Jwt } from '../../util/jwt.js';
|
||||
import { App, protocol_registration_options } from './index.js';
|
||||
import { createModalWindow } from './windows.js';
|
||||
import { tryGetNativeImageFromUrl } from './util.js';
|
||||
import { ZNCA_API_USE_URL } from '../../common/constants.js';
|
||||
import { createWindow } from './windows.js';
|
||||
import { WindowType } from '../common/types.js';
|
||||
import { protocol_registration_options } from './index.js';
|
||||
import { NintendoAccountAuthErrorResponse, NintendoAccountSessionAuthorisation, NintendoAccountSessionAuthorisationError, NintendoAccountSessionToken } from '../../api/na.js';
|
||||
import { NintendoAccountSessionAuthorisationCoral } from '../../api/coral.js';
|
||||
import { NintendoAccountSessionAuthorisationMoon } from '../../api/moon.js';
|
||||
import { getToken } from '../../common/auth/coral.js';
|
||||
import { getPctlToken } from '../../common/auth/moon.js';
|
||||
import createDebug from '../../util/debug.js';
|
||||
import { Jwt } from '../../util/jwt.js';
|
||||
import { ZNCA_API_USE_TEXT, ZNCA_API_USE_URL, ZNCA_API_USE_VERSION } from '../../common/constants.js';
|
||||
import { InvalidNintendoAccountTokenError } from '../../common/auth/na.js';
|
||||
|
||||
const debug = createDebug('app:main:na-auth');
|
||||
|
||||
export type NintendoAccountAuthResult = NintendoAccountSessionToken;
|
||||
|
||||
export function getAuthUrl(client_id: string, scope: string | string[]) {
|
||||
const state = crypto.randomBytes(36).toString('base64url');
|
||||
const verifier = crypto.randomBytes(32).toString('base64url');
|
||||
const challenge = crypto.createHash('sha256').update(verifier).digest().toString('base64url');
|
||||
|
||||
const params = {
|
||||
state,
|
||||
redirect_uri: 'npf' + client_id + '://auth',
|
||||
client_id,
|
||||
scope: typeof scope === 'string' ? scope : scope.join(' '),
|
||||
response_type: 'session_token_code',
|
||||
session_token_code_challenge: challenge,
|
||||
session_token_code_challenge_method: 'S256',
|
||||
theme: 'login_form',
|
||||
};
|
||||
|
||||
const url = 'https://accounts.nintendo.com/connect/1.0.0/authorize?' +
|
||||
new URLSearchParams(params).toString();
|
||||
|
||||
return {
|
||||
url,
|
||||
state,
|
||||
verifier,
|
||||
challenge,
|
||||
};
|
||||
}
|
||||
|
||||
const css = `
|
||||
html {
|
||||
overflow-x: hidden;
|
||||
|
|
@ -54,7 +26,7 @@ html {
|
|||
|
||||
let i = 0;
|
||||
|
||||
export function createAuthWindow() {
|
||||
export function createAuthWindow(app: App) {
|
||||
const browser_session = session.defaultSession;
|
||||
|
||||
const window = new BrowserWindow({
|
||||
|
|
@ -63,7 +35,7 @@ export function createAuthWindow() {
|
|||
resizable: false,
|
||||
maximizable: false,
|
||||
fullscreenable: false,
|
||||
title: 'Nintendo Account',
|
||||
title: app.i18n.t('na_auth:window.title') ?? 'Nintendo Account',
|
||||
webPreferences: {
|
||||
session: browser_session,
|
||||
scrollBounce: true,
|
||||
|
|
@ -78,51 +50,45 @@ export function createAuthWindow() {
|
|||
}
|
||||
|
||||
export interface NintendoAccountSessionTokenCode {
|
||||
authenticator: NintendoAccountSessionAuthorisation;
|
||||
code: string;
|
||||
verifier: string;
|
||||
window?: BrowserWindow;
|
||||
}
|
||||
|
||||
export class AuthoriseError extends Error {
|
||||
constructor(readonly code: string, message?: string) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
static fromSearchParams(qs: URLSearchParams) {
|
||||
const code = qs.get('error') ?? 'unknown_error';
|
||||
return new AuthoriseError(code, qs.get('error_description') ?? code);
|
||||
}
|
||||
}
|
||||
|
||||
export class AuthoriseCancelError extends AuthoriseError {
|
||||
export class AuthoriseCancelError extends NintendoAccountSessionAuthorisationError {
|
||||
constructor(message?: string) {
|
||||
super('access_denied', message);
|
||||
}
|
||||
}
|
||||
|
||||
export function getSessionTokenCodeByInAppBrowser(client_id: string, scope: string | string[], close_window: false):
|
||||
Promise<NintendoAccountSessionTokenCode & {window: BrowserWindow}>
|
||||
export function getSessionTokenCodeByInAppBrowser(client_id: string, scope: string | string[], close_window: true):
|
||||
Promise<NintendoAccountSessionTokenCode & {window?: never}>
|
||||
export function getSessionTokenCodeByInAppBrowser(client_id: string, scope: string | string[], close_window?: boolean):
|
||||
Promise<NintendoAccountSessionTokenCode & {window?: BrowserWindow}>
|
||||
export function getSessionTokenCodeByInAppBrowser(client_id: string, scope: string | string[], close_window = true) {
|
||||
export function getSessionTokenCodeByInAppBrowser(
|
||||
app: App, authenticator: NintendoAccountSessionAuthorisation, close_window: false,
|
||||
): Promise<NintendoAccountSessionTokenCode & {window: BrowserWindow}>
|
||||
export function getSessionTokenCodeByInAppBrowser(
|
||||
app: App, authenticator: NintendoAccountSessionAuthorisation, close_window: true,
|
||||
): Promise<NintendoAccountSessionTokenCode & {window?: never}>
|
||||
export function getSessionTokenCodeByInAppBrowser(
|
||||
app: App, authenticator: NintendoAccountSessionAuthorisation, close_window?: boolean,
|
||||
): Promise<NintendoAccountSessionTokenCode & {window?: BrowserWindow}>
|
||||
|
||||
export function getSessionTokenCodeByInAppBrowser(
|
||||
app: App, authenticator: NintendoAccountSessionAuthorisation, close_window = true,
|
||||
) {
|
||||
return new Promise<NintendoAccountSessionTokenCode>((rs, rj) => {
|
||||
const {url: authoriseurl, state, verifier, challenge} = getAuthUrl(client_id, scope);
|
||||
const window = createAuthWindow();
|
||||
const window = createAuthWindow(app);
|
||||
|
||||
const handleAuthUrl = (url: URL) => {
|
||||
const authorisedparams = new URLSearchParams(url.hash.substr(1));
|
||||
debug('Redirect URL parameters', [...authorisedparams.entries()]);
|
||||
|
||||
if (authorisedparams.get('state') !== state) {
|
||||
if (authorisedparams.get('state') !== authenticator.state) {
|
||||
rj(new Error('Invalid state'));
|
||||
window.close();
|
||||
return;
|
||||
}
|
||||
|
||||
if (authorisedparams.has('error')) {
|
||||
rj(AuthoriseError.fromSearchParams(authorisedparams));
|
||||
rj(NintendoAccountSessionAuthorisationError.fromSearchParams(authorisedparams));
|
||||
window.close();
|
||||
return;
|
||||
}
|
||||
|
|
@ -140,15 +106,15 @@ export function getSessionTokenCodeByInAppBrowser(client_id: string, scope: stri
|
|||
|
||||
if (close_window) {
|
||||
rs({
|
||||
authenticator,
|
||||
code,
|
||||
verifier,
|
||||
});
|
||||
|
||||
window.close();
|
||||
} else {
|
||||
rs({
|
||||
authenticator,
|
||||
code,
|
||||
verifier,
|
||||
window,
|
||||
});
|
||||
}
|
||||
|
|
@ -159,7 +125,7 @@ export function getSessionTokenCodeByInAppBrowser(client_id: string, scope: stri
|
|||
|
||||
debug('will navigate', url);
|
||||
|
||||
if (url.protocol === 'npf' + client_id + ':' && url.host === 'auth') {
|
||||
if (url.protocol === 'npf' + authenticator.client_id + ':' && url.host === 'auth') {
|
||||
handleAuthUrl(url);
|
||||
event.preventDefault();
|
||||
} else if (url.origin === 'https://accounts.nintendo.com') {
|
||||
|
|
@ -182,7 +148,7 @@ export function getSessionTokenCodeByInAppBrowser(client_id: string, scope: stri
|
|||
|
||||
debug('open', details);
|
||||
|
||||
if (url.protocol === 'npf' + client_id + ':' && url.host === 'auth') {
|
||||
if (url.protocol === 'npf' + authenticator.client_id + ':' && url.host === 'auth') {
|
||||
handleAuthUrl(url);
|
||||
} else {
|
||||
shell.openExternal(details.url);
|
||||
|
|
@ -191,40 +157,34 @@ export function getSessionTokenCodeByInAppBrowser(client_id: string, scope: stri
|
|||
return {action: 'deny'};
|
||||
});
|
||||
|
||||
debug('Loading Nintendo Account authorisation', {
|
||||
authoriseurl,
|
||||
state,
|
||||
verifier,
|
||||
challenge,
|
||||
});
|
||||
debug('Loading Nintendo Account authorisation', authenticator);
|
||||
|
||||
window.loadURL(authoriseurl);
|
||||
window.loadURL(authenticator.authorise_url);
|
||||
});
|
||||
}
|
||||
|
||||
const FORCE_MANUAL_AUTH_URI_ENTRY = process.env.NXAPI_FORCE_MANUAL_AUTH === '1';
|
||||
|
||||
export function getSessionTokenCodeByDefaultBrowser(
|
||||
client_id: string, scope: string | string[],
|
||||
authenticator: NintendoAccountSessionAuthorisation,
|
||||
close_window = true,
|
||||
force_manual = FORCE_MANUAL_AUTH_URI_ENTRY
|
||||
) {
|
||||
return new Promise<NintendoAccountSessionTokenCode>((rs, rj) => {
|
||||
const {url: authoriseurl, state, verifier, challenge} = getAuthUrl(client_id, scope);
|
||||
let window: BrowserWindow | undefined = undefined;
|
||||
|
||||
const handleAuthUrl = (url: URL) => {
|
||||
const authorisedparams = new URLSearchParams(url.hash.substr(1));
|
||||
debug('Redirect URL parameters', [...authorisedparams.entries()]);
|
||||
|
||||
if (authorisedparams.get('state') !== state) {
|
||||
if (authorisedparams.get('state') !== authenticator.state) {
|
||||
rj(new Error('Invalid state'));
|
||||
window?.close();
|
||||
return;
|
||||
}
|
||||
|
||||
if (authorisedparams.has('error')) {
|
||||
rj(AuthoriseError.fromSearchParams(authorisedparams));
|
||||
rj(NintendoAccountSessionAuthorisationError.fromSearchParams(authorisedparams));
|
||||
window?.close();
|
||||
return;
|
||||
}
|
||||
|
|
@ -241,28 +201,23 @@ export function getSessionTokenCodeByDefaultBrowser(
|
|||
debug('code', code, jwt, sig);
|
||||
|
||||
if (window && close_window) window.close();
|
||||
else if (window) rs({code, verifier, window});
|
||||
else rs({code, verifier});
|
||||
else if (window) rs({authenticator, code, window});
|
||||
else rs({authenticator, code});
|
||||
};
|
||||
|
||||
debug('Prompting user for Nintendo Account authorisation', {
|
||||
authoriseurl,
|
||||
state,
|
||||
verifier,
|
||||
challenge,
|
||||
});
|
||||
debug('Prompting user for Nintendo Account authorisation', authenticator);
|
||||
|
||||
const protocol = 'npf' + client_id;
|
||||
const protocol = 'npf' + authenticator.client_id;
|
||||
|
||||
if (force_manual) {
|
||||
debug('Manual entry forced, prompting for redirect URI');
|
||||
window = askUserForRedirectUri(authoriseurl, client_id, handleAuthUrl, rj);
|
||||
window = askUserForRedirectUri(authenticator.authorise_url, authenticator.client_id, handleAuthUrl, rj);
|
||||
} else if (app.isDefaultProtocolClient(protocol,
|
||||
protocol_registration_options?.path, protocol_registration_options?.argv
|
||||
)) {
|
||||
debug('App is already default protocol handler, opening browser');
|
||||
auth_state.set(state, [handleAuthUrl, rj, protocol]);
|
||||
shell.openExternal(authoriseurl);
|
||||
auth_state.set(authenticator.state, [handleAuthUrl, rj, protocol]);
|
||||
shell.openExternal(authenticator.authorise_url);
|
||||
} else {
|
||||
const registered_app = app.getApplicationNameForProtocol(protocol);
|
||||
|
||||
|
|
@ -270,11 +225,11 @@ export function getSessionTokenCodeByDefaultBrowser(
|
|||
protocol_registration_options?.path, protocol_registration_options?.argv
|
||||
)) {
|
||||
debug('Another app is using the auth protocol or registration failed, prompting for redirect URI');
|
||||
window = askUserForRedirectUri(authoriseurl, client_id, handleAuthUrl, rj);
|
||||
window = askUserForRedirectUri(authenticator.authorise_url, authenticator.client_id, handleAuthUrl, rj);
|
||||
} else {
|
||||
debug('App is now default protocol handler, opening browser');
|
||||
auth_state.set(state, [handleAuthUrl, rj, protocol]);
|
||||
shell.openExternal(authoriseurl);
|
||||
auth_state.set(authenticator.state, [handleAuthUrl, rj, protocol]);
|
||||
shell.openExternal(authenticator.authorise_url);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
|
@ -312,19 +267,9 @@ function askUserForRedirectUri(
|
|||
authoriseurl: string, client_id: string,
|
||||
handleAuthUrl: (url: URL) => void, rj: (reason: any) => void
|
||||
) {
|
||||
const window = createWindow(WindowType.ADD_ACCOUNT_MANUAL_PROMPT, {
|
||||
const window = createModalWindow(WindowType.ADD_ACCOUNT_MANUAL_PROMPT, {
|
||||
authoriseurl,
|
||||
client_id,
|
||||
}, {
|
||||
show: false,
|
||||
maximizable: false,
|
||||
minimizable: false,
|
||||
width: 560,
|
||||
height: 300,
|
||||
minWidth: 450,
|
||||
maxWidth: 700,
|
||||
minHeight: 300,
|
||||
maxHeight: 300,
|
||||
});
|
||||
|
||||
window.webContents.on('will-navigate', (event, url_string) => {
|
||||
|
|
@ -354,10 +299,11 @@ const NSO_SCOPE = [
|
|||
'user.screenName',
|
||||
];
|
||||
|
||||
export async function addNsoAccount(storage: persist.LocalStorage, use_in_app_browser = true) {
|
||||
const {code, verifier, window} = use_in_app_browser ?
|
||||
await getSessionTokenCodeByInAppBrowser(ZNCA_CLIENT_ID, NSO_SCOPE, false) :
|
||||
await getSessionTokenCodeByDefaultBrowser(ZNCA_CLIENT_ID, NSO_SCOPE, false);
|
||||
export async function addNsoAccount(app: App, use_in_app_browser = true) {
|
||||
const authenticator = NintendoAccountSessionAuthorisationCoral.create();
|
||||
const {code, window} = use_in_app_browser ?
|
||||
await getSessionTokenCodeByInAppBrowser(app, authenticator, false) :
|
||||
await getSessionTokenCodeByDefaultBrowser(authenticator, false);
|
||||
|
||||
window?.setFocusable(false);
|
||||
window?.blurWebView();
|
||||
|
|
@ -365,101 +311,124 @@ export async function addNsoAccount(storage: persist.LocalStorage, use_in_app_br
|
|||
try {
|
||||
const [jwt, sig] = Jwt.decode(code);
|
||||
|
||||
const nsotoken = await storage.getItem('NintendoAccountToken.' + jwt.payload.sub) as string | undefined;
|
||||
const nsotoken = await app.store.storage.getItem('NintendoAccountToken.' + jwt.payload.sub) as string | undefined;
|
||||
|
||||
if (nsotoken) {
|
||||
const data = await storage.getItem('NsoToken.' + nsotoken) as SavedToken | undefined;
|
||||
debug('Already authenticated', jwt.payload);
|
||||
|
||||
debug('Already authenticated', data);
|
||||
try {
|
||||
const {nso, data} = await getToken(app.store.storage, nsotoken, process.env.ZNC_PROXY_URL, false);
|
||||
|
||||
new Notification({
|
||||
title: 'Nintendo Switch Online',
|
||||
body: 'Already signed in as ' + data?.nsoAccount.user.name + ' (' + data?.user.nickname + ')',
|
||||
icon: await tryGetNativeImageFromUrl(data!.nsoAccount.user.imageUri),
|
||||
}).show();
|
||||
new Notification({
|
||||
title: app.i18n.t('na_auth:notification_coral.title') ?? 'Nintendo Switch Online',
|
||||
body: app.i18n.t('na_auth:notification_coral.body_existing', {
|
||||
name: data.nsoAccount.user.name,
|
||||
na_name: data.user.nickname,
|
||||
na_username: data.user.screenName,
|
||||
}) ?? 'Already signed in as ' + data.nsoAccount.user.name + ' (Nintendo Account ' +
|
||||
data.user.nickname + ' / ' + data.user.screenName + ')',
|
||||
icon: await tryGetNativeImageFromUrl(data.nsoAccount.user.image2Uri ??
|
||||
data.nsoAccount.user.imageUri),
|
||||
}).show();
|
||||
|
||||
return getToken(storage, nsotoken, process.env.ZNC_PROXY_URL, false);
|
||||
return {nso, data};
|
||||
} catch (err) {
|
||||
if (
|
||||
(err instanceof InvalidNintendoAccountTokenError) ||
|
||||
(err instanceof NintendoAccountAuthErrorResponse && err.data?.error === 'invalid_grant')
|
||||
) {
|
||||
// The session token has expired/was revoked
|
||||
return authenticateCoralSessionToken(app, authenticator, code, true);
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
await checkZncaApiUseAllowed(storage, window);
|
||||
await checkZncaApiUseAllowed(app, window);
|
||||
|
||||
const token = await getNintendoAccountSessionToken(code, verifier, ZNCA_CLIENT_ID);
|
||||
|
||||
debug('session token', token);
|
||||
|
||||
const {nso, data} = await getToken(storage, token.session_token, process.env.ZNC_PROXY_URL, false);
|
||||
|
||||
const users = new Set(await storage.getItem('NintendoAccountIds') ?? []);
|
||||
users.add(data.user.id);
|
||||
await storage.setItem('NintendoAccountIds', [...users]);
|
||||
|
||||
new Notification({
|
||||
title: 'Nintendo Switch Online',
|
||||
body: 'Authenticated as ' + data.nsoAccount.user.name + ' (NSO ' + data.user.nickname + ')',
|
||||
icon: await tryGetNativeImageFromUrl(data.nsoAccount.user.imageUri),
|
||||
}).show();
|
||||
|
||||
return {nso, data};
|
||||
return authenticateCoralSessionToken(app, authenticator, code);
|
||||
} finally {
|
||||
window?.close();
|
||||
}
|
||||
}
|
||||
|
||||
export async function askAddNsoAccount(storage: persist.LocalStorage, iab = true) {
|
||||
try {
|
||||
return await addNsoAccount(storage, iab);
|
||||
} catch (err: any) {
|
||||
if (err instanceof AuthoriseError && err.code === 'access_denied') return;
|
||||
async function authenticateCoralSessionToken(
|
||||
app: App,
|
||||
authenticator: NintendoAccountSessionAuthorisation, code: string,
|
||||
reauthenticate = false,
|
||||
) {
|
||||
const token = await authenticator.getSessionToken(code);
|
||||
|
||||
dialog.showErrorBox('Error adding account', err.stack || err.message);
|
||||
debug('session token', token);
|
||||
|
||||
const {nso, data} = await getToken(app.store.storage, token.session_token, process.env.ZNC_PROXY_URL, false);
|
||||
|
||||
const users = new Set(await app.store.storage.getItem('NintendoAccountIds') ?? []);
|
||||
users.add(data.user.id);
|
||||
await app.store.storage.setItem('NintendoAccountIds', [...users]);
|
||||
|
||||
new Notification({
|
||||
title: app.i18n.t('na_auth:notification_coral.title') ?? 'Nintendo Switch Online',
|
||||
body: app.i18n.t('na_auth:notification_coral.body_' + (reauthenticate ? 're' : '') + 'authenticated', {
|
||||
name: data.nsoAccount.user.name,
|
||||
na_name: data.user.nickname,
|
||||
na_username: data.user.screenName,
|
||||
}) ?? (reauthenticate ?
|
||||
'Reauthenticated to ' + data.nsoAccount.user.name + ' (Nintendo Account ' + data.user.nickname + ' / ' +
|
||||
data.user.screenName + ')' :
|
||||
'Authenticated as ' + data.nsoAccount.user.name + ' (Nintendo Account ' + data.user.nickname + ' / ' +
|
||||
data.user.screenName + ')'),
|
||||
icon: await tryGetNativeImageFromUrl(data.nsoAccount.user.imageUri),
|
||||
}).show();
|
||||
|
||||
return {nso, data};
|
||||
}
|
||||
|
||||
export async function askAddNsoAccount(app: App, iab = true) {
|
||||
try {
|
||||
return await addNsoAccount(app, iab);
|
||||
} catch (err: any) {
|
||||
if (err instanceof NintendoAccountSessionAuthorisationError && err.code === 'access_denied') return;
|
||||
|
||||
dialog.showErrorBox(app.i18n.t('na_auth:error.title') ?? 'Error adding account',
|
||||
err.stack || err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function checkZncaApiUseAllowed(storage: persist.LocalStorage, window?: BrowserWindow, force = false) {
|
||||
export async function checkZncaApiUseAllowed(app: App, window?: BrowserWindow, force = false) {
|
||||
if (!force) {
|
||||
if (await storage.getItem('ZncaApiConsent')) {
|
||||
const saved = await app.store.storage.getItem('ZncaApiConsent');
|
||||
const consent_version = typeof saved === 'number' ? saved :
|
||||
typeof saved === 'boolean' ? (saved ? 1 : null) : null;
|
||||
|
||||
if (consent_version && consent_version === ZNCA_API_USE_VERSION) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (process.env.ZNC_PROXY_URL) {
|
||||
debug('Skipping znca API consent; znc proxy URL set');
|
||||
await storage.setItem('ZncaApiConsent', true);
|
||||
return;
|
||||
}
|
||||
|
||||
const ids: string[] | undefined = await storage.getItem('NintendoAccountIds');
|
||||
|
||||
for (const id of ids ?? []) {
|
||||
const nsotoken: string | undefined = await storage.getItem('NintendoAccountToken.' + id);
|
||||
if (!nsotoken) continue;
|
||||
|
||||
debug('Skipping znca API consent; Nintendo Switch Online account already linked');
|
||||
await storage.setItem('ZncaApiConsent', true);
|
||||
await app.store.storage.setItem('ZncaApiConsent', ZNCA_API_USE_VERSION);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (await askZncaApiUseAllowed(window)) {
|
||||
await storage.setItem('ZncaApiConsent', true);
|
||||
if (await askZncaApiUseAllowed(app, window)) {
|
||||
await app.store.storage.setItem('ZncaApiConsent', ZNCA_API_USE_VERSION);
|
||||
} else {
|
||||
throw new Error('Cannot continue without third-party APIs allowed');
|
||||
}
|
||||
}
|
||||
|
||||
const ZNCA_API_USE_TEXT = `To access the Nintendo Switch Online app API, nxapi must send some data to third-party APIs. This is required to generate some data to make Nintendo think you\'re using the real Nintendo Switch Online app.
|
||||
|
||||
By default, this uses the imink API, but another service can be used by setting an environment variable. The default API may change without notice if you do not force use of a specific service.
|
||||
|
||||
The data sent includes:
|
||||
|
||||
- When authenticating to the Nintendo Switch Online app: a Nintendo Account ID token, containing your Nintendo Account ID and country, which is valid for 15 minutes
|
||||
- When authenticating to game-specific services: a Coral (Nintendo Switch Online app) ID token, containing your Coral user ID, Nintendo Switch Online membership status, and Nintendo Account child restriction status, which is valid for 2 hours`;
|
||||
|
||||
async function askZncaApiUseAllowed(window?: BrowserWindow): Promise<boolean> {
|
||||
async function askZncaApiUseAllowed(app?: App, window?: BrowserWindow): Promise<boolean> {
|
||||
const options: MessageBoxOptions = {
|
||||
message: 'Third-party API usage',
|
||||
detail: ZNCA_API_USE_TEXT,
|
||||
buttons: ['OK', 'Cancel', 'More information'],
|
||||
message: app?.i18n.t('na_auth:znca_api_use.title') ?? 'Third-party API usage',
|
||||
detail: app?.i18n.t('na_auth:znca_api_use.text') ?? ZNCA_API_USE_TEXT,
|
||||
buttons: [
|
||||
app?.i18n.t('na_auth:znca_api_use.ok') ?? 'OK',
|
||||
app?.i18n.t('na_auth:znca_api_use.cancel') ?? 'Cancel',
|
||||
app?.i18n.t('na_auth:znca_api_use.more_information') ?? 'More information',
|
||||
],
|
||||
cancelId: 1,
|
||||
};
|
||||
|
||||
|
|
@ -471,7 +440,7 @@ async function askZncaApiUseAllowed(window?: BrowserWindow): Promise<boolean> {
|
|||
|
||||
if (result.response === 2) {
|
||||
shell.openExternal(ZNCA_API_USE_URL);
|
||||
return askZncaApiUseAllowed(window);
|
||||
return askZncaApiUseAllowed(app, window);
|
||||
}
|
||||
|
||||
return result.response === 0;
|
||||
|
|
@ -493,10 +462,11 @@ const MOON_SCOPE = [
|
|||
'moonMonthlySummary',
|
||||
];
|
||||
|
||||
export async function addPctlAccount(storage: persist.LocalStorage, use_in_app_browser = true) {
|
||||
const {code, verifier, window} = use_in_app_browser ?
|
||||
await getSessionTokenCodeByInAppBrowser(ZNMA_CLIENT_ID, MOON_SCOPE, false) :
|
||||
await getSessionTokenCodeByDefaultBrowser(ZNMA_CLIENT_ID, MOON_SCOPE, false);
|
||||
export async function addPctlAccount(app: App, use_in_app_browser = true) {
|
||||
const authenticator = NintendoAccountSessionAuthorisationMoon.create();
|
||||
const {code, window} = use_in_app_browser ?
|
||||
await getSessionTokenCodeByInAppBrowser(app, authenticator, false) :
|
||||
await getSessionTokenCodeByDefaultBrowser(authenticator, false);
|
||||
|
||||
window?.setFocusable(false);
|
||||
window?.blurWebView();
|
||||
|
|
@ -504,48 +474,77 @@ export async function addPctlAccount(storage: persist.LocalStorage, use_in_app_b
|
|||
try {
|
||||
const [jwt, sig] = Jwt.decode(code);
|
||||
|
||||
const moontoken = await storage.getItem('NintendoAccountToken-pctl.' + jwt.payload.sub) as string | undefined;
|
||||
const moontoken = await app.store.storage.getItem('NintendoAccountToken-pctl.' + jwt.payload.sub) as string | undefined;
|
||||
|
||||
if (moontoken) {
|
||||
const data = await storage.getItem('MoonToken.' + moontoken) as SavedMoonToken | undefined;
|
||||
debug('Already authenticated', jwt.payload);
|
||||
|
||||
debug('Already authenticated', data);
|
||||
try {
|
||||
const {moon, data} = await getPctlToken(app.store.storage, moontoken, false);
|
||||
|
||||
new Notification({
|
||||
title: 'Nintendo Switch Parental Controls',
|
||||
body: 'Already signed in as ' + data?.user.nickname,
|
||||
}).show();
|
||||
new Notification({
|
||||
title: app.i18n.t('na_auth:notification_moon.title') ?? 'Nintendo Switch Parental Controls',
|
||||
body: app.i18n.t('na_auth:notification_moon.body_existing', {
|
||||
na_name: data.user.nickname,
|
||||
na_username: data.user.screenName,
|
||||
}) ?? 'Already signed in as ' + data.user.nickname + ' (' + data.user.screenName + ')',
|
||||
}).show();
|
||||
|
||||
return getPctlToken(storage, moontoken, false);
|
||||
return {moon, data};
|
||||
} catch (err) {
|
||||
if (
|
||||
(err instanceof InvalidNintendoAccountTokenError) ||
|
||||
(err instanceof NintendoAccountAuthErrorResponse && err.data?.error === 'invalid_grant')
|
||||
) {
|
||||
// The session token has expired/was revoked
|
||||
return authenticateMoonSessionToken(app, authenticator, code, true);
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
const token = await getNintendoAccountSessionToken(code, verifier, ZNMA_CLIENT_ID);
|
||||
|
||||
debug('session token', token);
|
||||
|
||||
const {moon, data} = await getPctlToken(storage, token.session_token, false);
|
||||
|
||||
const users = new Set(await storage.getItem('NintendoAccountIds') ?? []);
|
||||
users.add(data.user.id);
|
||||
await storage.setItem('NintendoAccountIds', [...users]);
|
||||
|
||||
new Notification({
|
||||
title: 'Nintendo Switch Parental Controls',
|
||||
body: 'Authenticated as ' + data.user.nickname,
|
||||
}).show();
|
||||
|
||||
return {moon, data};
|
||||
return authenticateMoonSessionToken(app, authenticator, code);
|
||||
} finally {
|
||||
window?.close();
|
||||
}
|
||||
}
|
||||
|
||||
export async function askAddPctlAccount(storage: persist.LocalStorage, iab = true) {
|
||||
try {
|
||||
return await addPctlAccount(storage, iab);
|
||||
} catch (err: any) {
|
||||
if (err instanceof AuthoriseError && err.code === 'access_denied') return;
|
||||
async function authenticateMoonSessionToken(
|
||||
app: App,
|
||||
authenticator: NintendoAccountSessionAuthorisation, code: string,
|
||||
reauthenticate = false,
|
||||
) {
|
||||
const token = await authenticator.getSessionToken(code);
|
||||
|
||||
dialog.showErrorBox('Error adding account', err.stack || err.message);
|
||||
debug('session token', token);
|
||||
|
||||
const {moon, data} = await getPctlToken(app.store.storage, token.session_token, false);
|
||||
|
||||
const users = new Set(await app.store.storage.getItem('NintendoAccountIds') ?? []);
|
||||
users.add(data.user.id);
|
||||
await app.store.storage.setItem('NintendoAccountIds', [...users]);
|
||||
|
||||
new Notification({
|
||||
title: app.i18n.t('na_auth:notification_moon.title') ?? 'Nintendo Switch Parental Controls',
|
||||
body: app.i18n.t('na_auth:notification_moon.body_' + (reauthenticate ? 're' : '') + 'authenticated', {
|
||||
na_name: data.user.nickname,
|
||||
na_username: data.user.screenName,
|
||||
}) ?? (reauthenticate ?
|
||||
'Reauthenticated to ' + data.user.nickname + ' (' + data.user.screenName + ')' :
|
||||
'Authenticated as ' + data.user.nickname + ' (' + data.user.screenName + ')'),
|
||||
}).show();
|
||||
|
||||
return {moon, data};
|
||||
}
|
||||
|
||||
export async function askAddPctlAccount(app: App, iab = true) {
|
||||
try {
|
||||
return await addPctlAccount(app, iab);
|
||||
} catch (err: any) {
|
||||
if (err instanceof NintendoAccountSessionAuthorisationError && err.code === 'access_denied') return;
|
||||
|
||||
dialog.showErrorBox(app.i18n.t('na_auth:error.title') ?? 'Error adding account',
|
||||
err.stack || err.message);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
88
src/app/main/support.ts
Normal file
88
src/app/main/support.ts
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
import { Buffer } from 'node:buffer';
|
||||
import { createWriteStream, WriteStream } from 'node:fs';
|
||||
import { app, dialog, Notification, shell } from 'electron';
|
||||
import createDebug from '../../util/debug.js';
|
||||
import { generateEncryptedLogArchive } from '../../util/support.js';
|
||||
import { join } from 'node:path';
|
||||
import { showErrorDialog } from './util.js';
|
||||
|
||||
const debug = createDebug('app:main:support');
|
||||
|
||||
export async function createLogArchive() {
|
||||
let start_notification: Notification | null = null;
|
||||
|
||||
try {
|
||||
const { default: config } = await import('../../common/remote-config.js');
|
||||
|
||||
if (!config.log_encryption_key) {
|
||||
throw new Error('No log encryption key in remote configuration');
|
||||
}
|
||||
|
||||
const default_name = 'nxapi-logs-' +
|
||||
new Date().toISOString().replace(/[-:Z]/g, '').replace(/\.\d+/, '').replace(/T/, '-') +
|
||||
'.tar.gz';
|
||||
|
||||
const result = await dialog.showSaveDialog({
|
||||
defaultPath: join(app.getPath('downloads'), default_name),
|
||||
filters: [{name: 'Tape archive (encrypted)', extensions: ['tgz', 'tar.gz']}],
|
||||
});
|
||||
|
||||
if (result.canceled) return;
|
||||
|
||||
const out = await createOutputStream(result.filePath);
|
||||
|
||||
debug('creating log archive');
|
||||
|
||||
start_notification = new Notification({
|
||||
title: 'Creating log archive',
|
||||
});
|
||||
start_notification.show();
|
||||
|
||||
const key = Buffer.from(config.log_encryption_key, 'base64url');
|
||||
const [encrypt] = await generateEncryptedLogArchive(key);
|
||||
|
||||
encrypt.pipe(out);
|
||||
|
||||
await new Promise((rs, rj) => {
|
||||
encrypt.on('end', rs);
|
||||
encrypt.on('error', rj);
|
||||
});
|
||||
|
||||
debug('done');
|
||||
|
||||
start_notification.close();
|
||||
|
||||
new Notification({
|
||||
title: 'Created log archive',
|
||||
}).show();
|
||||
|
||||
shell.showItemInFolder(result.filePath);
|
||||
} catch (err) {
|
||||
start_notification?.close();
|
||||
|
||||
showErrorDialog({
|
||||
message: 'Error creating log archive',
|
||||
error: err,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function createOutputStream(path: string) {
|
||||
return new Promise<WriteStream>((rs, rj) => {
|
||||
const out = createWriteStream(path);
|
||||
|
||||
const onready = () => {
|
||||
out.removeListener('ready', onready);
|
||||
out.removeListener('error', onerror);
|
||||
rs(out);
|
||||
};
|
||||
const onerror = () => {
|
||||
out.removeListener('ready', onready);
|
||||
out.removeListener('error', onerror);
|
||||
rs(out);
|
||||
};
|
||||
|
||||
out.on('ready', onready);
|
||||
out.on('error', onerror);
|
||||
});
|
||||
}
|
||||
|
|
@ -1,10 +1,15 @@
|
|||
import { BrowserWindow, Menu, MenuItem, nativeImage } from './electron.js';
|
||||
import { BrowserWindow, dialog, Menu, MenuItem, MessageBoxOptions, nativeImage, Session } from 'electron';
|
||||
import path from 'node:path';
|
||||
import { Buffer } from 'node:buffer';
|
||||
import fetch from 'node-fetch';
|
||||
import createDebug from '../../util/debug.js';
|
||||
import { fetch } from 'undici';
|
||||
import { dir } from '../../util/product.js';
|
||||
import { Store } from './index.js';
|
||||
import { App } from './index.js';
|
||||
import { SavedToken } from '../../common/auth/coral.js';
|
||||
import { ErrorDescription } from '../../util/errors.js';
|
||||
import { buildProxyAgent, ProxyAgentOptions } from '../../util/undici-proxy.js';
|
||||
|
||||
const debug = createDebug('app:main:util');
|
||||
|
||||
export const bundlepath = path.resolve(dir, 'dist', 'app', 'bundle');
|
||||
|
||||
|
|
@ -26,10 +31,10 @@ export async function tryGetNativeImageFromUrl(url: URL | string, useragent?: st
|
|||
return undefined;
|
||||
}
|
||||
|
||||
export async function askUserForUri(store: Store, uri: string, prompt: string): Promise<[string, SavedToken] | null> {
|
||||
export async function askUserForUri(app: App, uri: string, prompt: string): Promise<[string, SavedToken] | null> {
|
||||
const menu = new Menu();
|
||||
|
||||
const ids = await store.storage.getItem('NintendoAccountIds') as string[] | undefined;
|
||||
const ids = await app.store.storage.getItem('NintendoAccountIds') as string[] | undefined;
|
||||
menu.append(new MenuItem({label: prompt, enabled: false}));
|
||||
menu.append(new MenuItem({label: uri, enabled: false}));
|
||||
menu.append(new MenuItem({type: 'separator'}));
|
||||
|
|
@ -37,9 +42,9 @@ export async function askUserForUri(store: Store, uri: string, prompt: string):
|
|||
let selected_user: [string, SavedToken] | null = null;
|
||||
|
||||
const items = await Promise.all(ids?.map(async id => {
|
||||
const token = await store.storage.getItem('NintendoAccountToken.' + id) as string | undefined;
|
||||
const token = await app.store.storage.getItem('NintendoAccountToken.' + id) as string | undefined;
|
||||
if (!token) return;
|
||||
const data = await store.storage.getItem('NsoToken.' + token) as SavedToken | undefined;
|
||||
const data = await app.store.storage.getItem('NsoToken.' + token) as SavedToken | undefined;
|
||||
if (!data) return;
|
||||
|
||||
return new MenuItem({
|
||||
|
|
@ -55,7 +60,7 @@ export async function askUserForUri(store: Store, uri: string, prompt: string):
|
|||
|
||||
for (const item of items) if (item) menu.append(item);
|
||||
menu.append(new MenuItem({type: 'separator'}));
|
||||
menu.append(new MenuItem({label: 'Cancel', click: (i, w) => menu.closePopup(w)}));
|
||||
menu.append(new MenuItem({label: app.i18n.t('handle_uri:cancel')!, click: (i, w) => menu.closePopup(w)}));
|
||||
|
||||
const window = new BrowserWindow({show: false});
|
||||
// Add a delay to prevent the menu being closed immediately
|
||||
|
|
@ -65,3 +70,56 @@ export async function askUserForUri(store: Store, uri: string, prompt: string):
|
|||
|
||||
return selected_user;
|
||||
}
|
||||
|
||||
interface ErrorBoxOptions extends MessageBoxOptions {
|
||||
error: Error | unknown;
|
||||
app?: App;
|
||||
window?: BrowserWindow;
|
||||
}
|
||||
|
||||
export function showErrorDialog(options: ErrorBoxOptions) {
|
||||
const {error, app, window, ...message_box_options} = options;
|
||||
const detail = ErrorDescription.getErrorDescription(error);
|
||||
|
||||
message_box_options.detail = message_box_options.detail ?
|
||||
detail + '\n\n' + message_box_options.detail :
|
||||
detail;
|
||||
|
||||
if (!message_box_options.type) message_box_options.type = 'error';
|
||||
|
||||
return window ?
|
||||
dialog.showMessageBox(window, message_box_options) :
|
||||
dialog.showMessageBox(message_box_options);
|
||||
}
|
||||
|
||||
export function buildElectronProxyAgent(options: ProxyAgentOptions & {
|
||||
session: Session;
|
||||
}) {
|
||||
let warned_proxy_unsupported: string | null = null;
|
||||
|
||||
return buildProxyAgent({
|
||||
...options,
|
||||
resolveProxy: async origin => {
|
||||
// https://chromium.googlesource.com/chromium/src/+/HEAD/net/docs/proxy.md
|
||||
const proxies = await options.session.resolveProxy(origin);
|
||||
const proxy = proxies.split(';')[0].trim();
|
||||
|
||||
if (proxy === 'DIRECT') return null;
|
||||
|
||||
if (proxy.startsWith('PROXY ')) {
|
||||
return new URL('http://' + proxy.substr(6));
|
||||
}
|
||||
if (proxy.startsWith('HTTPS ')) {
|
||||
return new URL('https://' + proxy.substr(6));
|
||||
}
|
||||
|
||||
if (warned_proxy_unsupported !== proxy) {
|
||||
warned_proxy_unsupported = proxy;
|
||||
|
||||
debug('Unsupported proxy', proxy);
|
||||
}
|
||||
|
||||
return null;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,27 +1,28 @@
|
|||
import { app, BrowserWindow, clipboard, dialog, IpcMainInvokeEvent, nativeImage, nativeTheme, Notification, ShareMenu, shell, WebContents } from 'electron';
|
||||
import * as path from 'node:path';
|
||||
import { constants } from 'node:fs';
|
||||
import * as fs from 'node:fs/promises';
|
||||
import { Buffer } from 'node:buffer';
|
||||
import * as util from 'node:util';
|
||||
import createDebug from 'debug';
|
||||
import { app, BrowserWindow, clipboard, dialog, IpcMainInvokeEvent, nativeImage, nativeTheme, Notification, ShareMenu, shell, WebContents } from './electron.js';
|
||||
import fetch from 'node-fetch';
|
||||
import CoralApi from '../../api/coral.js';
|
||||
import { CurrentUser, WebService, WebServiceToken } from '../../api/coral-types.js';
|
||||
import { Store } from './index.js';
|
||||
import type { DownloadImagesRequest, NativeShareRequest, NativeShareUrlRequest, QrCodeReaderCameraOptions, QrCodeReaderCheckinOptions, QrCodeReaderCheckinResult, QrCodeReaderPhotoLibraryOptions, SendMessageOptions } from '../preload-webservice/znca-js-api.js';
|
||||
import { SavedToken } from '../../common/auth/coral.js';
|
||||
import { fetch } from 'undici';
|
||||
import mimetypes from 'mime-types';
|
||||
import { App, Store } from './index.js';
|
||||
import { createWebServiceWindow } from './windows.js';
|
||||
import { askUserForUri } from './util.js';
|
||||
import { NintendoAccountUser } from '../../api/na.js';
|
||||
import { askUserForUri, showErrorDialog } from './util.js';
|
||||
import type { DownloadImagesRequest, NativeShareRequest, NativeShareUrlRequest, QrCodeReaderCameraOptions, QrCodeReaderCheckinOptions, QrCodeReaderCheckinResult, QrCodeReaderPhotoLibraryOptions, SendMessageOptions } from '../preload-webservice/znca-js-api.js';
|
||||
import createDebug from '../../util/debug.js';
|
||||
import { CoralApiInterface, CoralAuthData } from '../../api/coral.js';
|
||||
import { WebService, WebServiceToken } from '../../api/coral-types.js';
|
||||
import { SavedToken } from '../../common/auth/coral.js';
|
||||
import { checkMembershipActive } from '../../common/auth/util.js';
|
||||
|
||||
const debug = createDebug('app:main:webservices');
|
||||
|
||||
const windows = new Map<string, BrowserWindow>();
|
||||
const windowapi = new WeakMap<WebContents, [Store, string, CoralApi, SavedToken, WebService]>();
|
||||
const windowapi = new WeakMap<WebContents, [Store, string, CoralApiInterface, SavedToken, WebService]>();
|
||||
|
||||
export default async function openWebService(
|
||||
store: Store, token: string, nso: CoralApi, data: SavedToken,
|
||||
store: Store, token: string, coral: CoralApiInterface, data: SavedToken,
|
||||
webservice: WebService, qs?: string
|
||||
) {
|
||||
const windowid = data.nsoAccount.user.nsaId + ':' + webservice.id;
|
||||
|
|
@ -41,12 +42,7 @@ export default async function openWebService(
|
|||
}
|
||||
|
||||
const verifymembership = webservice.customAttributes.find(a => a.attrKey === 'verifyMembership');
|
||||
|
||||
if (verifymembership?.attrValue === 'true') {
|
||||
const membership = data.nsoAccount.user.links.nintendoAccount.membership;
|
||||
const active = typeof membership.active === 'object' ? membership.active.active : membership.active;
|
||||
if (!active) throw new WebServiceValidationError('Nintendo Switch Online membership required');
|
||||
}
|
||||
if (verifymembership?.attrValue === 'true') checkMembershipActive(data);
|
||||
|
||||
const user_title_prefix = '[' + data.user.nickname +
|
||||
(data.nsoAccount.user.name !== data.user.nickname ? '/' + data.nsoAccount.user.name : '') + '] ';
|
||||
|
|
@ -54,7 +50,7 @@ export default async function openWebService(
|
|||
const window = createWebServiceWindow(data.nsoAccount.user.nsaId, webservice, user_title_prefix);
|
||||
|
||||
windows.set(windowid, window);
|
||||
windowapi.set(window.webContents, [store, token, nso, data, webservice]);
|
||||
windowapi.set(window.webContents, [store, token, coral, data, webservice]);
|
||||
|
||||
window.on('closed', () => {
|
||||
windows.delete(windowid);
|
||||
|
|
@ -68,6 +64,8 @@ export default async function openWebService(
|
|||
|
||||
if (!isWebServiceUrlAllowed(webservice, url)) {
|
||||
debug('Web service attempted to navigate to a URL not allowed by it\'s `whiteList`', webservice, url);
|
||||
debug('open', url);
|
||||
shell.openExternal(url);
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
|
|
@ -83,7 +81,7 @@ export default async function openWebService(
|
|||
return {action: 'deny'};
|
||||
});
|
||||
|
||||
const webserviceToken = await getWebServiceToken(nso, webservice, data.user, data.nsoAccount.user, window);
|
||||
const webserviceToken = await getWebServiceToken(coral, webservice, qs, data, window);
|
||||
|
||||
const url = new URL(webservice.uri);
|
||||
url.search = new URLSearchParams({
|
||||
|
|
@ -107,6 +105,7 @@ export default async function openWebService(
|
|||
|
||||
window.loadURL(url.toString(), {
|
||||
extraHeaders: Object.entries({
|
||||
'x-appplatform': 'android',
|
||||
'x-appcolorscheme': nativeTheme.shouldUseDarkColors ? 'DARK' : 'LIGHT',
|
||||
'x-gamewebtoken': webserviceToken.accessToken,
|
||||
'dnt': '1',
|
||||
|
|
@ -118,31 +117,19 @@ export default async function openWebService(
|
|||
export class WebServiceValidationError extends Error {}
|
||||
|
||||
async function getWebServiceToken(
|
||||
nso: CoralApi, webservice: WebService,
|
||||
user: NintendoAccountUser, nsoAccount: CurrentUser,
|
||||
window: BrowserWindow
|
||||
coral: CoralApiInterface,
|
||||
webservice: WebService, qs: string | undefined,
|
||||
auth_data: CoralAuthData,
|
||||
window: BrowserWindow,
|
||||
): Promise<WebServiceToken> {
|
||||
try {
|
||||
return await nso.getWebServiceToken(webservice.id);
|
||||
return await coral.getWebServiceToken(webservice.id);
|
||||
} catch (err) {
|
||||
const result = await dialog.showMessageBox(window, {
|
||||
type: 'error',
|
||||
message: (err instanceof Error ? err.name : 'Error') + ' requesting web service token',
|
||||
detail: (err instanceof Error ? err.stack ?? err.message : err) + '\n\n' + util.inspect({
|
||||
webservice: {
|
||||
id: webservice.id,
|
||||
name: webservice.name,
|
||||
uri: webservice.uri,
|
||||
},
|
||||
user_na_id: user.id,
|
||||
user_nsa_id: nsoAccount.nsaId,
|
||||
user_coral_id: nsoAccount.id,
|
||||
}, {compact: true}),
|
||||
buttons: ['Retry', 'Close ' + webservice.name, 'Ignore'],
|
||||
});
|
||||
const result = await handleOpenWebServiceError(err, webservice, qs, auth_data, window,
|
||||
['Retry', 'Close ' + webservice.name, 'Ignore']);
|
||||
|
||||
if (result.response === 0) {
|
||||
return getWebServiceToken(nso, webservice, user, nsoAccount, window);
|
||||
return getWebServiceToken(coral, webservice, qs, auth_data, window);
|
||||
}
|
||||
if (result.response === 1) {
|
||||
window.close();
|
||||
|
|
@ -158,41 +145,75 @@ function isWebServiceUrlAllowed(webservice: WebService, url: string | URL) {
|
|||
|
||||
if (typeof url === 'string') url = new URL(url);
|
||||
|
||||
for (const host of webservice.whiteList) {
|
||||
for (const allowed of webservice.whiteList) {
|
||||
const host = allowed.includes('/') ? allowed.substr(0, allowed.indexOf('/')) : allowed;
|
||||
const path = allowed.includes('/') ? allowed.substr(allowed.indexOf('/')) : null;
|
||||
|
||||
if (path && url.pathname !== path && !url.pathname.startsWith(path + '/')) continue;
|
||||
|
||||
if (host.startsWith('*.')) {
|
||||
return url.hostname === host.substr(2) ||
|
||||
url.hostname.endsWith(host.substr(1));
|
||||
if (url.hostname === host.substr(2) ||
|
||||
url.hostname.endsWith(host.substr(1))
|
||||
) return true;
|
||||
}
|
||||
|
||||
return url.hostname === host;
|
||||
if (url.hostname === host) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function handleOpenWebServiceUri(store: Store, uri: string) {
|
||||
export async function handleOpenWebServiceUri(app: App, uri: string) {
|
||||
const match = uri.match(/^com\.nintendo\.znca:\/\/(znca\/)game\/(\d+)\/?($|\?|\#)/i);
|
||||
if (!match) return;
|
||||
|
||||
const webservice_id = parseInt(match[2]);
|
||||
|
||||
const selected_user = await askUserForWebServiceUri(store, uri);
|
||||
const selected_user = await askUserForWebServiceUri(app, uri);
|
||||
if (!selected_user) return;
|
||||
|
||||
const {nso, data, webservices} = await store.users.get(selected_user[0]);
|
||||
const {nso, data, webservices} = await app.store.users.get(selected_user[0]);
|
||||
|
||||
const webservice = webservices.result.find(w => w.id === webservice_id);
|
||||
if (!webservice) {
|
||||
dialog.showErrorBox('Invalid web service', 'The URL did not reference an existing web service.\n\n' +
|
||||
dialog.showErrorBox(app.i18n.t('handle_uri:web_service_invalid_title'),
|
||||
app.i18n.t('handle_uri:web_service_invalid_detail') +
|
||||
'\n\n' +
|
||||
uri);
|
||||
return;
|
||||
}
|
||||
|
||||
return openWebService(store, selected_user[0], nso, data, webservice, new URL(uri).search.substr(1));
|
||||
return openWebService(app.store, selected_user[0], nso, data, webservice, new URL(uri).search.substr(1));
|
||||
}
|
||||
|
||||
function askUserForWebServiceUri(store: Store, uri: string) {
|
||||
return askUserForUri(store, uri, 'Select a user to open this web service');
|
||||
function askUserForWebServiceUri(app: App, uri: string) {
|
||||
return askUserForUri(app, uri, app.i18n.t('handle_uri:web_service_select'));
|
||||
}
|
||||
|
||||
export async function handleOpenWebServiceError(
|
||||
err: unknown,
|
||||
webservice: WebService, qs?: string, auth_data?: CoralAuthData,
|
||||
window?: BrowserWindow, buttons?: string[],
|
||||
) {
|
||||
const data = {
|
||||
webservice: {
|
||||
id: webservice.id,
|
||||
name: webservice.name,
|
||||
uri: webservice.uri,
|
||||
},
|
||||
qs,
|
||||
user_na_id: auth_data?.user.id,
|
||||
user_nsa_id: auth_data?.nsoAccount.user.nsaId,
|
||||
user_coral_id: auth_data?.nsoAccount.user.id,
|
||||
};
|
||||
|
||||
return showErrorDialog({
|
||||
message: (err instanceof Error ? err.name : 'Error') + ' opening web service',
|
||||
error: err,
|
||||
detail: util.inspect(data, {compact: true}),
|
||||
buttons,
|
||||
window,
|
||||
});
|
||||
}
|
||||
|
||||
export interface WebServiceData {
|
||||
|
|
@ -221,6 +242,7 @@ export class WebServiceIpc {
|
|||
store: data[0],
|
||||
token: data[1],
|
||||
nso: data[2],
|
||||
data: data[3],
|
||||
nintendoAccountToken: data[3].nintendoAccountToken,
|
||||
user: data[3].user,
|
||||
nsoAccount: data[3].nsoAccount,
|
||||
|
|
@ -269,16 +291,8 @@ export class WebServiceIpc {
|
|||
const dir = app.getPath('downloads');
|
||||
const basename = path.basename(new URL(image_url).pathname);
|
||||
const extname = path.extname(basename);
|
||||
let filename;
|
||||
let i = 0;
|
||||
|
||||
do {
|
||||
i++;
|
||||
|
||||
filename = i === 1 ? basename : basename.substr(0, basename.length - extname.length) + ' ' + i + extname;
|
||||
} while (await this.pathExists(path.join(dir, filename)));
|
||||
|
||||
debug('Downloading image %s to %s as %s', image_url, dir, filename);
|
||||
debug('Downloading image %s to %s', image_url, dir);
|
||||
|
||||
const response = await fetch(image_url, {
|
||||
headers: {
|
||||
|
|
@ -286,6 +300,22 @@ export class WebServiceIpc {
|
|||
},
|
||||
});
|
||||
const image = await response.arrayBuffer();
|
||||
|
||||
const type = response.headers.get('Content-Type');
|
||||
const ext = type ? mimetypes.extension(type) : null;
|
||||
|
||||
let filename;
|
||||
let i = 0;
|
||||
|
||||
do {
|
||||
i++;
|
||||
|
||||
filename = basename.substr(0, basename.length - extname.length) +
|
||||
(i === 1 ? basename : ' ' + i) +
|
||||
(ext ? '.' + ext : extname);
|
||||
} while (await this.pathExists(path.join(dir, filename)));
|
||||
|
||||
debug('Writing image %s to %s as %s', image_url, dir, filename);
|
||||
await fs.writeFile(path.join(dir, filename), Buffer.from(image));
|
||||
|
||||
return path.join(dir, filename);
|
||||
|
|
@ -317,12 +347,12 @@ export class WebServiceIpc {
|
|||
}
|
||||
|
||||
async requestGameWebToken(event: IpcMainInvokeEvent): Promise<string> {
|
||||
const {nso, user, nsoAccount, webservice} = this.getWindowData(event.sender);
|
||||
const {nso, data, nsoAccount, webservice} = this.getWindowData(event.sender);
|
||||
const window = BrowserWindow.fromWebContents(event.sender)!;
|
||||
|
||||
debug('Web service %s, user %s, called requestGameWebToken', webservice.name, nsoAccount.user.name);
|
||||
|
||||
const webserviceToken = await getWebServiceToken(nso, webservice, user, nsoAccount.user, window);
|
||||
const webserviceToken = await getWebServiceToken(nso, webservice, undefined, data, window);
|
||||
|
||||
return webserviceToken.accessToken;
|
||||
}
|
||||
|
|
@ -429,4 +459,10 @@ export class WebServiceIpc {
|
|||
|
||||
debug('Web service %s, user %s, called completeLoading', webservice.name, nsoAccount.user.name);
|
||||
}
|
||||
|
||||
async clearUnreadFlag(event: IpcMainInvokeEvent): Promise<void> {
|
||||
const {nsoAccount, webservice} = this.getWindowData(event.sender);
|
||||
|
||||
debug('Web service %s, user %s, called clearUnreadFlag', webservice.name, nsoAccount.user.name);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,26 +1,16 @@
|
|||
import { app, BrowserWindow, BrowserWindowConstructorOptions, Menu, nativeTheme, session, WebContents } from './electron.js';
|
||||
import { BrowserWindow, BrowserWindowConstructorOptions, nativeTheme, session, WebContents } from 'electron';
|
||||
import * as path from 'node:path';
|
||||
import { dev } from '../../util/product.js';
|
||||
import { WindowConfiguration, WindowType } from '../common/types.js';
|
||||
import { bundlepath } from './util.js';
|
||||
import { app_menu, createWindowMenu } from './app-menu.js';
|
||||
import { createWindowMenu, setWindowMenu } from './app-menu.js';
|
||||
import { WebService } from '../../api/coral-types.js';
|
||||
|
||||
const windows = new WeakMap<WebContents, WindowConfiguration>();
|
||||
const menus = new WeakMap<BrowserWindow, Menu>();
|
||||
|
||||
app.on('browser-window-focus', (event, window) => {
|
||||
Menu.setApplicationMenu(menus.get(window) ?? app_menu);
|
||||
});
|
||||
app.on('browser-window-blur', (event, window) => {
|
||||
if (!BrowserWindow.getFocusedWindow()) {
|
||||
Menu.setApplicationMenu(app_menu);
|
||||
}
|
||||
});
|
||||
|
||||
export function createWindow<T extends WindowType>(
|
||||
type: T, props: WindowConfiguration<T>['props'],
|
||||
options?: BrowserWindowConstructorOptions
|
||||
options?: BrowserWindowConstructorOptions,
|
||||
) {
|
||||
// Create the browser window
|
||||
const window = new BrowserWindow({
|
||||
|
|
@ -43,7 +33,7 @@ export function createWindow<T extends WindowType>(
|
|||
};
|
||||
|
||||
windows.set(window.webContents, data);
|
||||
menus.set(window, createWindowMenu(window));
|
||||
setWindowMenu(window, createWindowMenu(window));
|
||||
|
||||
window.loadFile(path.join(bundlepath, 'index.html'));
|
||||
if (dev) window.webContents.openDevTools();
|
||||
|
|
@ -61,6 +51,62 @@ export function getWindowConfiguration(webcontents: WebContents): WindowConfigur
|
|||
return data;
|
||||
}
|
||||
|
||||
const modal_window_width = new WeakMap<BrowserWindow, number>();
|
||||
const modal_window_shown = new WeakSet<BrowserWindow>();
|
||||
|
||||
export function createModalWindow<T extends WindowType>(
|
||||
type: T, props: WindowConfiguration<T>['props'],
|
||||
parent?: BrowserWindow | WebContents,
|
||||
options?: BrowserWindowConstructorOptions,
|
||||
) {
|
||||
if (parent && !(parent instanceof BrowserWindow)) {
|
||||
parent = BrowserWindow.fromWebContents(parent) ?? undefined;
|
||||
}
|
||||
|
||||
const window = createWindow(type, props, {
|
||||
parent,
|
||||
modal: !!parent,
|
||||
show: false,
|
||||
maximizable: false,
|
||||
minimizable: false,
|
||||
width: 560,
|
||||
height: 300,
|
||||
minWidth: 450,
|
||||
maxWidth: 700,
|
||||
minHeight: 300,
|
||||
maxHeight: 300,
|
||||
|
||||
...options,
|
||||
});
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
// Use a fixed window width on Windows due to a bug getting/setting window size
|
||||
window.setResizable(false);
|
||||
modal_window_width.set(window, options?.width ?? 560);
|
||||
}
|
||||
|
||||
return window;
|
||||
}
|
||||
|
||||
export function setWindowHeight(window: BrowserWindow, height: number) {
|
||||
const [curWidth, curHeight] = window.getSize();
|
||||
const [curContentWidth, curContentHeight] = window.getContentSize();
|
||||
const [minWidth, minHeight] = window.getMinimumSize();
|
||||
const [maxWidth, maxHeight] = window.getMaximumSize();
|
||||
|
||||
if (height !== curContentHeight && curHeight === minHeight && curHeight === maxHeight) {
|
||||
window.setMinimumSize(minWidth, height + (curHeight - curContentHeight));
|
||||
window.setMaximumSize(maxWidth, height + (curHeight - curContentHeight));
|
||||
}
|
||||
|
||||
window.setContentSize(modal_window_width.get(window) ?? curContentWidth, height);
|
||||
|
||||
if (!modal_window_shown.has(window)) {
|
||||
window.show();
|
||||
modal_window_shown.add(window);
|
||||
}
|
||||
}
|
||||
|
||||
const BACKGROUND_COLOUR_MAIN_LIGHT = process.platform === 'win32' ? '#ffffff' : '#ececec';
|
||||
const BACKGROUND_COLOUR_MAIN_DARK = process.platform === 'win32' ? '#000000' : '#252424';
|
||||
|
||||
|
|
@ -84,7 +130,7 @@ export function createWebServiceWindow(nsa_id: string, webservice: WebService, t
|
|||
},
|
||||
});
|
||||
|
||||
menus.set(window, createWindowMenu(window));
|
||||
setWindowMenu(window, createWindowMenu(window));
|
||||
|
||||
window.loadURL('about:blank');
|
||||
if (dev) window.webContents.openDevTools();
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { ipcRenderer, IpcRendererEvent } from 'electron';
|
||||
import { EventEmitter } from 'events';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import createDebug from 'debug';
|
||||
import { QrCodeReaderOptions, WebServiceData } from '../main/webservices.js';
|
||||
|
||||
|
|
@ -20,6 +20,7 @@ const ipc = {
|
|||
copyToClipboard: (data: string) => ipcRenderer.invoke('nxapi:webserviceapi:copyToClipboard', data) as Promise<void>,
|
||||
downloadImages: (data: string) => ipcRenderer.invoke('nxapi:webserviceapi:downloadImages', data) as Promise<void>,
|
||||
completeLoading: () => ipcRenderer.invoke('nxapi:webserviceapi:completeLoading') as Promise<void>,
|
||||
clearUnreadFlag: () => ipcRenderer.invoke('nxapi:webserviceapi:clearUnreadFlag') as Promise<void>,
|
||||
};
|
||||
|
||||
export default ipc;
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ const debug = createDebug('app:preload-webservice:quirks:splatnet3');
|
|||
|
||||
const SPLATNET3_WEBSERVICE_ID = 4834290508791808;
|
||||
|
||||
if (webservice.id === SPLATNET3_WEBSERVICE_ID) {
|
||||
if (webservice.id === SPLATNET3_WEBSERVICE_ID && location.hostname.endsWith('.av5ja.srv.nintendo.net')) {
|
||||
const style = window.document.createElement('style');
|
||||
|
||||
style.textContent = `
|
||||
|
|
@ -57,3 +57,17 @@ if (webservice.id === SPLATNET3_WEBSERVICE_ID) {
|
|||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (webservice.id === SPLATNET3_WEBSERVICE_ID && location.hostname === 'c.nintendo.com' && location.pathname.match(/^\/splatoon3-tournament(\/|$)/i)) {
|
||||
const style = window.document.createElement('style');
|
||||
|
||||
style.textContent = `
|
||||
[class*=AppHeader_closeWebView] {
|
||||
display: none;
|
||||
}
|
||||
`;
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
window.document.head.appendChild(style);
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -142,6 +142,31 @@ interface WebServiceJsApi {
|
|||
* Used by SplatNet 3.
|
||||
*/
|
||||
reloadExtension(): void;
|
||||
|
||||
/**
|
||||
* Clears the unread notifications flag.
|
||||
*/
|
||||
clearUnreadFlag(): void;
|
||||
|
||||
/**
|
||||
* Opens a URL in the default browser.
|
||||
*/
|
||||
openExternalBrowser(url: string): void;
|
||||
|
||||
/**
|
||||
* Plays a preset vibration pattern.
|
||||
*
|
||||
* Used by ZELDA NOTES.
|
||||
*/
|
||||
func_2644(data: string): void;
|
||||
|
||||
/**
|
||||
* Requests a web service token from the Coral API.
|
||||
* `window.znca._private.func_1d5e` is called with the returned token.
|
||||
*
|
||||
* Used by ZELDA NOTES.
|
||||
*/
|
||||
func_272e(): void;
|
||||
}
|
||||
|
||||
//
|
||||
|
|
@ -185,6 +210,17 @@ function requestGameWebToken() {
|
|||
});
|
||||
}
|
||||
|
||||
function func_272e() {
|
||||
debug('func_272e called');
|
||||
|
||||
ipc.requestGameWebToken().then(token => {
|
||||
// @ts-expect-error
|
||||
window.znca?._private?.func_1d5e?.call(null, token);
|
||||
}).catch(async err => {
|
||||
debug('Error requesting web service token', err);
|
||||
});
|
||||
}
|
||||
|
||||
//
|
||||
// Persistent data
|
||||
//
|
||||
|
|
@ -339,6 +375,31 @@ function reloadExtension() {
|
|||
debug('reloadExtension called');
|
||||
}
|
||||
|
||||
function clearUnreadFlag() {
|
||||
debug('clearUnreadFlag called');
|
||||
ipc.clearUnreadFlag();
|
||||
}
|
||||
|
||||
function openExternalBrowser(url: string) {
|
||||
debug('openExternalBrowser called', url);
|
||||
window.open(url);
|
||||
}
|
||||
|
||||
export interface VibrateOptions {
|
||||
pattern: VibratePattern;
|
||||
}
|
||||
export enum VibratePattern {
|
||||
TAP = '0',
|
||||
SUCCESS = '1',
|
||||
ERROR = '2',
|
||||
}
|
||||
|
||||
function func_2644(/** JSON.stringify(data: VibrateOptions) */ data: string) {
|
||||
const options: VibrateOptions = JSON.parse(data);
|
||||
|
||||
debug('func_2644 called', options);
|
||||
}
|
||||
|
||||
const api: WebServiceJsApi = {
|
||||
invokeNativeShare,
|
||||
invokeNativeShareUrl,
|
||||
|
|
@ -356,6 +417,10 @@ const api: WebServiceJsApi = {
|
|||
completeLoading,
|
||||
closeWebView,
|
||||
reloadExtension,
|
||||
clearUnreadFlag,
|
||||
openExternalBrowser,
|
||||
func_2644,
|
||||
func_272e,
|
||||
};
|
||||
|
||||
window.jsBridge = api;
|
||||
|
|
|
|||
|
|
@ -1,26 +1,43 @@
|
|||
import { contextBridge, ipcRenderer } from 'electron';
|
||||
import { EventEmitter } from 'events';
|
||||
import { contextBridge, ipcRenderer, SharingItem } from 'electron';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import createDebug from 'debug';
|
||||
import type { User } from 'discord-rpc';
|
||||
import type { SharingItem } from '../main/electron.js';
|
||||
import type { DiscordPresenceConfiguration, DiscordPresenceSource, LoginItem, LoginItemOptions, WindowConfiguration } from '../common/types.js';
|
||||
import type { DiscordPresenceConfiguration, DiscordPresenceSource, DiscordStatus, LoginItem, LoginItemOptions, WindowConfiguration } from '../common/types.js';
|
||||
import type { SavedToken } from '../../common/auth/coral.js';
|
||||
import type { SavedMoonToken } from '../../common/auth/moon.js';
|
||||
import type { UpdateCacheData } from '../../common/update.js';
|
||||
import type { Announcements, CoralSuccessResponse, CurrentUser, Friend, FriendCodeUrl, FriendCodeUser, GetActiveEventResult, WebService, WebServices } from '../../api/coral-types.js';
|
||||
import type { StatusUpdate } from '../../common/status.js';
|
||||
import type { Announcements_4, CoralSuccessResponse, CurrentUser, CurrentUserFriendCodeLink, Friend, Friend_4, FriendCodeUrl, FriendCodeUser, GetActiveEventResult, ReceivedFriendRequests, SentFriendRequests, WebService, WebServices_4 } from '../../api/coral-types.js';
|
||||
import type { DiscordPresence } from '../../discord/types.js';
|
||||
import type { NintendoAccountUser } from '../../api/na.js';
|
||||
import type { CachedErrorKey } from '../main/ipc.js';
|
||||
import type { DiscordSetupProps } from '../browser/discord/index.js';
|
||||
import type { FriendProps } from '../browser/friend/index.js';
|
||||
import type { AddFriendProps } from '../browser/add-friend/index.js';
|
||||
import { NintendoAccountUserCoral } from '../../api/coral.js';
|
||||
import { NintendoAccountUserMoon } from '../../api/moon.js';
|
||||
|
||||
// In sandboxed renderers the process object contains a very limited set of APIs
|
||||
// https://www.electronjs.org/docs/latest/api/process#sandbox
|
||||
|
||||
const debug = createDebug('app:preload');
|
||||
|
||||
const inv = <T = void>(channel: string, ...args: any[]) =>
|
||||
ipcRenderer.invoke('nxapi:' + channel, ...args) as Promise<T>;
|
||||
const inv = async <T = void>(channel: string, ...args: any[]) => {
|
||||
const data: {
|
||||
result: T;
|
||||
} | {
|
||||
error_type: string;
|
||||
message: string;
|
||||
type?: string;
|
||||
description: string;
|
||||
data: unknown;
|
||||
} = await ipcRenderer.invoke('nxapi:' + channel, ...args);
|
||||
|
||||
if ('result' in data) return data.result;
|
||||
|
||||
// Context isolation removes all other properties of Error objects
|
||||
throw new Error(data.description.replace(/^Error\: /, ''));
|
||||
};
|
||||
|
||||
const invSync = <T = void>(channel: string, ...args: any[]) =>
|
||||
ipcRenderer.sendSync('nxapi:' + channel, ...args) as T;
|
||||
|
||||
|
|
@ -33,8 +50,13 @@ const ipc = {
|
|||
getLoginItemSettings: () => inv<LoginItem>('systemPreferences:getloginitem'),
|
||||
setLoginItemSettings: (settings: LoginItemOptions) => inv('systemPreferences:setloginitem', settings),
|
||||
|
||||
getShowErrorAlerts: () => inv<boolean>('preferences:getshowerroralerts'),
|
||||
setShowErrorAlerts: (show: boolean) => inv('preferences:setshowerroralerts', show),
|
||||
|
||||
getUpdateData: () => inv<UpdateCacheData | null>('update:get'),
|
||||
checkUpdates: () => inv<UpdateCacheData | null>('update:check'),
|
||||
getStatusUpdateData: () => inv<StatusUpdate[] | null>('statusupdates:get'),
|
||||
forceUpdateStatusUpdates: () => inv<StatusUpdate[] | null>('statusupdates:refresh'),
|
||||
|
||||
listNintendoAccounts: () => inv<string[] | undefined>('accounts:list'),
|
||||
addCoralAccount: () => inv<string>('accounts:add-coral'),
|
||||
|
|
@ -42,15 +64,19 @@ const ipc = {
|
|||
|
||||
getNintendoAccountCoralToken: (id: string) => inv<string | undefined>('coral:gettoken', id),
|
||||
getSavedCoralToken: (token: string) => inv<SavedToken | undefined>('coral:getcachedtoken', token),
|
||||
getCoralAnnouncements: (token: string) => inv<Announcements>('coral:announcements', token),
|
||||
getNsoFriends: (token: string) => inv<Friend[]>('coral:friends', token),
|
||||
getWebServices: (token: string) => inv<WebServices | undefined>('coral:webservices', token),
|
||||
getCoralAnnouncements: (token: string) => inv<Announcements_4>('coral:announcements', token),
|
||||
getNsoFriends: (token: string) => inv<Friend_4[]>('coral:friends', token),
|
||||
getWebServices: (token: string) => inv<WebServices_4 | undefined>('coral:webservices', token),
|
||||
openWebService: (webservice: WebService, token: string, qs?: string) => inv<number>('coral:openwebservice', webservice, token, qs),
|
||||
getCoralActiveEvent: (token: string) => inv<GetActiveEventResult>('coral:activeevent', token),
|
||||
getNsoFriendCodeUrl: (token: string) => inv<FriendCodeUrl>('coral:friendcodeurl', token),
|
||||
getNsoReceivedFriendRequests: (token: string) => inv<ReceivedFriendRequests>('coral:friendrequests:received', token),
|
||||
getNsoSentFriendRequests: (token: string) => inv<SentFriendRequests>('coral:friendrequests:sent', token),
|
||||
getNsoUserByFriendCode: (token: string, friendcode: string, hash?: string) => inv<FriendCodeUser>('coral:friendcode', token, friendcode, hash),
|
||||
addNsoFriend: (token: string, nsa_id: string) => inv<{result: CoralSuccessResponse<{}>; friend: Friend | null}>('coral:addfriend', token, nsa_id),
|
||||
|
||||
showCoralErrors: (token: string, keys: CachedErrorKey | CachedErrorKey[]) => inv('coral:showlasterrors', token, keys),
|
||||
|
||||
getDiscordPresenceConfig: () => inv<DiscordPresenceConfiguration | null>('discord:config'),
|
||||
setDiscordPresenceConfig: (config: DiscordPresenceConfiguration | null) => inv<void>('discord:setconfig', config),
|
||||
getDiscordPresenceOptions: () => inv<Omit<DiscordPresenceConfiguration, 'source'> | null>('discord:options'),
|
||||
|
|
@ -59,6 +85,8 @@ const ipc = {
|
|||
getDiscordPresenceSource: () => inv<DiscordPresenceSource | null>('discord:source'),
|
||||
setDiscordPresenceSource: (source: DiscordPresenceSource | null) => inv<void>('discord:setsource', source),
|
||||
getDiscordPresence: () => inv<DiscordPresence | null>('discord:presence'),
|
||||
getDiscordStatus: () => inv<DiscordStatus | null>('discord:status'),
|
||||
showDiscordLastUpdateError: () => inv('discord:showerror'),
|
||||
getDiscordUser: () => inv<User | null>('discord:user'),
|
||||
getDiscordUsers: () => inv<User[]>('discord:users'),
|
||||
|
||||
|
|
@ -74,15 +102,17 @@ const ipc = {
|
|||
openExternalUrl: (url: string) => inv('misc:open-url', url),
|
||||
share: (item: SharingItem) => inv('misc:share', item),
|
||||
|
||||
showUserMenu: (user: NintendoAccountUser, nso?: CurrentUser, moon?: boolean) => inv('menu:user', user, nso, moon),
|
||||
showUserMenu: (user: NintendoAccountUserCoral | NintendoAccountUserMoon, nso?: CurrentUser<true> | CurrentUser<false>, moon?: boolean) => inv('menu:user', user, nso, moon),
|
||||
showAddUserMenu: () => inv('menu:add-user'),
|
||||
showFriendCodeMenu: (fc: CurrentUser['links']['friendCode']) => inv('menu:friend-code', fc),
|
||||
showFriendMenu: (user: NintendoAccountUser, nso: CurrentUser, friend: Friend) => inv('menu:friend', user, nso, friend),
|
||||
showFriendCodeMenu: (fc: CurrentUserFriendCodeLink) => inv('menu:friend-code', fc),
|
||||
showFriendMenu: (user: NintendoAccountUserCoral, nso: CurrentUser<true> | CurrentUser<false>, friend: Friend_4) => inv('menu:friend', user, nso, friend),
|
||||
|
||||
registerEventListener: (event: string, listener: (args: any[]) => void) => events.on(event, listener),
|
||||
removeEventListener: (event: string, listener: (args: any[]) => void) => events.removeListener(event, listener),
|
||||
|
||||
getLanguage: () => language,
|
||||
getAccentColour: () => accent_colour,
|
||||
getWindowFocused: () => focused,
|
||||
|
||||
platform: process.platform,
|
||||
};
|
||||
|
|
@ -90,15 +120,27 @@ const ipc = {
|
|||
export type NxapiElectronIpc = typeof ipc;
|
||||
|
||||
ipcRenderer.on('nxapi:window:refresh', () => events.emit('window:refresh') || location.reload());
|
||||
ipcRenderer.on('nxapi:statusupdates', (e, s: StatusUpdate[]) => events.emit('status-updates', s));
|
||||
ipcRenderer.on('nxapi:accounts:shouldrefresh', () => events.emit('update-nintendo-accounts'));
|
||||
ipcRenderer.on('nxapi:discord:shouldrefresh', () => events.emit('update-discord-presence-source'));
|
||||
ipcRenderer.on('nxapi:discord:presence', (e, p: DiscordPresence) => events.emit('update-discord-presence', p));
|
||||
ipcRenderer.on('nxapi:discord:user', (e, u: User) => events.emit('update-discord-user', u));
|
||||
ipcRenderer.on('nxapi:discord:status', (e, s: DiscordStatus | null) => events.emit('update-discord-status', s));
|
||||
|
||||
let language: string | undefined = invSync('app:language');
|
||||
ipcRenderer.on('nxapi:app:update-language', (event, l: string) => {
|
||||
language = l;
|
||||
events.emit('update-language', l);
|
||||
});
|
||||
|
||||
let accent_colour: string | undefined = invSync('systemPreferences:accent-colour');
|
||||
ipcRenderer.on('nxapi:systemPreferences:accent-colour', (event, c) => {
|
||||
ipcRenderer.on('nxapi:systemPreferences:accent-colour', (event, c: string) => {
|
||||
accent_colour = c;
|
||||
events.emit('systemPreferences:accent-colour', c);
|
||||
});
|
||||
|
||||
let focused: boolean = invSync('window:focused');
|
||||
window.addEventListener('focus', () => (focused = true, events.emit('window:focused', focused)));
|
||||
window.addEventListener('blur', () => (focused = false, events.emit('window:focused', focused)));
|
||||
|
||||
contextBridge.exposeInMainWorld('nxapiElectronIpc', ipc);
|
||||
|
|
|
|||
|
|
@ -1,9 +1,13 @@
|
|||
import createDebug from 'debug';
|
||||
import { join } from 'node:path';
|
||||
import { init as initDebug } from './util/debug.js';
|
||||
import { paths } from './util/product.js';
|
||||
|
||||
//
|
||||
// cli entrypoint for Rollup bundle
|
||||
// cli entrypoint
|
||||
//
|
||||
|
||||
createDebug.log = console.warn.bind(console);
|
||||
if (process.env.NXAPI_DEBUG_FILE !== '0') {
|
||||
await initDebug(join(paths.log, 'cli'));
|
||||
}
|
||||
|
||||
import('./cli.js').then(cli => cli.main.call(null));
|
||||
|
|
|
|||
18
src/cli.ts
18
src/cli.ts
|
|
@ -1,19 +1,25 @@
|
|||
import process from 'node:process';
|
||||
import createDebug from 'debug';
|
||||
import Yargs from 'yargs';
|
||||
import * as commands from './cli/index.js';
|
||||
import { setGlobalDispatcher } from 'undici';
|
||||
import * as commands from './cli/commands.js';
|
||||
import { checkUpdates } from './common/update.js';
|
||||
import { dev } from './util/product.js';
|
||||
import createDebug from './util/debug.js';
|
||||
import { dev, product } from './util/product.js';
|
||||
import { paths } from './util/storage.js';
|
||||
import { YargsArguments } from './util/yargs.js';
|
||||
import { addUserAgent } from './util/useragent.js';
|
||||
import { USER_AGENT_INFO_URL } from './common/constants.js';
|
||||
import { init as initGlobals } from './common/globals.js';
|
||||
import { buildEnvironmentProxyAgent } from './util/undici-proxy.js';
|
||||
import { ClientAssertionProvider, NXAPI_AUTH_CLI_CLIENT_ID, NXAPI_AUTH_CLI_SCOPE, setClientAssertionProvider } from './util/nxapi-auth.js';
|
||||
|
||||
const debug = createDebug('cli');
|
||||
|
||||
initGlobals();
|
||||
|
||||
const agent = buildEnvironmentProxyAgent();
|
||||
setGlobalDispatcher(agent);
|
||||
|
||||
export function createYargs(argv: string[]) {
|
||||
const yargs = Yargs(argv).option('data-path', {
|
||||
describe: 'Data storage path',
|
||||
|
|
@ -33,6 +39,7 @@ export function createYargs(argv: string[]) {
|
|||
.demandCommand()
|
||||
.help()
|
||||
// .version(false)
|
||||
.version(product)
|
||||
.showHelpOnFail(false, 'Specify --help for available options');
|
||||
|
||||
return yargs;
|
||||
|
|
@ -53,6 +60,11 @@ export async function main(argv = process.argv.slice(2)) {
|
|||
addUserAgent('unidentified-script');
|
||||
}
|
||||
|
||||
if (NXAPI_AUTH_CLI_CLIENT_ID) {
|
||||
setClientAssertionProvider(new ClientAssertionProvider(NXAPI_AUTH_CLI_CLIENT_ID, undefined,
|
||||
NXAPI_AUTH_CLI_SCOPE));
|
||||
}
|
||||
|
||||
const yargs = createYargs(argv);
|
||||
|
||||
if (!process.env.NXAPI_SKIP_UPDATE_CHECK) await checkUpdates();
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import process from 'node:process';
|
||||
import createDebug from 'debug';
|
||||
import createDebug from '../util/debug.js';
|
||||
import type { Arguments as ParentArguments } from '../cli.js';
|
||||
import { ArgumentsCamelCase, Argv, YargsArguments } from '../util/yargs.js';
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
import process from 'node:process';
|
||||
import { createRequire } from 'node:module';
|
||||
import * as path from 'node:path';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import createDebug from 'debug';
|
||||
import type { Arguments as ParentArguments } from '../cli.js';
|
||||
import createDebug from '../util/debug.js';
|
||||
import { ArgumentsCamelCase, Argv, YargsArguments } from '../util/yargs.js';
|
||||
import { dir } from '../util/product.js';
|
||||
|
||||
const debug = createDebug('cli:app');
|
||||
|
||||
|
|
@ -25,7 +27,7 @@ export async function handler(argv: ArgumentsCamelCase<Arguments>) {
|
|||
}
|
||||
|
||||
execFileSync(electron, [
|
||||
'dist/app/app-entry.cjs',
|
||||
path.resolve(dir, 'dist', 'app', 'app-entry.cjs'),
|
||||
], {
|
||||
stdio: 'inherit',
|
||||
env: {
|
||||
|
|
|
|||
11
src/cli/commands.ts
Normal file
11
src/cli/commands.ts
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
export * as users from './users.js';
|
||||
export * as nso from './nso/index.js';
|
||||
export * as splatnet2 from './splatnet2/index.js';
|
||||
export * as nooklink from './nooklink/index.js';
|
||||
export * as splatnet3 from './splatnet3/index.js';
|
||||
export * as pctl from './pctl/index.js';
|
||||
export * as nxapiAuth from './nxapi-auth/index.js';
|
||||
export * as androidZncaApiServerFrida from './android-znca-api-server-frida.js';
|
||||
export * as presenceServer from './presence-server.js';
|
||||
export * as util from './util/index.js';
|
||||
export * as app from './app.js';
|
||||
|
|
@ -1,10 +0,0 @@
|
|||
export * as users from './users.js';
|
||||
export * as nso from './nso.js';
|
||||
export * as splatnet2 from './splatnet2.js';
|
||||
export * as nooklink from './nooklink.js';
|
||||
export * as splatnet3 from './splatnet3.js';
|
||||
export * as pctl from './pctl.js';
|
||||
export * as androidZncaApiServerFrida from './android-znca-api-server-frida.js';
|
||||
export * as presenceServer from './presence-server.js';
|
||||
export * as util from './util.js';
|
||||
export * as app from './app.js';
|
||||
|
|
@ -1,29 +0,0 @@
|
|||
import process from 'node:process';
|
||||
import createDebug from 'debug';
|
||||
import type { Arguments as ParentArguments } from '../cli.js';
|
||||
import { Argv, YargsArguments } from '../util/yargs.js';
|
||||
import * as commands from './nooklink/index.js';
|
||||
|
||||
const debug = createDebug('cli:nooklink');
|
||||
|
||||
export const command = 'nooklink <command>';
|
||||
export const desc = 'NookLink';
|
||||
|
||||
export function builder(yargs: Argv<ParentArguments>) {
|
||||
for (const command of Object.values(commands)) {
|
||||
// @ts-expect-error
|
||||
yargs.command(command);
|
||||
}
|
||||
|
||||
return yargs.option('znc-proxy-url', {
|
||||
describe: 'URL of Nintendo Switch Online app API proxy server to use',
|
||||
type: 'string',
|
||||
default: process.env.ZNC_PROXY_URL,
|
||||
}).option('auto-update-session', {
|
||||
describe: 'Automatically obtain and refresh the NookLink game web token and user token',
|
||||
type: 'boolean',
|
||||
default: true,
|
||||
});
|
||||
}
|
||||
|
||||
export type Arguments = YargsArguments<ReturnType<typeof builder>>;
|
||||
10
src/cli/nooklink/commands.ts
Normal file
10
src/cli/nooklink/commands.ts
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
export * as users from './users.js';
|
||||
export * as user from './user.js';
|
||||
export * as island from './island.js';
|
||||
export * as newspapers from './newspapers.js';
|
||||
export * as newspaper from './newspaper.js';
|
||||
export * as dumpNewspapers from './dump-newspapers.js';
|
||||
export * as keyboard from './keyboard.js';
|
||||
export * as reactions from './reactions.js';
|
||||
export * as postReaction from './post-reaction.js';
|
||||
export * as userToken from './user-token.js';
|
||||
|
|
@ -1,8 +1,7 @@
|
|||
import * as fs from 'node:fs/promises';
|
||||
import * as path from 'node:path';
|
||||
import createDebug from 'debug';
|
||||
import mkdirp from 'mkdirp';
|
||||
import type { Arguments as ParentArguments } from '../nooklink.js';
|
||||
import type { Arguments as ParentArguments } from './index.js';
|
||||
import createDebug from '../../util/debug.js';
|
||||
import { ArgumentsCamelCase, Argv, YargsArguments } from '../../util/yargs.js';
|
||||
import { initStorage } from '../../util/storage.js';
|
||||
import { getUserToken } from '../../common/auth/nooklink.js';
|
||||
|
|
@ -40,7 +39,7 @@ export async function handler(argv: ArgumentsCamelCase<Arguments>) {
|
|||
|
||||
const directory = argv.directory ?? path.join(argv.dataPath, 'nooklink');
|
||||
|
||||
await mkdirp(directory);
|
||||
await fs.mkdir(directory, {recursive: true});
|
||||
|
||||
const latest = await nooklinkuser.getLatestNewspaper();
|
||||
const newspapers = await nooklinkuser.getNewspapers();
|
||||
|
|
|
|||
|
|
@ -1,10 +1,29 @@
|
|||
export * as users from './users.js';
|
||||
export * as user from './user.js';
|
||||
export * as island from './island.js';
|
||||
export * as newspapers from './newspapers.js';
|
||||
export * as newspaper from './newspaper.js';
|
||||
export * as dumpNewspapers from './dump-newspapers.js';
|
||||
export * as keyboard from './keyboard.js';
|
||||
export * as reactions from './reactions.js';
|
||||
export * as postReaction from './post-reaction.js';
|
||||
export * as userToken from './user-token.js';
|
||||
import process from 'node:process';
|
||||
import type { Arguments as ParentArguments } from '../../cli.js';
|
||||
import createDebug from '../../util/debug.js';
|
||||
import { Argv, YargsArguments } from '../../util/yargs.js';
|
||||
import * as commands from './commands.js';
|
||||
|
||||
const debug = createDebug('cli:nooklink');
|
||||
|
||||
export const command = 'nooklink <command>';
|
||||
export const desc = 'NookLink';
|
||||
|
||||
export function builder(yargs: Argv<ParentArguments>) {
|
||||
for (const command of Object.values(commands)) {
|
||||
// @ts-expect-error
|
||||
yargs.command(command);
|
||||
}
|
||||
|
||||
return yargs.option('znc-proxy-url', {
|
||||
describe: 'URL of Nintendo Switch Online app API proxy server to use',
|
||||
type: 'string',
|
||||
default: process.env.ZNC_PROXY_URL,
|
||||
}).option('auto-update-session', {
|
||||
describe: 'Automatically obtain and refresh the NookLink game web token and user token',
|
||||
type: 'boolean',
|
||||
default: true,
|
||||
});
|
||||
}
|
||||
|
||||
export type Arguments = YargsArguments<ReturnType<typeof builder>>;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import createDebug from 'debug';
|
||||
import Table from '../util/table.js';
|
||||
import type { Arguments as ParentArguments } from '../nooklink.js';
|
||||
import Table from '../../util/table.js';
|
||||
import type { Arguments as ParentArguments } from './index.js';
|
||||
import createDebug from '../../util/debug.js';
|
||||
import { ArgumentsCamelCase, Argv, YargsArguments } from '../../util/yargs.js';
|
||||
import { initStorage } from '../../util/storage.js';
|
||||
import { getUserToken, getWebServiceToken } from '../../common/auth/nooklink.js';
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import createDebug from 'debug';
|
||||
import type { Arguments as ParentArguments } from '../nooklink.js';
|
||||
import { read } from 'read';
|
||||
import type { Arguments as ParentArguments } from './index.js';
|
||||
import createDebug from '../../util/debug.js';
|
||||
import { ArgumentsCamelCase, Argv, YargsArguments } from '../../util/yargs.js';
|
||||
import { initStorage } from '../../util/storage.js';
|
||||
import { getUserToken } from '../../common/auth/nooklink.js';
|
||||
import prompt from '../util/prompt.js';
|
||||
|
||||
const debug = createDebug('cli:nooklink:keyboard');
|
||||
|
||||
|
|
@ -30,7 +30,8 @@ type Arguments = YargsArguments<ReturnType<typeof builder>>;
|
|||
|
||||
export async function handler(argv: ArgumentsCamelCase<Arguments>) {
|
||||
if (!argv.message) {
|
||||
argv.message = await prompt({
|
||||
argv.message = await read<string>({
|
||||
output: process.stderr,
|
||||
prompt: 'Message: ',
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import createDebug from 'debug';
|
||||
import Table from '../util/table.js';
|
||||
import type { Arguments as ParentArguments } from '../nooklink.js';
|
||||
import Table from '../../util/table.js';
|
||||
import type { Arguments as ParentArguments } from './index.js';
|
||||
import createDebug from '../../util/debug.js';
|
||||
import { ArgumentsCamelCase, Argv, YargsArguments } from '../../util/yargs.js';
|
||||
import { initStorage } from '../../util/storage.js';
|
||||
import { getUserToken } from '../../common/auth/nooklink.js';
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import createDebug from 'debug';
|
||||
import Table from '../util/table.js';
|
||||
import type { Arguments as ParentArguments } from '../nooklink.js';
|
||||
import Table from '../../util/table.js';
|
||||
import type { Arguments as ParentArguments } from './index.js';
|
||||
import createDebug from '../../util/debug.js';
|
||||
import { ArgumentsCamelCase, Argv, YargsArguments } from '../../util/yargs.js';
|
||||
import { initStorage } from '../../util/storage.js';
|
||||
import { getUserToken } from '../../common/auth/nooklink.js';
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import createDebug from 'debug';
|
||||
import type { Arguments as ParentArguments } from '../nooklink.js';
|
||||
import type { Arguments as ParentArguments } from './index.js';
|
||||
import createDebug from '../../util/debug.js';
|
||||
import { ArgumentsCamelCase, Argv, YargsArguments } from '../../util/yargs.js';
|
||||
import { initStorage } from '../../util/storage.js';
|
||||
import { getUserToken } from '../../common/auth/nooklink.js';
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import createDebug from 'debug';
|
||||
import Table from '../util/table.js';
|
||||
import type { Arguments as ParentArguments } from '../nooklink.js';
|
||||
import Table from '../../util/table.js';
|
||||
import type { Arguments as ParentArguments } from './index.js';
|
||||
import createDebug from '../../util/debug.js';
|
||||
import { ArgumentsCamelCase, Argv, YargsArguments } from '../../util/yargs.js';
|
||||
import { initStorage } from '../../util/storage.js';
|
||||
import { getUserToken } from '../../common/auth/nooklink.js';
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import createDebug from 'debug';
|
||||
import type { Arguments as ParentArguments } from '../nooklink.js';
|
||||
import type { Arguments as ParentArguments } from './index.js';
|
||||
import createDebug from '../../util/debug.js';
|
||||
import { ArgumentsCamelCase, Argv, YargsArguments } from '../../util/yargs.js';
|
||||
import { initStorage } from '../../util/storage.js';
|
||||
import { getUserToken } from '../../common/auth/nooklink.js';
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user