mirror of
https://github.com/samuelthomas2774/nxapi.git
synced 2026-03-21 18:04:10 -05:00
Compare commits
444 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 | ||
|
|
11077b02ee | ||
|
|
4e67c71dd7 | ||
|
|
14e7793b7c | ||
|
|
4fcecd9f5b | ||
|
|
20dd232a70 | ||
|
|
c5e50167dc | ||
|
|
7afc241190 | ||
|
|
1e75674e08 | ||
|
|
9055be67c5 | ||
|
|
8ab9c39f8c | ||
|
|
e0e8f712aa | ||
|
|
fb9cd6d76f | ||
|
|
7035fb6b19 | ||
|
|
b9f9fd7f4a | ||
|
|
cb78b3f5a7 | ||
|
|
3fcc7b35ae | ||
|
|
d23a65ba2e | ||
|
|
bdf72352fb | ||
|
|
083f3fca17 | ||
|
|
2ab832f6b6 | ||
|
|
205f01ebf0 | ||
|
|
ef5da22df0 | ||
|
|
7243fc3e96 | ||
|
|
67276d6dee | ||
|
|
d115d0d5bf | ||
|
|
055fe2dff4 | ||
|
|
3821a26038 | ||
|
|
496affa811 | ||
|
|
6d1391929f | ||
|
|
890c02e3ef | ||
|
|
827224cd80 | ||
|
|
0c0a27bd8e | ||
|
|
2dbee8bb35 | ||
|
|
3493ed09c0 | ||
|
|
c565dfbf60 | ||
|
|
b916e719bf | ||
|
|
fa877d5bd7 | ||
|
|
19cb8c8775 | ||
|
|
20bab43981 | ||
|
|
a52c45af36 | ||
|
|
4ac5f7f0ea | ||
|
|
7f4b190465 | ||
|
|
c90a36d8d5 | ||
|
|
4739eb1783 | ||
|
|
a8f665953b | ||
|
|
e6e1e73bdc | ||
|
|
0192529020 | ||
|
|
d573cf4dd0 | ||
|
|
0e33825d27 | ||
|
|
f1ae5a7ea2 | ||
|
|
1a25639440 | ||
|
|
6c7f008617 | ||
|
|
0935402b9d | ||
|
|
5014e32756 | ||
|
|
2776c936a1 | ||
|
|
516349e5df | ||
|
|
9cb4ced59f | ||
|
|
a6acd99db7 | ||
|
|
30418d89b6 | ||
|
|
e8cbbd39ca | ||
|
|
c913540ab4 | ||
|
|
82ba22b42f | ||
|
|
6f9afb041d | ||
|
|
9d290563d8 | ||
|
|
628c87c97b | ||
|
|
8a2e4c8090 | ||
|
|
462ec96fe2 | ||
|
|
8f6ae71061 | ||
|
|
a33a36c4f5 | ||
|
|
f88d10b61c | ||
|
|
c319e2685e | ||
|
|
0191edc9ad | ||
|
|
a49b4c427d | ||
|
|
44700fdd3a | ||
|
|
616c40888a | ||
|
|
1e6cec9303 | ||
|
|
04e6a80496 | ||
|
|
dda504b50c | ||
|
|
08ff27398e | ||
|
|
bf48cc201b | ||
|
|
65b36a384e | ||
|
|
02e49a9554 | ||
|
|
bc8e2ae2ac | ||
|
|
e2ac4bbfb3 | ||
|
|
79b1d9eaae | ||
|
|
cbefcad840 | ||
|
|
1ed1e9c817 | ||
|
|
84aa739f4b | ||
|
|
9647d9a411 | ||
|
|
4fac2bb941 | ||
|
|
9d6d49b44d | ||
|
|
5cb66f4249 | ||
|
|
b6002cbf8b | ||
|
|
0b726a7d0e | ||
|
|
605ba117a0 | ||
|
|
32475b76d5 | ||
|
|
8bf06ae439 | ||
|
|
43cbccd9cb | ||
|
|
50d942ae44 | ||
|
|
587b1237fb | ||
|
|
4a7277795c | ||
|
|
19f9ba74ec | ||
|
|
45c315978d | ||
|
|
d9fb2657e6 | ||
|
|
b71246719a | ||
|
|
85d93c681e | ||
|
|
85b9eb0543 | ||
|
|
b869046f1f | ||
|
|
62854fc428 | ||
|
|
c3c42ff8d3 | ||
|
|
72995b1a05 | ||
|
|
a4d328c72a | ||
|
|
d8fc9e352d | ||
|
|
b26f71f930 | ||
|
|
29b8923c5b | ||
|
|
0d3ca779e0 | ||
|
|
a0e9bc79b2 | ||
|
|
088604a509 | ||
|
|
9f001b83ff | ||
|
|
c85d184807 | ||
|
|
32327a0531 | ||
|
|
f4447e6014 | ||
|
|
c7fbe15047 | ||
|
|
4e6a29f74f | ||
|
|
e5fe9b389e | ||
|
|
6f84981018 | ||
|
|
3b9d07042f | ||
|
|
fa2854b527 | ||
|
|
13486a89c8 | ||
|
|
c7948ded9e | ||
|
|
25246be4b5 | ||
|
|
4cdc2adc30 | ||
|
|
99423f263b | ||
|
|
8012dba821 | ||
|
|
c60442fa5e | ||
|
|
6310485db7 | ||
|
|
99f263cef8 | ||
|
|
b7299cb001 | ||
|
|
6276cef356 | ||
|
|
4a993b2ca8 | ||
|
|
31926d83f4 | ||
|
|
7d8cfa7e3b | ||
|
|
56a991b03b | ||
|
|
41623b1bb3 | ||
|
|
07a30e89be | ||
|
|
7576a16af7 | ||
|
|
ccdb4bac8d | ||
|
|
ca0b063f58 | ||
|
|
eaa0c0810e | ||
|
|
809658ac7b | ||
|
|
a6cc0e6254 | ||
|
|
ed3067ff45 | ||
|
|
1da7d5b9aa | ||
|
|
c9c91a874d | ||
|
|
0b91bf87db | ||
|
|
b6099a7d18 | ||
|
|
e3b967a412 | ||
|
|
203a54be44 | ||
|
|
0821235a89 | ||
|
|
4a95c231d3 | ||
|
|
8979c6d28e | ||
|
|
1aa4aad85a | ||
|
|
80afc62268 | ||
|
|
5b93c63c23 | ||
|
|
9112a5a02b | ||
|
|
4b5edd73df | ||
|
|
0421f5e565 | ||
|
|
5236536222 | ||
|
|
8afcd80f5a | ||
|
|
87071dd5c3 | ||
|
|
66c8efdb96 | ||
|
|
960624cae4 | ||
|
|
120f45d561 |
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
|
||||
|
|
|
|||
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -3,4 +3,4 @@ dist
|
|||
data
|
||||
docker-compose.override.yml
|
||||
.env
|
||||
.vscode/schema
|
||||
.vscode/schema/generated
|
||||
|
|
|
|||
333
.gitlab-ci.yml
333
.gitlab-ci.yml
|
|
@ -1,130 +1,245 @@
|
|||
image: node:18
|
||||
|
||||
cache:
|
||||
paths:
|
||||
- node_modules/
|
||||
paths:
|
||||
- node_modules/
|
||||
|
||||
before_script:
|
||||
- npm --color="always" install --force
|
||||
- npm --color="always" install --force
|
||||
|
||||
build:
|
||||
stage: build
|
||||
script:
|
||||
- npx tsc
|
||||
# Uses CI_COMMIT_TAG
|
||||
- NODE_ENV=production npx rollup --config
|
||||
stage: build
|
||||
script:
|
||||
- npx tsc
|
||||
# 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
|
||||
- node bin/nxapi.js util validate-discord-titles
|
||||
|
||||
- "node -e \"fs.writeFileSync('package.json', JSON.stringify((json => {json.__nxapi_release = process.env.CI_COMMIT_TAG; return json;})(JSON.parse(fs.readFileSync('package.json', 'utf-8'))), null, 4) + '\\n', 'utf-8')\""
|
||||
- PACKAGE=`npm --color="always" pack`
|
||||
- mv "$PACKAGE" nxapi.tgz
|
||||
- export VERSION=`[ "$CI_COMMIT_BRANCH" != "main" ] || node resources/build/ci-main-version.js`
|
||||
- node resources/build/ci-package-json.js
|
||||
- PACKAGE=`npm --color="always" pack`
|
||||
- mv "$PACKAGE" nxapi.tgz
|
||||
artifacts:
|
||||
paths:
|
||||
- dist
|
||||
- nxapi.tgz
|
||||
|
||||
- npx electron-builder build --macos zip --linux --publish never
|
||||
- mv dist/app/package app
|
||||
artifacts:
|
||||
paths:
|
||||
- dist
|
||||
- nxapi.tgz
|
||||
- app
|
||||
exclude:
|
||||
- app/mac/**/*
|
||||
- app/win-unpacked/**/*
|
||||
- app/linux-unpacked/**/*
|
||||
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"
|
||||
- |
|
||||
[ "$GH_REGISTRY_IMAGE" != "" ] && docker login -u "$GH_REGISTRY_USER" -p "$GH_REGISTRY_PASSWORD" "$GH_REGISTRY"
|
||||
script:
|
||||
- node resources/build/ci-package-json.js docker "$CI_REGISTRY_IMAGE:ref-$CI_COMMIT_REF_SLUG"
|
||||
|
||||
- docker build --pull --no-cache --tag "$CI_REGISTRY_IMAGE:ref-$CI_COMMIT_REF_SLUG" .
|
||||
- |
|
||||
if [ "$CI_COMMIT_TAG" = "" ]; then
|
||||
docker push "$CI_REGISTRY_IMAGE:ref-$CI_COMMIT_REF_SLUG"
|
||||
fi
|
||||
|
||||
- |
|
||||
if [ "$DH_REGISTRY_IMAGE" != "" ] && [ "$CI_COMMIT_TAG" = "" ]; then
|
||||
docker tag "$CI_REGISTRY_IMAGE:ref-$CI_COMMIT_REF_SLUG" "$DH_REGISTRY_IMAGE:ref-$CI_COMMIT_REF_SLUG"
|
||||
docker push "$DH_REGISTRY_IMAGE:ref-$CI_COMMIT_REF_SLUG"
|
||||
fi
|
||||
|
||||
- |
|
||||
if [ "$GH_REGISTRY_IMAGE" != "" ] && [ "$CI_COMMIT_TAG" = "" ]; then
|
||||
docker tag "$CI_REGISTRY_IMAGE:ref-$CI_COMMIT_REF_SLUG" "$GH_REGISTRY_IMAGE:ref-$CI_COMMIT_REF_SLUG"
|
||||
docker push "$GH_REGISTRY_IMAGE:ref-$CI_COMMIT_REF_SLUG"
|
||||
fi
|
||||
|
||||
- |
|
||||
if [ "$CI_COMMIT_TAG" != "" ]; then
|
||||
docker tag "$CI_REGISTRY_IMAGE:ref-$CI_COMMIT_REF_SLUG" "$CI_REGISTRY_IMAGE:$CI_COMMIT_TAG"
|
||||
docker push "$CI_REGISTRY_IMAGE:$CI_COMMIT_TAG"
|
||||
docker tag "$CI_REGISTRY_IMAGE:ref-$CI_COMMIT_REF_SLUG" "$CI_REGISTRY_IMAGE:latest"
|
||||
docker push "$CI_REGISTRY_IMAGE:latest"
|
||||
fi
|
||||
|
||||
- |
|
||||
if [ "$CI_COMMIT_TAG" != "" ] && [ "$DH_REGISTRY_IMAGE" != "" ]; then
|
||||
docker tag "$CI_REGISTRY_IMAGE:ref-$CI_COMMIT_REF_SLUG" "$DH_REGISTRY_IMAGE:$CI_COMMIT_TAG"
|
||||
docker push "$DH_REGISTRY_IMAGE:$CI_COMMIT_TAG"
|
||||
docker tag "$CI_REGISTRY_IMAGE:ref-$CI_COMMIT_REF_SLUG" "$DH_REGISTRY_IMAGE:latest"
|
||||
docker push "$DH_REGISTRY_IMAGE:latest"
|
||||
fi
|
||||
|
||||
- |
|
||||
if [ "$CI_COMMIT_TAG" != "" ] && [ "$GH_REGISTRY_IMAGE" != "" ]; then
|
||||
docker tag "$CI_REGISTRY_IMAGE:ref-$CI_COMMIT_REF_SLUG" "$GH_REGISTRY_IMAGE:$CI_COMMIT_TAG"
|
||||
docker push "$GH_REGISTRY_IMAGE:$CI_COMMIT_TAG"
|
||||
docker tag "$CI_REGISTRY_IMAGE:ref-$CI_COMMIT_REF_SLUG" "$GH_REGISTRY_IMAGE:latest"
|
||||
docker push "$GH_REGISTRY_IMAGE:latest"
|
||||
fi
|
||||
rules:
|
||||
- if: $BUILD_DOCKER_IMAGE == "true"
|
||||
cache:
|
||||
policy: pull
|
||||
|
||||
build-app:
|
||||
stage: build
|
||||
script:
|
||||
- node resources/build/ci-package-json.js
|
||||
|
||||
- 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
|
||||
artifacts:
|
||||
paths:
|
||||
- app
|
||||
exclude:
|
||||
- app/mac/**/*
|
||||
- app/mac-arm64/**/*
|
||||
- app/linux-unpacked/**/*
|
||||
rules:
|
||||
- if: $BUILD_APP == "true"
|
||||
cache:
|
||||
paths:
|
||||
- node_modules/
|
||||
policy: pull
|
||||
|
||||
build-windows:
|
||||
stage: build
|
||||
image: electronuserland/builder:wine
|
||||
script:
|
||||
- npx tsc
|
||||
# Uses CI_COMMIT_TAG
|
||||
- NODE_ENV=production npx rollup --config
|
||||
stage: build
|
||||
image: electronuserland/builder:wine
|
||||
script:
|
||||
- node resources/build/ci-package-json.js
|
||||
|
||||
- node bin/nxapi.js util validate-discord-titles
|
||||
|
||||
- "node -e \"fs.writeFileSync('package.json', JSON.stringify((json => {json.__nxapi_release = process.env.CI_COMMIT_TAG; return json;})(JSON.parse(fs.readFileSync('package.json', 'utf-8'))), null, 4) + '\\n', 'utf-8')\""
|
||||
|
||||
- npx electron-builder build --win nsis --publish never
|
||||
- mv dist/app/package app
|
||||
artifacts:
|
||||
paths:
|
||||
- app
|
||||
exclude:
|
||||
- app/mac/**/*
|
||||
- app/win-unpacked/**/*
|
||||
- app/linux-unpacked/**/*
|
||||
only:
|
||||
variables:
|
||||
- $BUILD_WINDOWS_APP == "true"
|
||||
cache:
|
||||
paths:
|
||||
- node_modules/
|
||||
policy: pull
|
||||
- npx electron-builder build --win nsis --publish never
|
||||
- mv dist/app/package app
|
||||
needs:
|
||||
- job: build
|
||||
artifacts:
|
||||
paths:
|
||||
- app
|
||||
exclude:
|
||||
- app/win-unpacked/**/*
|
||||
rules:
|
||||
- if: $BUILD_WINDOWS_APP == "true"
|
||||
cache:
|
||||
paths:
|
||||
- node_modules/
|
||||
policy: pull
|
||||
|
||||
publish-npm:
|
||||
stage: deploy
|
||||
script:
|
||||
- echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc
|
||||
- npm --color="always" publish
|
||||
dependencies:
|
||||
- build
|
||||
only:
|
||||
refs:
|
||||
- /^v.*$/
|
||||
variables:
|
||||
- $NPM_TOKEN
|
||||
except:
|
||||
- branches
|
||||
cache:
|
||||
paths:
|
||||
- node_modules/
|
||||
policy: pull
|
||||
stage: deploy
|
||||
script:
|
||||
- node resources/build/ci-package-json.js
|
||||
|
||||
- echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc
|
||||
- npm --color="always" publish
|
||||
needs:
|
||||
- build
|
||||
rules:
|
||||
- if: $CI_COMMIT_TAG =~ /^v/ && $NPM_TOKEN
|
||||
cache:
|
||||
paths:
|
||||
- node_modules/
|
||||
policy: pull
|
||||
|
||||
publish-gitlab:
|
||||
stage: deploy
|
||||
script:
|
||||
# Update the package.json and package-lock.json
|
||||
- "node -e \"fs.writeFileSync('package.json', JSON.stringify((json => {json.name = process.env.GITLAB_NPM_PACKAGE_NAME; json.publishConfig = {access: 'public'}; return json;})(JSON.parse(fs.readFileSync('package.json', 'utf-8'))), null, 4) + '\\n', 'utf-8')\""
|
||||
- "node -e \"fs.writeFileSync('package-lock.json', JSON.stringify((json => {json.name = process.env.GITLAB_NPM_PACKAGE_NAME; return json;})(JSON.parse(fs.readFileSync('package-lock.json', 'utf-8'))), null, 4) + '\\n', 'utf-8')\""
|
||||
stage: deploy
|
||||
script:
|
||||
# Update the package.json and package-lock.json
|
||||
- node resources/build/ci-package-json.js gitlab
|
||||
|
||||
- echo "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/npm/:_authToken=${CI_JOB_TOKEN}" | sed s/^https:// > .npmrc
|
||||
- npm --color="always" --registry=${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/npm/ publish
|
||||
dependencies:
|
||||
- build
|
||||
only:
|
||||
refs:
|
||||
- /^v.*$/
|
||||
variables:
|
||||
- $GITLAB_NPM_PUBLISH == "true"
|
||||
- $GITLAB_NPM_PACKAGE_NAME
|
||||
except:
|
||||
- branches
|
||||
cache:
|
||||
paths:
|
||||
- node_modules/
|
||||
policy: pull
|
||||
- echo "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/npm/:_authToken=${CI_JOB_TOKEN}" | sed s/^https:// > .npmrc
|
||||
- npm --color="always" --registry=${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/npm/ publish
|
||||
needs:
|
||||
- build
|
||||
rules:
|
||||
- if: $CI_COMMIT_TAG =~ /^v/ && $GITLAB_NPM_PUBLISH == "true" && $GITLAB_NPM_PACKAGE_NAME
|
||||
cache:
|
||||
paths:
|
||||
- node_modules/
|
||||
policy: pull
|
||||
|
||||
publish-github:
|
||||
stage: deploy
|
||||
script:
|
||||
# Update the package.json and package-lock.json
|
||||
- "node -e \"fs.writeFileSync('package.json', JSON.stringify((json => {json.name = process.env.GITHUB_NPM_PACKAGE_NAME; json.publishConfig = {access: 'public'}; json.repository = {type: 'git', url: 'https://github.com/' + process.env.GITHUB_REPOSITORY + '.git'}; return json;})(JSON.parse(fs.readFileSync('package.json', 'utf-8'))), null, 4) + '\\n', 'utf-8')\""
|
||||
- "node -e \"fs.writeFileSync('package-lock.json', JSON.stringify((json => {json.name = process.env.GITHUB_NPM_PACKAGE_NAME; return json;})(JSON.parse(fs.readFileSync('package-lock.json', 'utf-8'))), null, 4) + '\\n', 'utf-8')\""
|
||||
stage: deploy
|
||||
script:
|
||||
# Update the package.json and package-lock.json
|
||||
- node resources/build/ci-package-json.js github
|
||||
|
||||
- echo "//npm.pkg.github.com/:_authToken=${GITHUB_NPM_TOKEN}" > .npmrc
|
||||
- npm --color="always" --registry=https://npm.pkg.github.com/ publish
|
||||
dependencies:
|
||||
- build
|
||||
only:
|
||||
refs:
|
||||
- /^v.*$/
|
||||
variables:
|
||||
- $GITHUB_REPOSITORY
|
||||
- $GITHUB_NPM_PACKAGE_NAME
|
||||
- $GITHUB_NPM_TOKEN
|
||||
except:
|
||||
- branches
|
||||
cache:
|
||||
paths:
|
||||
- node_modules/
|
||||
policy: pull
|
||||
- echo "//npm.pkg.github.com/:_authToken=${GITHUB_NPM_TOKEN}" > .npmrc
|
||||
- npm --color="always" --registry=https://npm.pkg.github.com/ publish
|
||||
needs:
|
||||
- build
|
||||
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/
|
||||
policy: pull
|
||||
|
||||
publish-next:
|
||||
stage: deploy
|
||||
script:
|
||||
- export VERSION=`[ "$CI_COMMIT_BRANCH" != "main" ] || node resources/build/ci-main-version.js`
|
||||
- node resources/build/ci-package-json.js
|
||||
|
||||
- |
|
||||
if [ "$CI_COMMIT_BRANCH" = "main" -a "$VERSION" != "" ]; then
|
||||
if [ "$NPM_PUBLISH_NEXT" = "true" -a "$NPM_TOKEN" != "" ]; then
|
||||
echo "Publishing $VERSION to npm"
|
||||
# Prerelease version was already written to package.json
|
||||
echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc
|
||||
npm --color="always" publish --tag next
|
||||
fi
|
||||
|
||||
if [ "$GITLAB_NPM_PUBLISH_NEXT" = "true" -a "$GITLAB_NPM_PACKAGE_NAME" != "" ]; then
|
||||
echo "Publishing $VERSION to GitLab"
|
||||
node resources/build/ci-package-json.js gitlab
|
||||
|
||||
echo "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/npm/:_authToken=${CI_JOB_TOKEN}" | sed s/^https:// > .npmrc
|
||||
npm --color="always" --registry=${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/npm/ publish --tag next
|
||||
fi
|
||||
|
||||
if [ "$GITHUB_NPM_PUBLISH_NEXT" = "true" -a "$GITHUB_NPM_PACKAGE_NAME" != "" -a "$GITHUB_REPOSITORY" != "" -a "$GITHUB_NPM_TOKEN" != "" ]; then
|
||||
echo "Publishing $VERSION to GitHub"
|
||||
node resources/build/ci-package-json.js github
|
||||
|
||||
echo "//npm.pkg.github.com/:_authToken=${GITHUB_NPM_TOKEN}" > .npmrc
|
||||
npm --color="always" --registry=https://npm.pkg.github.com/ publish --tag next
|
||||
fi
|
||||
fi
|
||||
needs:
|
||||
- build
|
||||
rules:
|
||||
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
|
||||
cache:
|
||||
paths:
|
||||
- node_modules/
|
||||
policy: pull
|
||||
|
|
|
|||
21
.vscode/generate-schemas.sh
vendored
21
.vscode/generate-schemas.sh
vendored
|
|
@ -1,19 +1,10 @@
|
|||
#!/bin/sh
|
||||
|
||||
mkdir -p .vscode/schema/{moon,splatnet2,nooklink}
|
||||
mkdir -p .vscode/schema/generated
|
||||
|
||||
npx ts-json-schema-generator --path src/api/moon-types.ts --type DailySummary --no-type-check > .vscode/schema/moon/dailysummary.schema.json
|
||||
npx ts-json-schema-generator --path src/api/moon-types.ts --type MonthlySummary --no-type-check > .vscode/schema/moon/monthlysummary.schema.json
|
||||
npx ts-json-schema-generator --path src/api/moon-types.ts --expose all --no-type-check > .vscode/schema/generated/moon-types.schema.json
|
||||
npx ts-json-schema-generator --path src/api/splatnet2-types.ts --expose all --no-type-check > .vscode/schema/generated/splatnet2-types.schema.json
|
||||
npx ts-json-schema-generator --path src/api/nooklink-types.ts --expose all --no-type-check > .vscode/schema/generated/nooklink-types.schema.json
|
||||
npx ts-json-schema-generator --path src/api/splatnet3-types.ts --expose all --no-type-check > .vscode/schema/generated/splatnet3-types.schema.json
|
||||
|
||||
npx ts-json-schema-generator --path src/api/splatnet2-types.ts --type Records --no-type-check > .vscode/schema/splatnet2/records.schema.json
|
||||
npx ts-json-schema-generator --path src/api/splatnet2-types.ts --type NicknameAndIcon --no-type-check > .vscode/schema/splatnet2/ni.schema.json
|
||||
npx ts-json-schema-generator --path src/api/splatnet2-types.ts --type Timeline --no-type-check > .vscode/schema/splatnet2/timeline.schema.json
|
||||
npx ts-json-schema-generator --path src/api/splatnet2-types.ts --type HeroRecords --no-type-check > .vscode/schema/splatnet2/hero.schema.json
|
||||
npx ts-json-schema-generator --path src/api/splatnet2-types.ts --type Results --no-type-check > .vscode/schema/splatnet2/results-summary.schema.json
|
||||
npx ts-json-schema-generator --path src/api/splatnet2-types.ts --type ResultWithPlayerNicknameAndIcons --no-type-check > .vscode/schema/splatnet2/result.schema.json
|
||||
npx ts-json-schema-generator --path src/api/splatnet2-types.ts --type CoopResults --no-type-check > .vscode/schema/splatnet2/coop-summary.schema.json
|
||||
npx ts-json-schema-generator --path src/api/splatnet2-types.ts --type CoopResultWithPlayerNicknameAndIcons --no-type-check > .vscode/schema/splatnet2/coop-result.schema.json
|
||||
|
||||
npx ts-json-schema-generator --path src/api/nooklink-types.ts --type Newspaper --no-type-check > .vscode/schema/nooklink/newspaper.schema.json
|
||||
|
||||
npx ts-json-schema-generator --path src/common/remote-config.ts --type NxapiRemoteConfig --no-type-check > .vscode/schema/remote-config.schema.json
|
||||
npx ts-json-schema-generator --path src/common/remote-config.ts --type NxapiRemoteConfig --no-type-check > .vscode/schema/generated/remote-config.schema.json
|
||||
|
|
|
|||
24
.vscode/launch.json
vendored
24
.vscode/launch.json
vendored
|
|
@ -17,7 +17,7 @@
|
|||
"runtimeExecutable": "${workspaceFolder}/node_modules/electron/dist/electron.exe"
|
||||
},
|
||||
"args": [
|
||||
"dist/app/main/app-entry.cjs"
|
||||
"dist/app/app-entry.cjs"
|
||||
],
|
||||
"outputCapture": "std",
|
||||
"env": {
|
||||
|
|
@ -25,6 +25,28 @@
|
|||
"DEBUG_COLORS": "1",
|
||||
"FORCE_COLOR": "3"
|
||||
},
|
||||
"envFile": "${workspaceFolder}/.env"
|
||||
},
|
||||
{
|
||||
"name": "Coral API proxy",
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"cwd": "${workspaceFolder}",
|
||||
"program": "bin/nxapi.js",
|
||||
"args": [
|
||||
"nso",
|
||||
"http-server",
|
||||
"--listen",
|
||||
"[::1]:8080",
|
||||
"--no-require-token"
|
||||
],
|
||||
"outputCapture": "std",
|
||||
"env": {
|
||||
"DEBUG": "*,-express:*,-body-parser:*",
|
||||
"DEBUG_COLORS": "1",
|
||||
"FORCE_COLOR": "3"
|
||||
},
|
||||
"envFile": "${workspaceFolder}/.env"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
4
.vscode/schema/moon/dailysummary.schema.json
vendored
Normal file
4
.vscode/schema/moon/dailysummary.schema.json
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$ref": "../generated/moon-types.schema.json#/definitions/DailySummary"
|
||||
}
|
||||
4
.vscode/schema/moon/monthlysummary.schema.json
vendored
Normal file
4
.vscode/schema/moon/monthlysummary.schema.json
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$ref": "../generated/moon-types.schema.json#/definitions/MonthlySummary"
|
||||
}
|
||||
4
.vscode/schema/nooklink/newspaper.schema.json
vendored
Normal file
4
.vscode/schema/nooklink/newspaper.schema.json
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$ref": "../generated/nooklink-types.schema.json#/definitions/Newspaper"
|
||||
}
|
||||
4
.vscode/schema/splatnet2/coop-result.schema.json
vendored
Normal file
4
.vscode/schema/splatnet2/coop-result.schema.json
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$ref": "../generated/splatnet2-types.schema.json#/definitions/CoopResultWithPlayerNicknameAndIcons"
|
||||
}
|
||||
4
.vscode/schema/splatnet2/coop-summary.schema.json
vendored
Normal file
4
.vscode/schema/splatnet2/coop-summary.schema.json
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$ref": "../generated/splatnet2-types.schema.json#/definitions/CoopResults"
|
||||
}
|
||||
4
.vscode/schema/splatnet2/hero.schema.json
vendored
Normal file
4
.vscode/schema/splatnet2/hero.schema.json
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$ref": "../generated/splatnet2-types.schema.json#/definitions/HeroRecords"
|
||||
}
|
||||
4
.vscode/schema/splatnet2/ni.schema.json
vendored
Normal file
4
.vscode/schema/splatnet2/ni.schema.json
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$ref": "../generated/splatnet2-types.schema.json#/definitions/NicknameAndIcon"
|
||||
}
|
||||
4
.vscode/schema/splatnet2/records.schema.json
vendored
Normal file
4
.vscode/schema/splatnet2/records.schema.json
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$ref": "../generated/splatnet2-types.schema.json#/definitions/Records"
|
||||
}
|
||||
4
.vscode/schema/splatnet2/result.schema.json
vendored
Normal file
4
.vscode/schema/splatnet2/result.schema.json
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$ref": "../generated/splatnet2-types.schema.json#/definitions/ResultWithPlayerNicknameAndIcons"
|
||||
}
|
||||
4
.vscode/schema/splatnet2/results-summary.schema.json
vendored
Normal file
4
.vscode/schema/splatnet2/results-summary.schema.json
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$ref": "../generated/splatnet2-types.schema.json#/definitions/Results"
|
||||
}
|
||||
4
.vscode/schema/splatnet2/timeline.schema.json
vendored
Normal file
4
.vscode/schema/splatnet2/timeline.schema.json
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$ref": "../generated/splatnet2-types.schema.json#/definitions/Timeline"
|
||||
}
|
||||
12
.vscode/schema/splatnet3/coop-result.schema.json
vendored
Normal file
12
.vscode/schema/splatnet3/coop-result.schema.json
vendored
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"result": {
|
||||
"$ref": "../generated/splatnet3-types.schema.json#/definitions/CoopHistoryDetail"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"result"
|
||||
]
|
||||
}
|
||||
12
.vscode/schema/splatnet3/result.schema.json
vendored
Normal file
12
.vscode/schema/splatnet3/result.schema.json
vendored
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"result": {
|
||||
"$ref": "../generated/splatnet3-types.schema.json#/definitions/VsHistoryDetail"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"result"
|
||||
]
|
||||
}
|
||||
11
.vscode/settings.json
vendored
11
.vscode/settings.json
vendored
|
|
@ -50,9 +50,18 @@
|
|||
"url": "./.vscode/schema/nooklink/newspaper.schema.json"
|
||||
},
|
||||
|
||||
{
|
||||
"fileMatch": ["**/splatnet3-result-*.json"],
|
||||
"url": "./.vscode/schema/splatnet3/result.schema.json"
|
||||
},
|
||||
{
|
||||
"fileMatch": ["**/splatnet3-coop-result-*.json"],
|
||||
"url": "./.vscode/schema/splatnet3/coop-result.schema.json"
|
||||
},
|
||||
|
||||
{
|
||||
"fileMatch": ["**/resources/common/remote-config.json", "**/data/remote-config.json"],
|
||||
"url": "./.vscode/schema/remote-config.schema.json"
|
||||
"url": "./.vscode/schema/generated/remote-config.schema.json"
|
||||
},
|
||||
],
|
||||
"typescript.tsdk": "node_modules/typescript/lib",
|
||||
|
|
|
|||
12
Dockerfile
12
Dockerfile
|
|
@ -1,4 +1,4 @@
|
|||
FROM node:18 as build
|
||||
FROM node:20 as build
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
|
|
@ -13,11 +13,7 @@ ADD tsconfig.json /app
|
|||
|
||||
RUN npx tsc
|
||||
|
||||
FROM node:18
|
||||
|
||||
RUN apt update && \
|
||||
apt install -y android-tools-adb && \
|
||||
apt-get clean
|
||||
FROM node:20
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
|
|
@ -25,18 +21,16 @@ ADD package.json /app
|
|||
ADD package-lock.json /app
|
||||
|
||||
RUN npm ci --production
|
||||
RUN npm install --no-save frida
|
||||
|
||||
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
|
||||
ENV NXAPI_DATA_PATH=/data
|
||||
ENV NODE_ENV=production
|
||||
|
||||
RUN ln -s /data/android /root/.android
|
||||
|
||||
VOLUME [ "/data" ]
|
||||
|
||||
ENTRYPOINT [ "/app/resources/docker-entrypoint.sh" ]
|
||||
|
|
|
|||
661
LICENSE
Normal file
661
LICENSE
Normal file
|
|
@ -0,0 +1,661 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
262
README.md
262
README.md
|
|
@ -1,73 +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 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
|
||||
- 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 ...
|
||||
Nintendo\ Switch\ Online.app/Contents/bin/nxapi
|
||||
|
||||
# Windows
|
||||
node 'Nintendo Switch Online/resources/app/dist/bundle/cli-bundle.js' ...
|
||||
# Linux, installed via dpkg
|
||||
# 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?
|
||||
|
|
@ -76,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.
|
||||
|
|
@ -88,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.
|
||||
|
||||
|
|
@ -130,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
|
||||
|
|
@ -149,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
|
||||
|
|
@ -205,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.
|
||||
|
|
@ -218,24 +266,33 @@ Environment variable | Description
|
|||
`NXAPI_DATA_PATH` | Sets the location to store user data. See [data location](#data-location).
|
||||
`ZNC_PROXY_URL` | Sets the URL of the nxapi znc API proxy server. See [API proxy server](docs/cli.md#api-proxy-server).
|
||||
`NXAPI_ZNCA_API` | Sets the API to use for Coral client authentication. Either `flapg` or `imink`. See [Coral client authentication](#coral-client-authentication).
|
||||
`ZNCA_API_URL` | Sets the URL of the nxapi znca API server to use for Coral client authentication, if `NXAPI_ZNCA_API` is not set. See [znca API server](docs/cli.md#znca-api-server).
|
||||
`ZNCA_API_URL` | Sets the URL of the nxapi znca API server to use for Coral client authentication, if `NXAPI_ZNCA_API` is not set. See https://gitlab.fancy.org.uk/samuel/nxapi-znca-api or https://github.com/samuelthomas2774/nxapi-znca-api.
|
||||
`NXAPI_USER_AGENT` | Sets the application/script user agent string used by the nxapi command. See [user agent strings](#user-agent-strings).
|
||||
`NXAPI_ENABLE_REMOTE_CONFIG` | Disables fetching and using remote configuration data if set to `0`. Do not disable remote configuration if nxapi has run with it enabled.
|
||||
`NXAPI_REMOTE_CONFIG_FALLBACK` | Allows using local configuration data if the remote configuration data cannot be fetched if set to `1`. This should not be used, as it can cause nxapi to revert to local configuration data after previously using newer remote configuration data.
|
||||
`NXAPI_CONFIG_URL` | Sets the URL to fetch remote configuration data from.
|
||||
`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.
|
||||
|
||||
#### User agent strings
|
||||
|
||||
As nxapi can be used in scripts or as a library, it exposes a few different methods for setting a user agent string for requests to the splatnet2statink, flapg, imink and other non-Nintendo APIs. You must include the name and version number of your script/program in the user agent. If your program is not open source or not easily discoverable (e.g. by searching GitHub) it must also include contact information.
|
||||
As nxapi can be used in scripts or as a library, it exposes a few different methods for setting a user agent string for requests to the imink, flapg and other non-Nintendo APIs. You must include the name and version number of your script/program in the user agent. If your program is not open source or not easily discoverable (e.g. by searching GitHub) it must also include contact information.
|
||||
|
||||
When using the nxapi command in a script or other program, the `NXAPI_USER_AGENT` environment variable should be used. The `NXAPI_USER_AGENT` environment variable is only used by the nxapi command, and will be ignored by the Electron app or when using nxapi as a library.
|
||||
|
||||
```sh
|
||||
NXAPI_USER_AGENT="your-script/1.0.0 (+https://github.com/...)" nxapi nso ...
|
||||
export NXAPI_USER_AGENT="your-script/1.0.0 (+https://github.com/...)"
|
||||
nxapi nso ...
|
||||
```
|
||||
|
||||
When using nxapi as a TypeScript/JavaScript library, the `addUserAgent` function should be used.
|
||||
|
|
@ -244,98 +301,36 @@ 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
|
||||
|
||||
nxapi exports it's API library and types. See [docs/lib](docs/lib/index.md) and [src/exports](src/exports).
|
||||
nxapi exports it's API library and types.
|
||||
|
||||
> You must set a user agent string using the `addUserAgent` function when using anything that contacts non-Nintendo APIs, such as the splatnet2statink API.
|
||||
|
||||
> Please read https://github.com/frozenpandaman/splatnet2statink/wiki/api-docs and https://github.com/JoneWang/imink/wiki/imink-API-Documentation if you intend to share anything you create.
|
||||
|
||||
> nxapi uses native ECMAScript modules. nxapi also uses features like top-level await, so it cannot be converted to CommonJS using Rollup or similar. If you need to use nxapi from CommonJS modules or other module systems, use a [dynamic import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import).
|
||||
|
||||
> If you need any help using nxapi as a library [join the Discord server](https://discord.com/invite/4D82rFkXRv) or [create a discussion](https://github.com/samuelthomas2774/nxapi/discussions/new).
|
||||
|
||||
Example authenticating to the Nintendo Switch Online app:
|
||||
|
||||
> This is a simplified example of authenticating to the Coral API and using cached tokens. More logic is required to ensure you are using these APIs properly, and to renew expired tokens - [see src/common/auth/coral.ts for the authentication functions used in nxapi's CLI and Electron app](src/common/auth/coral.ts).
|
||||
|
||||
```ts
|
||||
import { addUserAgent } from 'nxapi';
|
||||
import CoralApi, { CoralAuthData } from 'nxapi/coral';
|
||||
|
||||
addUserAgent('your-script/1.0.0 (+https://github.com/...)');
|
||||
|
||||
declare function getCachedCoralToken(): [CoralAuthData, Date];
|
||||
declare function setCachedCoralToken(auth_data: CoralAuthData, expires_at: Date): void;
|
||||
declare function getNintendoAccountSessionToken(): string;
|
||||
|
||||
let coral;
|
||||
|
||||
try {
|
||||
const [auth_data, expires_at] = getCachedCoralToken();
|
||||
if (expires_at.getTime() > Date.now()) throw new Error('Token expired');
|
||||
|
||||
coral = CoralApi.createWithSavedToken(auth_data);
|
||||
} catch (err) {
|
||||
const na_session_token = getNintendoAccountSessionToken();
|
||||
const {nso, data} = await CoralApi.createWithSessionToken(na_session_token);
|
||||
setCachedCoralToken(data, Date.now() + (data.credential.expiresIn * 1000));
|
||||
coral = nso;
|
||||
}
|
||||
|
||||
const friends = await coral.getFriendList();
|
||||
```
|
||||
|
||||
Example getting SplatNet 2 records:
|
||||
|
||||
> This example does not include authenticating to SplatNet 2. To benefit from the caching in the nxapi command, the `nxapi splatnet2 token --json` command can be used in most scripts. For example:
|
||||
>
|
||||
> ```sh
|
||||
> SPLATNET_TOKEN=`nxapi splatnet2 token --json` node your-script.js
|
||||
> ```
|
||||
>
|
||||
> your-script.js can then read the iksm_session, unique player ID and region like this:
|
||||
>
|
||||
> ```ts
|
||||
> import SplatNet2Api from 'nxapi/splatnet2';
|
||||
>
|
||||
> const data = JSON.parse(process.env.SPLATNET_TOKEN);
|
||||
> const splatnet2 = SplatNet2Api.createWithCliTokenData(data);
|
||||
> ```
|
||||
|
||||
```ts
|
||||
import SplatNet2Api from 'nxapi/splatnet2';
|
||||
|
||||
const iksm_session = '...';
|
||||
const unique_id = '...';
|
||||
const splatnet2 = SplatNet2Api.createWithIksmSession(iksm_session, unique_id);
|
||||
|
||||
const records = await splatnet2.getRecords();
|
||||
```
|
||||
See [docs/lib](docs/lib/index.md) and [src/exports](src/exports).
|
||||
|
||||
<a name="splatnet2statink-and-flapg"></a>
|
||||
|
||||
### 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 [splatnet2statink and flapg APIs](https://github.com/frozenpandaman/splatnet2statink/wiki/api-docs) can be used by setting the `NXAPI_ZNCA_API` environment variable to `flapg`. Note that the splatnet2statink API, which is required to use the flapg API, is deprecated in favour of using only the imink API and scheduled to be shut down by the end of 2022. (`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.
|
||||
|
||||
|
|
@ -345,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~~
|
||||
|
|
@ -367,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>
|
||||
|
|
@ -1,7 +1,11 @@
|
|||
version: '3'
|
||||
|
||||
services:
|
||||
web:
|
||||
#
|
||||
# Coral/znc proxy
|
||||
#
|
||||
|
||||
znc-proxy:
|
||||
build: .
|
||||
command: nso http-server --listen \[::]:80
|
||||
restart: unless-stopped
|
||||
|
|
@ -12,40 +16,59 @@ services:
|
|||
traefik.http.routers.nxapi-znc.tls: true
|
||||
traefik.http.services.nxapi-znc.loadbalancer.server.port: 80
|
||||
environment:
|
||||
DEBUG: '*,-express:*'
|
||||
ZNCA_API_URL: http://znca-api/api/znca
|
||||
DEBUG: '*,-express:*,-body-parser:*'
|
||||
# ZNCA_API_URL: http://znca-api/api/znca
|
||||
env_file: .env
|
||||
volumes:
|
||||
- data:/data
|
||||
|
||||
znca-api:
|
||||
image: ${COMPOSE_PROJECT_NAME:-nxapi}_web
|
||||
command:
|
||||
- android-znca-api-server-frida
|
||||
- $ZNCA_API_ANDROID_DEVICE
|
||||
- --exec-command
|
||||
- ${ZNCA_API_EXEC_COMMAND:-}
|
||||
- --frida-server-path
|
||||
- ${ZNCA_API_FRIDA_SERVER_PATH:-/data/local/tmp/frida-server}
|
||||
- --listen
|
||||
- '[::]:80'
|
||||
#
|
||||
# Presence server
|
||||
#
|
||||
# Start with docker compose --profile presence-server up -d.
|
||||
#
|
||||
# Users used to fetch presence data must have a saved session token, e.g. by
|
||||
# running docker compose run --rm -it presence-server nso auth/token. If not
|
||||
# all users have access to SplatNet 3, remove the --splatnet3 option and don't
|
||||
# start the presence-splatnet3-proxy service.
|
||||
#
|
||||
# The znc-proxy and presence-splatnet3-proxy services allow the presence-server
|
||||
# service to be scaled without sending additional requests to Nintendo servers.
|
||||
# The znc-proxy and presence-splatnet3-proxy services should not be scaled as
|
||||
# they handle fetching data from Nintendo.
|
||||
#
|
||||
|
||||
presence-server:
|
||||
build: .
|
||||
command: presence-server --listen \[::]:80 --splatnet3 --splatnet3-fest-votes
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
- web
|
||||
profiles:
|
||||
- presence-server
|
||||
labels:
|
||||
traefik.enable: true
|
||||
traefik.http.routers.nxapi-znca.entrypoints: websecure
|
||||
traefik.http.routers.nxapi-znca.rule: Host(`${TRAEFIK_HOST:-nxapi.ta.fancy.org.uk}`) && PathPrefix(`/api/znca/`)
|
||||
traefik.http.routers.nxapi-znca.tls: true
|
||||
traefik.http.services.nxapi-znca.loadbalancer.server.port: 80
|
||||
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/`) || PathPrefix(`/api/splatnet3/resources/`))
|
||||
traefik.http.routers.nxapi-presence.tls: true
|
||||
traefik.http.services.nxapi-presence.loadbalancer.server.port: 80
|
||||
environment:
|
||||
DEBUG: '*,-express:*,-body-parser:*'
|
||||
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
|
||||
volumes:
|
||||
- data:/data
|
||||
|
||||
presence-splatnet3-proxy:
|
||||
build: .
|
||||
command: presence-server --listen \[::]:80 --splatnet3 --splatnet3-proxy --splatnet3-record-fest-votes
|
||||
restart: unless-stopped
|
||||
profiles:
|
||||
- presence-server
|
||||
environment:
|
||||
DEBUG: '*,-express:*'
|
||||
ZNC_PROXY_URL: http://znc-proxy/api/znc
|
||||
volumes:
|
||||
- data:/data
|
||||
healthcheck:
|
||||
test: [ "ENTRYPOINT", "curl", "http://[::1]:80" ]
|
||||
timeout: 45s
|
||||
interval: 10s
|
||||
retries: 10
|
||||
|
||||
volumes:
|
||||
data:
|
||||
|
|
|
|||
269
docs/cli.md
269
docs/cli.md
|
|
@ -201,7 +201,7 @@ curl --no-buffer "http://[::1]:12345/api/znc/presence/events?user=0123456789abcd
|
|||
SplatNet 2
|
||||
---
|
||||
|
||||
All SplatNet 2 commands may automatically request a web service token. This will involve the splatnet2statink and flapg APIs (or a custom server). This can be disabled by setting `--no-auto-update-session`, however this will cause commands to fail if there isn't a valid SplatNet 2 token.
|
||||
All SplatNet 2 commands may automatically request a web service token. This will involve the imink/flapg API (or a custom server). This can be disabled by setting `--no-auto-update-session`, however this will cause commands to fail if there isn't a valid SplatNet 2 token.
|
||||
|
||||
### User
|
||||
|
||||
|
|
@ -343,7 +343,7 @@ nxapi nso presence --splatnet2-monitor --sn2-update-interval 60
|
|||
NookLink
|
||||
---
|
||||
|
||||
All NookLink commands may automatically request a web service token. This will involve the splatnet2statink and flapg APIs (or a custom server). This can be disabled by setting `--no-auto-update-session`, however this will cause commands to fail if there isn't a valid NookLink token.
|
||||
All NookLink commands may automatically request a web service token. This will involve the imink/flapg API (or a custom server). This can be disabled by setting `--no-auto-update-session`, however this will cause commands to fail if there isn't a valid NookLink token.
|
||||
|
||||
### User
|
||||
|
||||
|
|
@ -414,6 +414,144 @@ nxapi nooklink reactions
|
|||
nxapi nooklink post-reaction happyflower
|
||||
```
|
||||
|
||||
SplatNet 3
|
||||
---
|
||||
|
||||
All SplatNet 3 commands may automatically request a web service token. This will involve the imink/flapg API (or a custom server). This can be disabled by setting `--no-auto-update-session`, however this will cause commands to fail if there isn't a valid SplatNet 3 token.
|
||||
|
||||
### User
|
||||
|
||||
```sh
|
||||
# Show the authenticated SplatNet 3 user
|
||||
nxapi splatnet3 user
|
||||
```
|
||||
|
||||
### Download history/hero/catalog records and stage/weapon stats
|
||||
|
||||
```sh
|
||||
# Download user records to the splatnet3 directory in nxapi's data path
|
||||
nxapi splatnet3 dump-records
|
||||
# Download user records to data/splatnet3
|
||||
nxapi splatnet3 dump-records data/splatnet3
|
||||
|
||||
# Only download history records
|
||||
nxapi splatnet3 dump-records --history
|
||||
# Only download hero records
|
||||
nxapi splatnet3 dump-records --hero
|
||||
# Only download catalog records
|
||||
nxapi splatnet3 dump-records --catalog
|
||||
# Only download stage stats
|
||||
nxapi splatnet3 dump-records --stage
|
||||
# Only download weapon stats
|
||||
nxapi splatnet3 dump-records --weapon
|
||||
```
|
||||
|
||||
### Download Splatfest records
|
||||
|
||||
```sh
|
||||
# Download Splatfest records to the splatnet3 directory in nxapi's data path
|
||||
nxapi splatnet3 dump-fests
|
||||
# Download Splatfest records to data/splatnet3
|
||||
nxapi splatnet3 dump-fests data/splatnet3
|
||||
|
||||
# Include rankings
|
||||
nxapi splatnet3 dump-fests --include-rankings
|
||||
```
|
||||
|
||||
### Download photo album items
|
||||
|
||||
```sh
|
||||
# Download photos to the splatnet3 directory in nxapi's data path
|
||||
nxapi splatnet3 dump-album
|
||||
# Download photos to data/splatnet3
|
||||
nxapi splatnet3 dump-album data/splatnet3
|
||||
```
|
||||
|
||||
### Download history/hero/catalog records and stage/weapon stats
|
||||
|
||||
```sh
|
||||
# Download user records to the splatnet3 directory in nxapi's data path
|
||||
nxapi splatnet3 dump-records
|
||||
# Download user records to data/splatnet3
|
||||
nxapi splatnet3 dump-records data/splatnet3
|
||||
|
||||
# Only download history records
|
||||
nxapi splatnet3 dump-records --history
|
||||
# Only download hero records
|
||||
nxapi splatnet3 dump-records --hero
|
||||
# Only download catalog records
|
||||
nxapi splatnet3 dump-records --catalog
|
||||
# Only download stage stats
|
||||
nxapi splatnet3 dump-records --stage
|
||||
# Only download weapon stats
|
||||
nxapi splatnet3 dump-records --weapon
|
||||
```
|
||||
|
||||
### Download battle/Salmon Run results
|
||||
|
||||
```sh
|
||||
# Download battle and Salmon Run results to the splatnet3 directory in nxapi's data path
|
||||
# Data that already exists will not be redownloaded
|
||||
nxapi splatnet3 dump-results
|
||||
# Download battle and Salmon Run results to data/splatnet3
|
||||
nxapi splatnet3 dump-results data/splatnet3
|
||||
|
||||
# Only download battle results
|
||||
nxapi splatnet3 dump-results --battles
|
||||
# Only download Salmon Run results
|
||||
nxapi splatnet3 dump-results --coop
|
||||
|
||||
# Additionally download history records
|
||||
nxapi splatnet3 dump-results --include-history
|
||||
# Additionally download catalog records
|
||||
nxapi splatnet3 dump-results --include-catalog
|
||||
```
|
||||
|
||||
### Monitor SplatNet 3 for new user records/battle/Salmon Run results
|
||||
|
||||
This will constantly check SplatNet 3 for new data.
|
||||
|
||||
```sh
|
||||
# Watch for new battle and Salmon Run results and photo album items and download them
|
||||
# to the splatnet3 directory in nxapi's data path
|
||||
nxapi splatnet3 monitor
|
||||
|
||||
# Watch for new battle and Salmon Run results and download them to data/splatnet3
|
||||
nxapi splatnet3 monitor data/splatnet3
|
||||
|
||||
# Download history records when new battle/coop results are available
|
||||
nxapi splatnet3 monitor --include-history
|
||||
# Download catalog records when new battle/coop results are available
|
||||
nxapi splatnet3 monitor --include-catalog
|
||||
# Download stage stats when new battle results are available
|
||||
nxapi splatnet3 monitor --include-stage
|
||||
# Download weapon stats when new battle results are available
|
||||
nxapi splatnet3 monitor --include-weapon
|
||||
|
||||
# Only monitor battle results
|
||||
nxapi splatnet3 monitor --battles
|
||||
# Only monitor Salmon Run results
|
||||
nxapi splatnet3 monitor --coop
|
||||
# Only monitor photo album items
|
||||
nxapi splatnet3 monitor --album
|
||||
|
||||
# Set update interval to 1800 seconds (30 minutes)
|
||||
nxapi splatnet3 monitor --update-interval 1800
|
||||
```
|
||||
|
||||
### Friends
|
||||
|
||||
```sh
|
||||
# Show Nintendo Switch friends who have played Splatoon 3 in a table
|
||||
# This shows more information about in-game activities than `nxapi nso friends`
|
||||
# Friends that are online and selected in a game will appear as online, even if they are not playing Splatoon 3
|
||||
nxapi splatnet3 friends
|
||||
|
||||
# JSON
|
||||
nxapi splatnet3 friends --json
|
||||
nxapi splatnet3 friends --json-pretty-print
|
||||
```
|
||||
|
||||
Nintendo Switch Parental Controls
|
||||
---
|
||||
|
||||
|
|
@ -491,6 +629,99 @@ nxapi pctl dump-summaries data/summaries
|
|||
nxapi pctl dump-summaries --device 0123456789abcdef
|
||||
```
|
||||
|
||||
Presence server
|
||||
---
|
||||
|
||||
nxapi includes a HTTP server for fetching presence data from Coral and SplatNet 3.
|
||||
|
||||
```sh
|
||||
# Start the server listening on all interfaces on a random port
|
||||
# The `--user` option is required and can be used multiple times
|
||||
nxapi presence-server --user 0123456789abcdef
|
||||
|
||||
# Start the server listening on a specific address/port
|
||||
# The `--listen` option can be used multiple times
|
||||
nxapi presence-server --listen "[::1]:12345" --user 0123456789abcdef
|
||||
|
||||
# Enable Splatoon 3 presence data using SplatNet 3
|
||||
# All users specified with the `--user` option must be able to access SplatNet 3
|
||||
nxapi presence-server --user 0123456789abcdef --splatnet3
|
||||
|
||||
# Allow returning presence data for all users at `/api/presence`
|
||||
nxapi presence-server --user 0123456789abcdef --allow-all-users
|
||||
|
||||
# Set the update interval to 5 minutes (300 seconds)
|
||||
nxapi presence-server --user 0123456789abcdef --update-interval 300
|
||||
```
|
||||
|
||||
```sh
|
||||
# Fetch all available presence data using curl (requires the `--allow-all-users` option)
|
||||
curl http://[::1]:12345/api/presence
|
||||
|
||||
# Fetch presence data for a specific user using curl
|
||||
# Replace `0123456789abcdef` with the user's NSA ID
|
||||
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:
|
||||
|
||||
```ts
|
||||
const events = new EventSource('https://[::1]:12345/api/presence/0123456789abcdef/events');
|
||||
|
||||
events.addEventListener('close', event => {
|
||||
console.error('Event stream closed', event);
|
||||
// Handle reconnecting to the server...
|
||||
});
|
||||
|
||||
events.addEventListener('friend', event => {
|
||||
const data = JSON.parse(event.data);
|
||||
console.log('Received Coral presence data', data.presence);
|
||||
});
|
||||
```
|
||||
|
||||
Misc. commands/options
|
||||
---
|
||||
|
||||
|
|
@ -524,36 +755,6 @@ This command has no options, but environment variables can still be used.
|
|||
|
||||
### znca API server
|
||||
|
||||
A server for controlling the Nintendo Switch Online app on an Android device/emulator using Frida can be used instead of the splatnet2statink and flapg APIs.
|
||||
A server for controlling the Nintendo Switch Online app on an Android device/emulator using Frida can be used instead of the imink/flapg APIs to generate `f` parameters for authentication.
|
||||
|
||||
This requires:
|
||||
|
||||
- adb is installed on the computer running nxapi
|
||||
- The Android device is running adbd as root or a su-like command can be used to escalate to root
|
||||
- The frida-server executable is located at `/data/local/tmp/frida-server` on the Android device
|
||||
- The Nintendo Switch Online app is installed on the Android device
|
||||
|
||||
The Android device must be constantly reachable using ADB. The server will exit if the device is unreachable.
|
||||
|
||||
```sh
|
||||
# Start the server using the ADB server "android.local:5555" listening on all interfaces on a random port
|
||||
nxapi android-znca-api-server-frida android.local:5555
|
||||
|
||||
# Start the server listening on a specific address/port
|
||||
# The `--listen` option can be used multiple times
|
||||
nxapi android-znca-api-server-frida android.local:5555 --listen "[::1]:12345"
|
||||
|
||||
# Use a command to escalate to root to start frida-server and the Nintendo Switch Online app
|
||||
# "{cmd}" will be replaced with the path to a temporary script in double quotes
|
||||
nxapi android-znca-api-server-frida android.local:5555 --exec-command "/system/bin/su -c {cmd}"
|
||||
|
||||
# Specify a different location to the frida-server executable
|
||||
nxapi android-znca-api-server-frida android.local:5555 --frida-server-path "/data/local/tmp/frida-server-15.1.17-android-arm"
|
||||
|
||||
# Make API requests using curl
|
||||
curl --header "Content-Type: application/json" --data '{"type": "nso", "token": "...", "timestamp": "...", "uuid": "..."}' "http://[::1]:12345/api/znca/f"
|
||||
|
||||
# Use the znca API server in other commands
|
||||
# This should be set when running any nso commands as the access token will be refreshed automatically when it expires
|
||||
ZNCA_API_URL=http://[::1]:12345/api/znca nxapi nso ...
|
||||
```
|
||||
This is now a separate project at https://gitlab.fancy.org.uk/samuel/nxapi-znca-api or https://github.com/samuelthomas2774/nxapi-znca-api.
|
||||
|
|
|
|||
1
docs/lib/README.md
Symbolic link
1
docs/lib/README.md
Symbolic link
|
|
@ -0,0 +1 @@
|
|||
index.md
|
||||
|
|
@ -54,8 +54,9 @@ import CoralApi, { CoralAuthData, PartialCoralAuthData } from 'nxapi/coral';
|
|||
|
||||
const coral: CoralApi;
|
||||
const auth_data: CoralAuthData;
|
||||
const na_session_token: string;
|
||||
|
||||
const data = await coral.renewToken(auth_data);
|
||||
const data = await coral.renewToken(na_session_token, auth_data.user);
|
||||
// data is a plain object of type PartialCoralAuthData
|
||||
|
||||
const new_auth_data = Object.assign({}, auth_data, data);
|
||||
|
|
@ -63,6 +64,34 @@ const new_auth_data = Object.assign({}, auth_data, data);
|
|||
// new_auth_data should be saved and reused
|
||||
```
|
||||
|
||||
#### `CoralApi.onTokenExpired`
|
||||
|
||||
Function called when a `9404 Token expired` response is received from the API.
|
||||
|
||||
This function should either call `CoralApi.getToken` to renew the token, then return the `PartialCoralAuthData` object, or call `CoralApi.renewToken`.
|
||||
|
||||
```ts
|
||||
import CoralApi, { CoralAuthData } from 'nxapi/coral';
|
||||
import { Response } from 'node-fetch';
|
||||
|
||||
const coral = CoralApi.createWithSavedToken(...);
|
||||
let auth_data: CoralAuthData;
|
||||
const na_session_token: string;
|
||||
|
||||
coral.onTokenExpired = async (response: Response) => {
|
||||
const data = await coral.getToken(na_session_token, auth_data.user);
|
||||
// data is a plain object of type PartialCoralAuthData
|
||||
|
||||
const new_auth_data = Object.assign({}, auth_data, data);
|
||||
// new_auth_data is a plain object of type CoralAuthData
|
||||
// new_auth_data should be saved and reused
|
||||
|
||||
auth_data = new_auth_data;
|
||||
|
||||
return data;
|
||||
};
|
||||
```
|
||||
|
||||
### `ZncProxyApi`
|
||||
|
||||
nxapi API proxy server client. Instances of this class are generally compatible with `CoralApi`; nxapi's command line interface and Electron apps internally use either depending on whether the API proxy is enabled.
|
||||
|
|
|
|||
|
|
@ -3,16 +3,88 @@ Usage as a JavaScript library
|
|||
|
||||
nxapi exports it's API library and types. nxapi is split into several modules that can be imported separately.
|
||||
|
||||
> You must set a user agent string using the `addUserAgent` function when using anything that contacts non-Nintendo APIs, such as the splatnet2statink API.
|
||||
> You must set a user agent string using the `addUserAgent` function when using anything that contacts non-Nintendo APIs, such as the imink API.
|
||||
|
||||
> Please read https://github.com/frozenpandaman/splatnet2statink/wiki/api-docs and https://github.com/JoneWang/imink/wiki/imink-API-Documentation if you intend to share anything you create.
|
||||
|
||||
> By default nxapi will fetch certain settings, mostly version numbers to report to Nintendo, from my server. This can be disabled using environment variables.
|
||||
|
||||
> nxapi uses native ECMAScript modules. nxapi also uses features like top-level await, so it cannot be converted to CommonJS using Rollup or similar. If you need to use nxapi from CommonJS modules or other module systems, use a [dynamic import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import).
|
||||
>
|
||||
> For TypeScript projects, this means you need to set `moduleResolution` to `node16` (or `nodenext`) (https://www.typescriptlang.org/tsconfig#moduleResolution). I recommend setting the following options:
|
||||
>
|
||||
> ```jsonc
|
||||
> {
|
||||
> "compilerOptions": {
|
||||
> "strict": true,
|
||||
> "target": "es2020",
|
||||
> "module": "node16",
|
||||
> "moduleResolution": "node16",
|
||||
> "skipLibCheck": true
|
||||
> }
|
||||
> }
|
||||
> ```
|
||||
|
||||
> If you need any help using nxapi as a library [join the Discord server](https://discord.com/invite/4D82rFkXRv) or [create a discussion](https://github.com/samuelthomas2774/nxapi/discussions/new).
|
||||
|
||||
Example authenticating to the Nintendo Switch Online app:
|
||||
|
||||
> This is a simplified example of authenticating to the Coral API and using cached tokens. More logic is required to ensure you are using these APIs properly, and to renew expired tokens - [see src/common/auth/coral.ts for the authentication functions used in nxapi's CLI and Electron app](src/common/auth/coral.ts).
|
||||
|
||||
```ts
|
||||
import { addUserAgent } from 'nxapi';
|
||||
import CoralApi, { CoralAuthData } from 'nxapi/coral';
|
||||
|
||||
addUserAgent('your-script/1.0.0 (+https://github.com/...)');
|
||||
|
||||
declare function getCachedCoralToken(): [CoralAuthData, Date];
|
||||
declare function setCachedCoralToken(auth_data: CoralAuthData, expires_at: Date): void;
|
||||
declare function getNintendoAccountSessionToken(): string;
|
||||
|
||||
let coral;
|
||||
|
||||
try {
|
||||
const [auth_data, expires_at] = getCachedCoralToken();
|
||||
if (expires_at.getTime() > Date.now()) throw new Error('Token expired');
|
||||
|
||||
coral = CoralApi.createWithSavedToken(auth_data);
|
||||
} catch (err) {
|
||||
const na_session_token = getNintendoAccountSessionToken();
|
||||
const {nso, data} = await CoralApi.createWithSessionToken(na_session_token);
|
||||
setCachedCoralToken(data, Date.now() + (data.credential.expiresIn * 1000));
|
||||
coral = nso;
|
||||
}
|
||||
|
||||
const friends = await coral.getFriendList();
|
||||
```
|
||||
|
||||
Example getting SplatNet 2 records:
|
||||
|
||||
> This example does not include authenticating to SplatNet 2. To benefit from the caching in the nxapi command, the `nxapi splatnet2 token --json` command can be used in most scripts. For example:
|
||||
>
|
||||
> ```sh
|
||||
> SPLATNET_TOKEN=`nxapi splatnet2 token --json` node your-script.js
|
||||
> ```
|
||||
>
|
||||
> your-script.js can then read the iksm_session, unique player ID and region like this:
|
||||
>
|
||||
> ```ts
|
||||
> import SplatNet2Api from 'nxapi/splatnet2';
|
||||
>
|
||||
> const data = JSON.parse(process.env.SPLATNET_TOKEN);
|
||||
> const splatnet2 = SplatNet2Api.createWithCliTokenData(data);
|
||||
> ```
|
||||
|
||||
```ts
|
||||
import SplatNet2Api from 'nxapi/splatnet2';
|
||||
|
||||
const iksm_session = '...';
|
||||
const unique_id = '...';
|
||||
const splatnet2 = SplatNet2Api.createWithIksmSession(iksm_session, unique_id);
|
||||
|
||||
const records = await splatnet2.getRecords();
|
||||
```
|
||||
|
||||
### Install
|
||||
|
||||
nxapi should be installed as a project dependency rather than a globally installed package. TypeScript definitions are included and do not need to be installed separately.
|
||||
|
|
@ -79,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.
|
||||
|
|
@ -112,3 +188,9 @@ This module exports the SplatNet 2 API library and types, as well as functions f
|
|||
This module exports the NookLink API library and types.
|
||||
|
||||
[See docs/lib/nooklink.md.](nooklink.md)
|
||||
|
||||
### `nxapi/splatnet3`
|
||||
|
||||
This module exports the SplatNet 3 API library and types.
|
||||
|
||||
[See docs/lib/splatnet3.md.](splatnet3.md)
|
||||
|
|
|
|||
|
|
@ -56,6 +56,31 @@ const data = await moon.renewToken(na_session_token);
|
|||
// data should be saved and reused
|
||||
```
|
||||
|
||||
#### `MoonApi.onTokenExpired`
|
||||
|
||||
Function called when a `401 Unauthorized` response is received from the API.
|
||||
|
||||
This function should either call `MoonApi.loginWithSessionToken` to renew the token, then return the `MoonAuthData` object, or call `MoonApi.renewToken`.
|
||||
|
||||
```ts
|
||||
import MoonApi, { MoonAuthData } from 'nxapi/moon';
|
||||
import { Response } from 'node-fetch';
|
||||
|
||||
const moon = MoonApi.createWithSavedToken(...);
|
||||
let auth_data: MoonAuthData;
|
||||
const na_session_token: string;
|
||||
|
||||
moon.onTokenExpired = async (error: MoonError, response: Response) => {
|
||||
const data = await MoonApi.loginWithSessionToken(na_session_token);
|
||||
// data is a plain object of type MoonAuthData
|
||||
// data should be saved and reused
|
||||
|
||||
auth_data = data;
|
||||
|
||||
return data;
|
||||
};
|
||||
```
|
||||
|
||||
### API types
|
||||
|
||||
`nxapi/moon` exports all API types from [src/api/moon-types.ts](../../src/api/moon-types.ts).
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
`nxapi/nooklink`
|
||||
---
|
||||
|
||||
NookLink is more complex that SplatNet 2 as it supports multiple users linked to the same network account.
|
||||
NookLink is more complex than other web services as it supports multiple users linked to the same network account:
|
||||
|
||||
- `NooklinkApi` is used at NSA-level, and is solely used to list available NookLink users and authenticate to NookLink at ACNH-level.
|
||||
- `NooklinkUserApi` is used at ACNH-level, and is used to perform all other actions in the NookLink web app.
|
||||
|
|
@ -76,6 +76,31 @@ const {nooklinkuser, data} = await nooklink.createUserClient(user_id);
|
|||
// data is a plain object of type NooklinkUserAuthData
|
||||
```
|
||||
|
||||
#### `NooklinkApi.onTokenExpired`
|
||||
|
||||
Function called when a `401 Unauthorized` response is received from the API.
|
||||
|
||||
This function should either call `NooklinkApi.loginWithWebServiceToken` or `NooklinkApi.loginWithCoral` to renew the token, then return the `NooklinkAuthData` object, or call `NooklinkApi.renewTokenWithWebServiceToken` or `NooklinkApi.renewTokenWithCoral`.
|
||||
|
||||
```ts
|
||||
import NooklinkApi, { NooklinkAuthData, WebServiceError } from 'nxapi/nooklink';
|
||||
import { Response } from 'node-fetch';
|
||||
|
||||
const nooklink = NooklinkApi.createWithSavedToken(...);
|
||||
let auth_data: NooklinkAuthData;
|
||||
const na_session_token: string;
|
||||
|
||||
nooklink.onTokenExpired = async (error: WebServiceError, response: Response) => {
|
||||
const data = await NooklinkApi.loginWithSessionToken(na_session_token);
|
||||
// data is a plain object of type NooklinkAuthData
|
||||
// data should be saved and reused
|
||||
|
||||
auth_data = data;
|
||||
|
||||
return data;
|
||||
};
|
||||
```
|
||||
|
||||
### `NooklinkUserApi`
|
||||
|
||||
NookLink ACNH-level API client. An instance of this class should not be created directly; instead `NooklinkApi.createUserClient` or one of the `createWith*` static methods should be used.
|
||||
|
|
@ -110,6 +135,37 @@ const nooklinkuser = NooklinkUserApi.createWithCliTokenData(data);
|
|||
// nooklinkuser instanceof NooklinkUserApi
|
||||
```
|
||||
|
||||
#### `NooklinkUserApi.onTokenExpired`
|
||||
|
||||
Function called when a `401 Unauthorized` response is received from the API.
|
||||
|
||||
This function should either call `NooklinkUserApi.getToken` to renew the token, then return the `PartialNooklinkUserAuthData` object, or call `NooklinkUserApi.renewToken`.
|
||||
|
||||
```ts
|
||||
import NooklinkApi, { NooklinkAuthData, NooklinkUserApi, PartialNooklinkUserAuthData, WebServiceError } from 'nxapi/nooklink';
|
||||
import { Response } from 'node-fetch';
|
||||
|
||||
const nooklink: NooklinkApi;
|
||||
|
||||
const nooklinkuser = NooklinkUserApi.createWithSavedToken(...);
|
||||
let auth_data: NooklinkUserAuthData;
|
||||
const na_session_token: string;
|
||||
|
||||
nooklinkuser.onTokenExpired = async (error: WebServiceError, response: Response) => {
|
||||
const data = await nooklinkuser.getToken(nooklink);
|
||||
// data is a plain object of type PartialNooklinkUserAuthData
|
||||
// data should be saved and reused
|
||||
|
||||
const new_auth_data = Object.assign({}, auth_data, data);
|
||||
// new_auth_data is a plain object of type NooklinkUserAuthData
|
||||
// new_auth_data should be saved and reused
|
||||
|
||||
auth_data = new_auth_data;
|
||||
|
||||
return data;
|
||||
};
|
||||
```
|
||||
|
||||
### API types
|
||||
|
||||
`nxapi/nooklink` exports all API types from [src/api/nooklink-types.ts](../../src/api/nooklink-types.ts).
|
||||
|
|
|
|||
123
docs/lib/splatnet3.md
Normal file
123
docs/lib/splatnet3.md
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
`nxapi/splatnet3`
|
||||
---
|
||||
|
||||
### `SplatNet3Api`
|
||||
|
||||
> This is exported as `default`.
|
||||
|
||||
SplatNet 3 API client. An instance of this class should not be created directly; instead one of the `createWith*` static methods should be used.
|
||||
|
||||
Most of this API is intentionally undocumented. Read the source code at [src/api/splatnet3.ts](../../src/api/splatnet3.ts), [src/common/auth/splatnet3.ts](../../src/common/auth/splatnet3.ts) and [src/cli/splatnet3](../../src/cli/splatnet3) for examples of using this API. If you need any help using this API ask in [#splatnet3](https://discordapp.com/channels/998657768594608138/998664939537440820) on Discord.
|
||||
|
||||
You should review HTTP captures of SplatNet 3 in the Nintendo Switch Online app and attempt to match the behaviour of Nintendo's official app.
|
||||
|
||||
#### `SplatNet3Api.createWithCoral`
|
||||
|
||||
Authenticate to SplatNet 3 using a `CoralApi` instance.
|
||||
|
||||
> This function should not be called often. If your project will create a new SplatNet3Api object again for the same user before the SplatNet 3 authentication token expires (usually after 2 hours), you must store the `data` object this returns and use `SplatNet3Api.createWithSavedToken`.
|
||||
|
||||
```ts
|
||||
import CoralApi, { CoralAuthData } from 'nxapi/coral';
|
||||
import SplatNet3Api, { SplatNet3AuthData } from 'nxapi/splatnet3';
|
||||
|
||||
const coral: CoralApi;
|
||||
const coral_auth_data: CoralAuthData;
|
||||
|
||||
const {splatnet, data} = await SplatNet3Api.createWithCoral(coral, coral_auth_data.user);
|
||||
// splatnet instanceof SplatNet3Api
|
||||
// data is a plain object of type SplatNet3AuthData
|
||||
// data should be saved and reused
|
||||
```
|
||||
|
||||
#### `SplatNet3Api.createWithSavedToken`
|
||||
|
||||
Create a SplatNet3Api instance using cached data from `SplatNet3Api.createWithCoral` or `SplatNet3Api.loginWithCoral`.
|
||||
|
||||
```ts
|
||||
import SplatNet3Api, { SplatNet3AuthData } from 'nxapi/splatnet3';
|
||||
|
||||
const auth_data: SplatNet3AuthData;
|
||||
|
||||
const splatnet = SplatNet3Api.createWithSavedToken(auth_data);
|
||||
// splatnet instanceof SplatNet3Api
|
||||
```
|
||||
|
||||
#### `SplatNet3Api.createWithCliTokenData`
|
||||
|
||||
Create a SplatNet3Api instance using the output of the `nxapi splatnet3 token --json` command.
|
||||
|
||||
```ts
|
||||
import SplatNet3Api, { SplatNet3CliTokenData } from 'nxapi/splatnet3';
|
||||
|
||||
const data: SplatNet3CliTokenData;
|
||||
|
||||
const splatnet = SplatNet3Api.createWithCliTokenData(data);
|
||||
// splatnet instanceof SplatNet3Api
|
||||
```
|
||||
|
||||
#### `SplatNet3Api.onTokenExpired`
|
||||
|
||||
Function called when a `401 Unauthorized` response is received from the API, meaning the token has expired.
|
||||
|
||||
This function should either call `SplatNet3Api.loginWithWebServiceToken` or `SplatNet3Api.loginWithCoral` to renew the token, then return the `SplatNet3AuthData` object, or call `SplatNet3Api.renewTokenWithWebServiceToken` or `SplatNet3Api.renewTokenWithCoral`. An existing web service token should be used to avoid calling the imink/flapg API, and then fall back to issuing a new token.
|
||||
|
||||
```ts
|
||||
import { ErrorResponse } from 'nxapi';
|
||||
import CoralApi, { CoralAuthData } from 'nxapi/coral';
|
||||
import SplatNet3Api, { SplatNet3AuthData } from 'nxapi/splatnet3';
|
||||
import { Response } from 'node-fetch';
|
||||
|
||||
let splatnet3_auth_data: SplatNet3AuthData;
|
||||
const splatnet = SplatNet3Api.createWithSavedToken(splatnet3_auth_data);
|
||||
|
||||
splatnet.onTokenExpired = async (response: Response) => {
|
||||
try {
|
||||
// This should be cached - using stale data is fine, as only the user data is used
|
||||
const coral_auth_data: CoralAuthData;
|
||||
|
||||
const data = await SplatNet3Api.loginWithWebServiceToken(splatnet3_auth_data.webserviceToken, coral_auth_data.user);
|
||||
// data is a plain object of type SplatNet3AuthData
|
||||
// data should be saved and reused
|
||||
|
||||
splatnet3_auth_data = data;
|
||||
|
||||
return data;
|
||||
} catch (err) {
|
||||
// `401 Unauthorized` from `/api/bullet_tokens` means the web service token has expired (or is invalid)
|
||||
if (err instanceof ErrorResponse && err.response.status === 401) {
|
||||
const coral: CoralApi;
|
||||
const coral_auth_data: CoralAuthData;
|
||||
|
||||
const data = await SplatNet3Api.loginWithCoral(coral, coral_auth_data.user);
|
||||
// data is a plain object of type SplatNet3AuthData
|
||||
// data should be saved and reused
|
||||
|
||||
splatnet3_auth_data = data;
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
#### `SplatNet3Api.onTokenShouldRenew`
|
||||
|
||||
Function called when the `x-bullettoken-remaining` header received from the API is less than 300, meaning the token will expire in 5 minutes and should be renewed in the background.
|
||||
|
||||
```ts
|
||||
import SplatNet3Api, { SplatNet3AuthData } from 'nxapi/splatnet3';
|
||||
import { Response } from 'node-fetch';
|
||||
|
||||
const splatnet = SplatNet3Api.createWithSavedToken(...);
|
||||
|
||||
splatnet.onTokenShouldRenew = async (remaining: number, response: Response) => {
|
||||
// See SplatNet3Api.onTokenExpired for an example
|
||||
};
|
||||
```
|
||||
|
||||
### API types
|
||||
|
||||
SplatNet 3 types are available from [splatnet3-types](https://gitlab.fancy.org.uk/samuel/splatnet3-types) ([GitHub](https://github.com/nintendoapis/splatnet3-types)).
|
||||
12716
package-lock.json
generated
12716
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
142
package.json
142
package.json
|
|
@ -1,14 +1,17 @@
|
|||
{
|
||||
"name": "nxapi",
|
||||
"version": "1.4.0",
|
||||
"version": "1.6.1",
|
||||
"description": "Nintendo Switch app APIs",
|
||||
"author": "Samuel Elliott",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"author": "Ellie <ellie+nxapi@fancy.org.uk>",
|
||||
"main": "dist/index.js",
|
||||
"type": "module",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git@gitlab.fancy.org.uk:samuel/nxapi.git"
|
||||
},
|
||||
"homepage": "https://gitlab.fancy.org.uk/samuel/nxapi",
|
||||
"bugs": "https://github.com/samuelthomas2774/nxapi/issues",
|
||||
"files": [
|
||||
"dist",
|
||||
"!dist/app",
|
||||
|
|
@ -19,10 +22,12 @@
|
|||
],
|
||||
"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",
|
||||
"./nooklink": "./dist/exports/nooklink.js"
|
||||
"./nooklink": "./dist/exports/nooklink.js",
|
||||
"./splatnet3": "./dist/exports/splatnet3.js"
|
||||
},
|
||||
"bin": {
|
||||
"nxapi": "bin/nxapi.js"
|
||||
|
|
@ -31,64 +36,65 @@
|
|||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"body-parser": "^1.20.0",
|
||||
"@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.1",
|
||||
"dotenv-expand": "^8.0.3",
|
||||
"dotenv": "^16.4.5",
|
||||
"dotenv-expand": "^11.0.6",
|
||||
"env-paths": "^3.0.0",
|
||||
"express": "^4.18.1",
|
||||
"mkdirp": "^1.0.4",
|
||||
"node-fetch": "^3.2.10",
|
||||
"express": "^4.19.2",
|
||||
"murmurhash": "^2.0.1",
|
||||
"node-notifier": "^10.0.1",
|
||||
"node-persist": "^3.1.0",
|
||||
"read": "^1.0.7",
|
||||
"supports-color": "^8.1.1",
|
||||
"tslib": "^2.4.0",
|
||||
"uuid": "^8.3.2",
|
||||
"yargs": "^17.5.1"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"frida": "^15.2.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": "^13.3.0",
|
||||
"@rollup/plugin-replace": "^4.0.0",
|
||||
"@rollup/plugin-typescript": "^8.4.0",
|
||||
"@types/body-parser": "^1.19.2",
|
||||
"@types/cli-table": "^0.3.0",
|
||||
"@types/debug": "^4.1.7",
|
||||
"@types/discord-rpc": "^4.0.3",
|
||||
"@types/express": "^4.17.13",
|
||||
"@types/mkdirp": "^1.0.2",
|
||||
"@types/node": "^18.7.13",
|
||||
"@types/node-notifier": "^8.0.2",
|
||||
"@types/node-persist": "^3.1.2",
|
||||
"@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.11",
|
||||
"electron": "^20.0.3",
|
||||
"electron-builder": "^23.3.3",
|
||||
"frida": "^15.2.2",
|
||||
"react": "^17.0.2",
|
||||
"react-dom": "^17.0.2",
|
||||
"react-native-web": "^0.17.7",
|
||||
"rollup": "^2.78.1",
|
||||
"rollup-plugin-polyfill-node": "^0.10.2",
|
||||
"ts-json-schema-generator": "^1.0.0",
|
||||
"typescript": "^4.7.4"
|
||||
"@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",
|
||||
|
|
@ -96,7 +102,9 @@
|
|||
"!dist/app/package",
|
||||
"!**/node_modules/**/*",
|
||||
"resources/app",
|
||||
"resources/common"
|
||||
"resources/common",
|
||||
"!resources/common/remote-config.json",
|
||||
"resources/cli"
|
||||
],
|
||||
"asar": false,
|
||||
"extraMetadata": {
|
||||
|
|
@ -115,10 +123,42 @@
|
|||
"schemes": [
|
||||
"com.nintendo.znca"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Nintendo Account authentication for Nintendo Switch Online",
|
||||
"schemes": [
|
||||
"npf71b963c1b7b6d119"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Nintendo Account authentication for Nintendo Switch Parental Controls",
|
||||
"schemes": [
|
||||
"npf54789befb391a838"
|
||||
]
|
||||
}
|
||||
],
|
||||
"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'
|
||||
69
resources/build/ci-main-version.js
Normal file
69
resources/build/ci-main-version.js
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import * as fs from 'node:fs/promises';
|
||||
import * as child_process from 'node:child_process';
|
||||
import * as util from 'node:util';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const execFile = util.promisify(child_process.execFile);
|
||||
|
||||
const options = {cwd: fileURLToPath(new URL('../..', import.meta.url))};
|
||||
const git = (...args) => execFile('git', args, options).then(({stdout}) => stdout.toString().trim());
|
||||
|
||||
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([
|
||||
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'),
|
||||
]);
|
||||
|
||||
const branch = branch_str && branch_str !== 'HEAD' ? branch_str : null;
|
||||
const changed_files = changed_files_str.length ? changed_files_str.split('\n') : [];
|
||||
const tags = tags_str.split(/\n|, /).filter(t => t.startsWith('tag: ')).map(t => t.substr(5));
|
||||
const last_tagged_version = tags.find(t => t.startsWith('v'))?.substr(1) ?? null;
|
||||
const last_version = last_tagged_version ?? pkg.version;
|
||||
const commit_count = parseInt(commit_count_str);
|
||||
|
||||
console.warn({
|
||||
version: pkg.version,
|
||||
last_tagged_version,
|
||||
last_version,
|
||||
revision,
|
||||
branch,
|
||||
changed_files,
|
||||
tags,
|
||||
tags_str,
|
||||
commit_count,
|
||||
});
|
||||
|
||||
if (!last_tagged_version || pkg.version !== last_tagged_version) {
|
||||
console.warn('Last tagged version does not match package.json version', {
|
||||
version: pkg.version,
|
||||
tag: last_tagged_version ? 'v' + last_tagged_version : null,
|
||||
});
|
||||
process.exit();
|
||||
}
|
||||
|
||||
const last_tagged_version_commit_count = parseInt(await git('rev-list', '--count', 'v' + last_version));
|
||||
const commit_count_since_last_version = commit_count - last_tagged_version_commit_count;
|
||||
|
||||
console.warn({
|
||||
last_tagged_version_commit_count,
|
||||
commit_count_since_last_version,
|
||||
});
|
||||
|
||||
if (commit_count_since_last_version <= 0) {
|
||||
console.warn('No changes since last tagged version');
|
||||
process.exit();
|
||||
}
|
||||
|
||||
const version = last_version +
|
||||
'-next.' + (commit_count_since_last_version - 1) +
|
||||
'+sha.' + revision.substr(0, 7);
|
||||
|
||||
console.warn({
|
||||
version,
|
||||
});
|
||||
|
||||
console.log(version);
|
||||
69
resources/build/ci-package-json.js
Normal file
69
resources/build/ci-package-json.js
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import * as fs from 'node:fs/promises';
|
||||
import * as child_process from 'node:child_process';
|
||||
import * as util from 'node:util';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const execFile = util.promisify(child_process.execFile);
|
||||
const options = {cwd: fileURLToPath(new URL('../..', import.meta.url))};
|
||||
const git = (...args) => execFile('git', args, options).then(({stdout}) => stdout.toString().trim());
|
||||
|
||||
const pkg = JSON.parse(await fs.readFile(new URL('../../package.json', import.meta.url), 'utf-8'));
|
||||
|
||||
const [revision, branch, changed_files] = await Promise.all([
|
||||
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'),
|
||||
]);
|
||||
|
||||
if (process.argv[2] === 'gitlab') {
|
||||
pkg.name = process.env.GITLAB_NPM_PACKAGE_NAME ?? pkg.name;
|
||||
pkg.publishConfig = {access: 'public'};
|
||||
}
|
||||
|
||||
if (process.argv[2] === 'github') {
|
||||
pkg.name = process.env.GITHUB_NPM_PACKAGE_NAME ?? pkg.name;
|
||||
pkg.repository = {
|
||||
type: 'git',
|
||||
url: 'https://github.com/' + process.env.GITHUB_REPOSITORY + '.git',
|
||||
};
|
||||
pkg.publishConfig = {access: 'public'};
|
||||
}
|
||||
|
||||
pkg.version = process.env.VERSION || pkg.version;
|
||||
pkg.__nxapi_release = process.env.CI_COMMIT_TAG;
|
||||
|
||||
if (process.argv[2] === 'docker') {
|
||||
pkg.__nxapi_docker = process.argv[3];
|
||||
}
|
||||
|
||||
pkg.__nxapi_git = pkg.__nxapi_git ?? {
|
||||
revision,
|
||||
branch: branch && branch !== 'HEAD' ? branch : null,
|
||||
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,19 +1,28 @@
|
|||
{
|
||||
"require_version": [],
|
||||
"log_encryption_key": "E2Sii_7drCzK-68RsEoArmopiAIlZD_6TMA2F_UAAU0",
|
||||
"coral": {
|
||||
"znca_version": "2.2.0"
|
||||
"znca_version": "2.12.0"
|
||||
},
|
||||
"coral_auth": {
|
||||
"default": "imink",
|
||||
"splatnet2statink": {},
|
||||
"flapg": {},
|
||||
"default": [
|
||||
"nxapi",
|
||||
"https:\/\/nxapi-znca-api.fancy.org.uk\/api\/znca"
|
||||
],
|
||||
"splatnet2statink": null,
|
||||
"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": "4.0.0-091d4283",
|
||||
"version": "4.0.0",
|
||||
"revision": "091d428399dc86fd3a7fc43d64bd33b8bd1e875d"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
BIN
resources/discord-activity-splatoon3.png
Normal file
BIN
resources/discord-activity-splatoon3.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 74 KiB |
|
|
@ -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 "$@"
|
||||
|
|
|
|||
115
rollup.config.js
115
rollup.config.js
|
|
@ -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,8 +109,8 @@ const main = {
|
|||
}),
|
||||
],
|
||||
external: [
|
||||
'electron',
|
||||
'node-notifier',
|
||||
'frida',
|
||||
'register-scheme',
|
||||
'bindings',
|
||||
],
|
||||
|
|
@ -111,29 +121,27 @@ const main = {
|
|||
* @type {import('rollup').RollupOptions}
|
||||
*/
|
||||
const app_entry = {
|
||||
input: 'src/app/main/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/main/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',
|
||||
|
|
@ -147,7 +155,10 @@ const app_entry = {
|
|||
],
|
||||
external: [
|
||||
'electron',
|
||||
path.resolve(__dirname, 'src/app/main/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,
|
||||
};
|
||||
|
|
@ -156,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',
|
||||
|
|
@ -164,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({
|
||||
|
|
@ -188,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({
|
||||
|
|
@ -219,30 +218,40 @@ const app_preload_webservice = {
|
|||
* @type {import('rollup').RollupOptions}
|
||||
*/
|
||||
const app_browser = {
|
||||
input: 'src/app/browser/index.ts',
|
||||
input: 'dist/app/browser/index.js',
|
||||
output: {
|
||||
file: 'dist/app/bundle/browser.js',
|
||||
format: 'iife',
|
||||
dir: 'dist/app/bundle',
|
||||
format: 'es',
|
||||
sourcemap: true,
|
||||
manualChunks(id) {
|
||||
if (id.includes('node_modules')) {
|
||||
return 'vendor';
|
||||
}
|
||||
if (id.startsWith('\0')) {
|
||||
return 'internal';
|
||||
}
|
||||
},
|
||||
chunkFileNames: 'chunk-[name].js',
|
||||
},
|
||||
plugins: [
|
||||
html({
|
||||
title: 'nxapi',
|
||||
}),
|
||||
replace(replace_options),
|
||||
typescript({
|
||||
noEmit: true,
|
||||
declaration: false,
|
||||
}),
|
||||
commonjs({
|
||||
// the ".ts" extension is required
|
||||
extensions: ['.js', '.jsx', '.ts', '.tsx'],
|
||||
esmExternals: true,
|
||||
}),
|
||||
nodePolyfill(),
|
||||
alias({
|
||||
entries: [
|
||||
{find: 'react-native', replacement: path.resolve(__dirname, 'node_modules', 'react-native-web')},
|
||||
// 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(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'},
|
||||
],
|
||||
}),
|
||||
nodeResolve({
|
||||
|
|
@ -253,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;
|
||||
|
|
@ -78,9 +78,21 @@ export interface AccountLogin {
|
|||
};
|
||||
}
|
||||
|
||||
/** /v3/Account/GetToken */
|
||||
/** /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/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
|
||||
//
|
||||
|
|
|
|||
1087
src/api/coral.ts
1087
src/api/coral.ts
File diff suppressed because it is too large
Load Diff
841
src/api/f.ts
841
src/api/f.ts
File diff suppressed because it is too large
Load Diff
115
src/api/moon.ts
115
src/api/moon.ts
|
|
@ -1,8 +1,8 @@
|
|||
import fetch from 'node-fetch';
|
||||
import createDebug from 'debug';
|
||||
import { getNintendoAccountToken, getNintendoAccountUser, NintendoAccountToken, NintendoAccountUser } from './na.js';
|
||||
import { ErrorResponse } from './util.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,12 +10,17 @@ 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;
|
||||
/** @internal */
|
||||
_renewToken: Promise<void> | null = null;
|
||||
protected _token_expired = false;
|
||||
|
||||
protected constructor(
|
||||
public token: string,
|
||||
public naId: string,
|
||||
|
|
@ -24,7 +29,25 @@ export default class MoonApi {
|
|||
readonly znma_useragent = ZNMA_USER_AGENT,
|
||||
) {}
|
||||
|
||||
async fetch<T = unknown>(url: string, method = 'GET', body?: string, headers?: object) {
|
||||
async fetch<T extends object>(
|
||||
url: string, method = 'GET', body?: string, headers?: object,
|
||||
/** @internal */ _autoRenewToken = true,
|
||||
/** @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;
|
||||
}
|
||||
|
||||
const [signal, cancel] = timeoutSignal();
|
||||
const response = await fetch(MOON_URL + url, {
|
||||
method,
|
||||
|
|
@ -49,17 +72,30 @@ 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
|
||||
this._renewToken = this._renewToken ?? this.onTokenExpired.call(null, data, response).then(data => {
|
||||
if (data) this.setTokenWithSavedToken(data);
|
||||
}).finally(() => {
|
||||
this._renewToken = null;
|
||||
});
|
||||
return this.fetch(url, method, body, headers, _autoRenewToken, _attempt + 1);
|
||||
}
|
||||
|
||||
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 data;
|
||||
return defineResponse(data, response);
|
||||
}
|
||||
|
||||
async getUser() {
|
||||
|
|
@ -92,13 +128,16 @@ export default class MoonApi {
|
|||
|
||||
async renewToken(token: string) {
|
||||
const data = await MoonApi.loginWithSessionToken(token);
|
||||
|
||||
this.token = data.nintendoAccountToken.access_token!;
|
||||
this.naId = data.user.id;
|
||||
|
||||
this.setTokenWithSavedToken(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
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) {
|
||||
const data = await this.loginWithSessionToken(token);
|
||||
return {moon: this.createWithSavedToken(data), data};
|
||||
|
|
@ -126,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,
|
||||
|
|
@ -138,10 +177,56 @@ 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;
|
||||
}
|
||||
export interface PartialMoonAuthData {
|
||||
nintendoAccountToken: NintendoAccountToken;
|
||||
}
|
||||
|
|
|
|||
343
src/api/na.ts
343
src/api/na.ts
|
|
@ -1,11 +1,131 @@
|
|||
import fetch from 'node-fetch';
|
||||
import createDebug from 'debug';
|
||||
import { 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({
|
||||
|
|
@ -26,18 +145,22 @@ export async function getNintendoAccountSessionToken(code: string, verifier: str
|
|||
signal,
|
||||
}).finally(cancel);
|
||||
|
||||
if (response.status !== 200) {
|
||||
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('[na] ' + token.detail, response, token);
|
||||
}
|
||||
if ('error' in token) {
|
||||
throw new ErrorResponse('[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);
|
||||
|
||||
return token;
|
||||
return defineResponse(token, response);
|
||||
}
|
||||
|
||||
export async function getNintendoAccountToken(token: string, client_id: string) {
|
||||
|
|
@ -59,21 +182,26 @@ export async function getNintendoAccountToken(token: string, client_id: string)
|
|||
signal,
|
||||
}).finally(cancel);
|
||||
|
||||
if (response.status !== 200) {
|
||||
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('[na] ' + nintendoAccountToken.detail, response, nintendoAccountToken);
|
||||
}
|
||||
if ('error' in nintendoAccountToken) {
|
||||
throw new ErrorResponse('[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);
|
||||
|
||||
return nintendoAccountToken;
|
||||
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();
|
||||
|
|
@ -88,15 +216,19 @@ export async function getNintendoAccountUser(token: NintendoAccountToken) {
|
|||
signal,
|
||||
}).finally(cancel);
|
||||
|
||||
const user = await response.json() as NintendoAccountUser | NintendoAccountError;
|
||||
if (response.status !== 200) {
|
||||
throw await NintendoAccountErrorResponse.fromResponse(response, '[na] Non-200 status code');
|
||||
}
|
||||
|
||||
const user = await response.json() as NintendoAccountUser<S> | NintendoAccountError;
|
||||
|
||||
if ('errorCode' in user) {
|
||||
throw new ErrorResponse('[na] ' + user.detail, response, user);
|
||||
throw new NintendoAccountErrorResponse('[na] ' + user.detail, response, user);
|
||||
}
|
||||
|
||||
debug('Got Nintendo Account user info', user);
|
||||
|
||||
return user;
|
||||
return defineResponse(user, response);
|
||||
}
|
||||
|
||||
export interface NintendoAccountSessionToken {
|
||||
|
|
@ -104,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;
|
||||
|
|
@ -118,7 +250,7 @@ export interface NintendoAccountSessionTokenJwtPayload extends JwtPayload {
|
|||
}
|
||||
|
||||
export interface NintendoAccountToken {
|
||||
scope: string[];
|
||||
scope: NintendoAccountScope[];
|
||||
token_type: 'Bearer';
|
||||
id_token: string;
|
||||
access_token?: string;
|
||||
|
|
@ -133,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;
|
||||
}
|
||||
|
|
@ -145,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;
|
||||
|
|
@ -184,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,
|
||||
|
|
@ -212,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 {
|
||||
|
|
@ -297,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,15 +1,14 @@
|
|||
import fetch 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 { ErrorResponse } from './util.js';
|
||||
import CoralApi from './coral.js';
|
||||
import { defineResponse, ErrorResponse, HasResponse } from './util.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');
|
||||
|
||||
export const NOOKLINK_WEBSERVICE_ID = '4953919198265344';
|
||||
export const NOOKLINK_WEBSERVICE_ID = 4953919198265344;
|
||||
export const NOOKLINK_WEBSERVICE_URL = 'https://web.sd.lp1.acbaa.srv.nintendo.net';
|
||||
export const NOOKLINK_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';
|
||||
|
||||
|
|
@ -17,13 +16,36 @@ 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;
|
||||
/** @internal */
|
||||
_renewToken: Promise<void> | null = null;
|
||||
protected _token_expired = false;
|
||||
|
||||
protected constructor(
|
||||
public gtoken: string,
|
||||
public useragent: string,
|
||||
readonly client_version = BLANCO_VERSION,
|
||||
) {}
|
||||
|
||||
async fetch<T = unknown>(url: string, method = 'GET', body?: string | FormData, headers?: object) {
|
||||
async fetch<T extends object>(
|
||||
url: string, method = 'GET', body?: string | FormData, headers?: object,
|
||||
/** @internal */ _autoRenewToken = true,
|
||||
/** @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;
|
||||
}
|
||||
|
||||
const [signal, cancel] = timeoutSignal();
|
||||
const response = await fetch(NOOKLINK_URL + url, {
|
||||
method,
|
||||
|
|
@ -32,7 +54,7 @@ export default class NooklinkApi {
|
|||
'User-Agent': this.useragent,
|
||||
'Cookie': '_gtoken=' + encodeURIComponent(this.gtoken),
|
||||
'dnt': '1',
|
||||
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
|
||||
'Accept': 'application/json, text/plain, */*',
|
||||
'Accept-Language': 'en-GB,en-US;q=0.8',
|
||||
'Origin': 'https://web.sd.lp1.acbaa.srv.nintendo.net',
|
||||
'Content-Type': 'application/json',
|
||||
|
|
@ -44,17 +66,30 @@ export default class NooklinkApi {
|
|||
|
||||
debug('fetch %s %s, response %s', method, url, response.status);
|
||||
|
||||
if (response.status !== 200 && response.status !== 201) {
|
||||
throw new ErrorResponse('[nooklink] Non-200/201 status code', response, await response.text());
|
||||
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
|
||||
this._renewToken = this._renewToken ?? this.onTokenExpired.call(null, data, response).then(data => {
|
||||
if (data) this.setTokenWithSavedToken(data);
|
||||
}).finally(() => {
|
||||
this._renewToken = null;
|
||||
});
|
||||
return this.fetch(url, method, body, headers, _autoRenewToken, _attempt + 1);
|
||||
}
|
||||
|
||||
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('[nooklink] Error ' + data.code, response, data);
|
||||
throw new NooklinkErrorResponse('[nooklink] Error ' + data.code, response, data);
|
||||
}
|
||||
|
||||
return data;
|
||||
return defineResponse(data, response);
|
||||
}
|
||||
|
||||
async getUsers() {
|
||||
|
|
@ -71,8 +106,25 @@ export default class NooklinkApi {
|
|||
return NooklinkUserApi._createWithNooklinkApi(this, user_id);
|
||||
}
|
||||
|
||||
static async createWithCoral(nso: CoralApi, user: NintendoAccountUser) {
|
||||
const data = await this.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: NintendoAccountUserCoral) {
|
||||
const data = await NooklinkApi.loginWithWebServiceToken(webserviceToken, user);
|
||||
this.setTokenWithSavedToken(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
private setTokenWithSavedToken(data: NooklinkAuthData) {
|
||||
this.gtoken = data.gtoken;
|
||||
this._token_expired = false;
|
||||
}
|
||||
|
||||
static async createWithCoral(coral: CoralApiInterface, user: NintendoAccountUserCoral) {
|
||||
const data = await this.loginWithCoral(coral, user);
|
||||
return {nooklink: this.createWithSavedToken(data), data};
|
||||
}
|
||||
|
||||
|
|
@ -80,14 +132,17 @@ export default class NooklinkApi {
|
|||
return new this(data.gtoken, data.useragent);
|
||||
}
|
||||
|
||||
static async loginWithCoral(nso: CoralApi, user: NintendoAccountUser) {
|
||||
const webserviceToken = await nso.getWebServiceToken(NOOKLINK_WEBSERVICE_ID);
|
||||
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');
|
||||
|
||||
return this.loginWithWebServiceToken(webserviceToken.result, user);
|
||||
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');
|
||||
|
|
@ -104,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',
|
||||
|
|
@ -116,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] Unknown error', 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]);
|
||||
|
|
@ -152,6 +208,11 @@ export default class NooklinkApi {
|
|||
}
|
||||
|
||||
export class NooklinkUserApi {
|
||||
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,
|
||||
public auth_token: string,
|
||||
|
|
@ -161,7 +222,25 @@ export class NooklinkUserApi {
|
|||
readonly client_version = BLANCO_VERSION,
|
||||
) {}
|
||||
|
||||
async fetch<T = unknown>(url: string, method = 'GET', body?: string | FormData, headers?: object) {
|
||||
async fetch<T extends object>(
|
||||
url: string, method = 'GET', body?: string | FormData, headers?: object,
|
||||
/** @internal */ _autoRenewToken = true,
|
||||
/** @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;
|
||||
}
|
||||
|
||||
const [signal, cancel] = timeoutSignal();
|
||||
const response = await fetch(NOOKLINK_URL + url, {
|
||||
method,
|
||||
|
|
@ -170,9 +249,8 @@ export class NooklinkUserApi {
|
|||
'User-Agent': this.useragent,
|
||||
'Cookie': '_gtoken=' + encodeURIComponent(this.gtoken),
|
||||
'dnt': '1',
|
||||
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
|
||||
'Accept': 'application/json, text/plain,*/*',
|
||||
'Accept-Language': 'en-GB,en-US;q=0.8',
|
||||
'X-Requested-With': 'com.nintendo.znca',
|
||||
'Origin': 'https://web.sd.lp1.acbaa.srv.nintendo.net',
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer ' + this.auth_token,
|
||||
|
|
@ -184,17 +262,30 @@ export class NooklinkUserApi {
|
|||
|
||||
debug('fetch %s %s, response %s', method, url, response.status);
|
||||
|
||||
if (response.status !== 200 && response.status !== 201) {
|
||||
throw new ErrorResponse('[nooklink] Non-200/201 status code', response, await response.text());
|
||||
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
|
||||
this._renewToken = this._renewToken ?? this.onTokenExpired.call(null, data, response).then(data => {
|
||||
if (data) this.setTokenWithSavedToken(data);
|
||||
}).finally(() => {
|
||||
this._renewToken = null;
|
||||
});
|
||||
return this.fetch(url, method, body, headers, _autoRenewToken, _attempt + 1);
|
||||
}
|
||||
|
||||
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('[nooklink] Error ' + data.code, response, data);
|
||||
throw new NooklinkErrorResponse('[nooklink] Error ' + data.code, response, data);
|
||||
}
|
||||
|
||||
return data;
|
||||
return defineResponse(data, response);
|
||||
}
|
||||
|
||||
async getUserProfile(id?: string) {
|
||||
|
|
@ -222,7 +313,7 @@ export class NooklinkUserApi {
|
|||
}
|
||||
|
||||
async postMessage(body: string, type: MessageType, destination_user_id?: string) {
|
||||
return this.fetch<unknown>('/sd/v1/messages', 'POST', JSON.stringify({
|
||||
return this.fetch('/sd/v1/messages', 'POST', JSON.stringify({
|
||||
type,
|
||||
body,
|
||||
userId: destination_user_id,
|
||||
|
|
@ -241,6 +332,29 @@ export class NooklinkUserApi {
|
|||
return this.postMessage(reaction.label, MessageType.EMOTICON);
|
||||
}
|
||||
|
||||
async getToken(client: NooklinkApi): Promise<PartialNooklinkUserAuthData> {
|
||||
const token = await client.getAuthToken(this.user_id);
|
||||
|
||||
return {
|
||||
gtoken: client.gtoken,
|
||||
user_id: this.user_id,
|
||||
token,
|
||||
};
|
||||
}
|
||||
|
||||
async renewToken(client: NooklinkApi) {
|
||||
const data = await this.getToken(client);
|
||||
this.setTokenWithSavedToken(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
private setTokenWithSavedToken(data: NooklinkUserAuthData | PartialNooklinkUserAuthData) {
|
||||
this.user_id = data.user_id;
|
||||
this.auth_token = data.token.token;
|
||||
this.gtoken = data.gtoken;
|
||||
this._token_expired = false;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
static async _loginWithNooklinkApi(client: NooklinkApi, user_id: string): Promise<NooklinkUserAuthData> {
|
||||
const token = await client.getAuthToken(user_id);
|
||||
|
|
@ -277,6 +391,8 @@ export class NooklinkUserApi {
|
|||
}
|
||||
}
|
||||
|
||||
export class NooklinkErrorResponse extends ErrorResponse<WebServiceError> {}
|
||||
|
||||
export interface NooklinkAuthData {
|
||||
webserviceToken: WebServiceToken;
|
||||
url: string;
|
||||
|
|
@ -298,6 +414,8 @@ export interface NooklinkUserAuthData {
|
|||
token: AuthToken;
|
||||
language: string;
|
||||
}
|
||||
export type PartialNooklinkUserAuthData =
|
||||
Pick<NooklinkUserAuthData, 'gtoken' | 'user_id' | 'token'>;
|
||||
|
||||
export interface NooklinkUserCliTokenData {
|
||||
gtoken: string;
|
||||
|
|
|
|||
|
|
@ -1,17 +1,16 @@
|
|||
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 { ErrorResponse } from './util.js';
|
||||
import CoralApi from './coral.js';
|
||||
import { defineResponse, ErrorResponse } from './util.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';
|
||||
|
||||
const debug = createDebug('nxapi:api:splatnet2');
|
||||
|
||||
export const SPLATNET2_WEBSERVICE_ID = '5741031244955648';
|
||||
export const SPLATNET2_WEBSERVICE_ID = 5741031244955648;
|
||||
export const SPLATNET2_WEBSERVICE_URL = 'https://app.splatoon2.nintendo.net/';
|
||||
export const SPLATNET2_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';
|
||||
|
||||
|
|
@ -25,13 +24,19 @@ export const updateIksmSessionLastUsed: {
|
|||
} = {};
|
||||
|
||||
export default class SplatNet2Api {
|
||||
protected _session_expired = false;
|
||||
|
||||
protected constructor(
|
||||
public iksm_session: string,
|
||||
public unique_id: string,
|
||||
public useragent: string,
|
||||
) {}
|
||||
|
||||
async fetch<T = unknown>(url: string, method = 'GET', body?: string | FormData, headers?: object) {
|
||||
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,10 +70,10 @@ export default class SplatNet2Api {
|
|||
const data = await response.json() as T | WebServiceError;
|
||||
|
||||
if ('code' in data) {
|
||||
throw new ErrorResponse('[splatnet2] ' + data.message, response, data);
|
||||
throw new SplatNet2ErrorResponse('[splatnet2] ' + data.message, response, data);
|
||||
}
|
||||
|
||||
return data;
|
||||
return defineResponse(data, response);
|
||||
}
|
||||
|
||||
async getRecords() {
|
||||
|
|
@ -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.result, user);
|
||||
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] Unknown error', 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;
|
||||
|
|
|
|||
6
src/api/splatnet3-types.ts
Normal file
6
src/api/splatnet3-types.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
/** /bullet_tokens */
|
||||
export interface BulletToken {
|
||||
bulletToken: string;
|
||||
lang: string;
|
||||
is_noe_country: 'true' | 'false';
|
||||
}
|
||||
1205
src/api/splatnet3.ts
Normal file
1205
src/api/splatnet3.ts
Normal file
File diff suppressed because it is too large
Load Diff
|
|
@ -1,5 +1,18 @@
|
|||
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');
|
||||
|
||||
export interface ResponseData<R> {
|
||||
[ResponseSymbol]: R;
|
||||
}
|
||||
export type HasResponse<T, R> = T & ResponseData<R>;
|
||||
|
||||
export function defineResponse<T, R>(data: T, response: R) {
|
||||
Object.defineProperty(data, ResponseSymbol, {enumerable: false, value: response});
|
||||
return data as HasResponse<T, R>;
|
||||
}
|
||||
|
||||
export class ErrorResponse<T = unknown> extends Error {
|
||||
readonly body: string | undefined;
|
||||
|
|
@ -7,11 +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 {
|
||||
|
|
@ -30,18 +58,22 @@ export class ErrorResponse<T = unknown> extends Error {
|
|||
' from ' + response.url + ' (' + response.status + ' ' + response.statusText + ')\n' +
|
||||
' ' + util.inspect(this.data ? this.data : this.body, {
|
||||
compact: true,
|
||||
maxStringLength: 100,
|
||||
}).replace(/\n/g, '\n ') +
|
||||
(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, {
|
||||
configurable: true,
|
||||
value: (instance: ErrorResponse) => {
|
||||
return instance instanceof Error &&
|
||||
'response' in instance &&
|
||||
'body' in instance &&
|
||||
'data' in instance;
|
||||
return instance && ErrorResponseSymbol in instance;
|
||||
},
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,180 +1,300 @@
|
|||
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 { ErrorResponse } from './util.js';
|
||||
import CoralApi from './coral.js';
|
||||
import { NintendoAccountUser } from './na.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 { 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<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 === 204) return null!;
|
||||
|
||||
if (response.status !== 200) {
|
||||
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 = await response.json() as T;
|
||||
const data = (response.status === 204 ? {} : await response.json()) as T;
|
||||
|
||||
return data;
|
||||
return defineResponse(data, response);
|
||||
}
|
||||
|
||||
async call<T = unknown>(url: string, parameter = {}): Promise<CoralSuccessResponse<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 response = await this.fetch<{announcements: Announcements}>('/announcements');
|
||||
return {status: CoralStatus.OK as const, result: response.announcements, correlationId: ''};
|
||||
const result = await this.fetchProxyApi<{announcements: Announcements_4}>('announcements');
|
||||
return createResult(result, result.announcements);
|
||||
}
|
||||
|
||||
async getFriendList() {
|
||||
const response = await this.fetch<{friends: Friend[]}>('/friends');
|
||||
return {status: CoralStatus.OK as const, result: response, correlationId: ''};
|
||||
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) {
|
||||
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 {status: CoralStatus.OK as const, result: {}, correlationId: ''};
|
||||
return createResult(result, {});
|
||||
}
|
||||
|
||||
async removeFavouriteFriend(nsaid: string) {
|
||||
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 {status: CoralStatus.OK as const, result: {}, correlationId: ''};
|
||||
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 response = await this.fetch<{webservices: WebService[]}>('/webservices');
|
||||
return {status: CoralStatus.OK as const, result: response.webservices, correlationId: ''};
|
||||
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 response = await this.fetch<{activeevent: ActiveEvent}>('/activeevent');
|
||||
return {status: CoralStatus.OK as const, result: response.activeevent, correlationId: ''};
|
||||
const result = await this.fetchProxyApi<{activeevent: ActiveEvent | null}>('activeevent');
|
||||
return createResult<GetActiveEventResult, typeof result>(result, result.activeevent ?? {});
|
||||
}
|
||||
|
||||
async getEvent(id: number) {
|
||||
const response = await this.fetch<{event: Event}>('/event/' + id);
|
||||
return {status: CoralStatus.OK as const, result: response.event, correlationId: ''};
|
||||
const result = await this.fetchProxyApi<{event: Event}>('event/' + id);
|
||||
return createResult(result, result.event);
|
||||
}
|
||||
|
||||
async getUser(id: number) {
|
||||
const response = await this.fetch<{user: User}>('/user/' + id);
|
||||
return {status: CoralStatus.OK as const, result: response.user, correlationId: ''};
|
||||
const result = await this.fetchProxyApi<{user: User}>('user/' + id);
|
||||
return createResult(result, result.user);
|
||||
}
|
||||
|
||||
async getUserByFriendCode(friend_code: string, hash?: string) {
|
||||
const response = await this.fetch<{user: FriendCodeUser}>('/friendcode/' + friend_code);
|
||||
return {status: CoralStatus.OK as const, result: response.user, correlationId: ''};
|
||||
const result = await this.fetchProxyApi<{user: FriendCodeUser}>('friendcode/' + friend_code);
|
||||
return createResult(result, result.user);
|
||||
}
|
||||
|
||||
async sendFriendRequest(nsa_id: string): Promise<CoralSuccessResponse<{}>> {
|
||||
throw new Error('Not supported in ZncProxyApi');
|
||||
}
|
||||
// async sendFriendRequest(nsa_id: string): Promise<Result<{}>> {
|
||||
// throw new Error('Not supported in ZncProxyApi');
|
||||
// }
|
||||
|
||||
async getCurrentUser() {
|
||||
const response = await this.fetch<{user: CurrentUser}>('/user');
|
||||
return {status: CoralStatus.OK as const, result: response.user, correlationId: ''};
|
||||
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 response = await this.fetch<{friendcode: FriendCodeUrl}>('/friendcode');
|
||||
return {status: CoralStatus.OK as const, result: response.friendcode, correlationId: ''};
|
||||
const result = await this.fetchProxyApi<{friendcode: FriendCodeUrl}>('friendcode');
|
||||
return createResult(result, result.friendcode);
|
||||
}
|
||||
|
||||
async getCurrentUserPermissions() {
|
||||
const user = await this.getCurrentUser();
|
||||
|
||||
return {
|
||||
status: CoralStatus.OK as const,
|
||||
result: {
|
||||
etag: user.result.etag,
|
||||
permissions: user.result.permissions,
|
||||
},
|
||||
correlationId: '',
|
||||
};
|
||||
return createResult(user, {
|
||||
etag: user.etag,
|
||||
permissions: user.permissions,
|
||||
});
|
||||
}
|
||||
|
||||
async updateCurrentUserPermissions(
|
||||
to: PresencePermissions, from: PresencePermissions, etag: string
|
||||
): Promise<CoralSuccessResponse<{}>> {
|
||||
// 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.fetchProxyApi<{token: WebServiceToken}>('webservice/' + id + '/token');
|
||||
return createResult(result, result.token);
|
||||
}
|
||||
|
||||
async getToken(token: string, user: NintendoAccountUser): Promise<PartialCoralAuthData> {
|
||||
throw new Error('Not supported in ZncProxyApi');
|
||||
}
|
||||
|
||||
async getWebServiceToken(id: string) {
|
||||
const response = await this.fetch<{token: WebServiceToken}>('/webservice/' + id + '/token');
|
||||
return {status: CoralStatus.OK as const, result: response.token, correlationId: ''};
|
||||
}
|
||||
|
||||
async getToken(token: string, user: NintendoAccountUser): ReturnType<CoralApi['getToken']> {
|
||||
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;
|
||||
}
|
||||
|
||||
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};
|
||||
}
|
||||
}
|
||||
|
||||
function createResult<T extends {}, R>(data: R & {[ResponseSymbol]: Response}, result: T): Result<T> {
|
||||
const coral_result: CoralSuccessResponse<T> = {
|
||||
status: CoralStatus.OK as const,
|
||||
result,
|
||||
correlationId: '',
|
||||
};
|
||||
|
||||
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: ''});
|
||||
|
||||
Object.defineProperty(result, 'status', {enumerable: false, value: CoralStatus.OK});
|
||||
Object.defineProperty(result, 'result', {enumerable: false, value: result});
|
||||
Object.defineProperty(result, 'correlationId', {enumerable: false, value: ''});
|
||||
|
||||
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;
|
||||
|
||||
|
|
@ -191,12 +311,13 @@ export enum ZncPresenceEventStreamEvent {
|
|||
}
|
||||
|
||||
export type PresenceUrlResponse =
|
||||
Presence | {presence: Presence} |
|
||||
PresenceOnline | PresenceOnline_4 | PresenceOffline |
|
||||
{presence: PresenceOnline | PresenceOnline_4 | PresenceOffline} |
|
||||
CurrentUser | {user: CurrentUser} |
|
||||
Friend | {friend: Friend};
|
||||
|
||||
export async function getPresenceFromUrl(presence_url: string, useragent?: string) {
|
||||
const [signal, cancel] = timeoutSignal();
|
||||
const [signal, cancel, controller] = timeoutSignal();
|
||||
const response = await fetch(presence_url, {
|
||||
headers: {
|
||||
'User-Agent': getUserAgent(useragent),
|
||||
|
|
@ -207,17 +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(;|$)$/)) {
|
||||
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 :
|
||||
|
|
@ -227,5 +353,5 @@ export async function getPresenceFromUrl(presence_url: string, useragent?: strin
|
|||
throw new Error('Invalid presence data');
|
||||
}
|
||||
|
||||
return [presence, user] as const;
|
||||
return defineResponse([presence, user, data as unknown] as const, response);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ Electron app
|
|||
|
||||
The Electron app is bundled into ~4 files in `dist/app/bundle` using Rollup. The main process code is not bundled for development, but is when packaging the app at `dist/bundle` (with the command line executable at `dist/bundle/cli-bundle.js`).
|
||||
|
||||
[electron.ts](electron.ts) exports all Electron APIs used in the main process. This is because the `electron` module doesn't actually exist - Electron patches the `require` function (but not the module importer). Additionally Electron does not support using a standard JavaScript module as the app entrypoint, so [main/app-entry.cts](main/app-entry.cts) (a CommonJS module) is used to import the actual app entrypoint after the `ready` event.
|
||||
[electron.ts](electron.ts) exports all Electron APIs used in the main process. This is because the `electron` module doesn't actually exist - Electron patches the `require` function (but not the module importer). Additionally Electron does not support using a standard JavaScript module as the app entrypoint, so [app-entry.cts](app-entry.cts) (a CommonJS module) is used to import the actual app entrypoint after the `ready` event.
|
||||
|
||||
Electron APIs used in renderer processes should be imported directly from the `electron` module as they are always bundled into a CommonJS module.
|
||||
|
||||
|
|
|
|||
16
src/app/app-entry.cts
Normal file
16
src/app/app-entry.cts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
const electron = require('electron');
|
||||
|
||||
// Do anything that must be run before the app is ready...
|
||||
|
||||
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))
|
||||
.catch(err => {
|
||||
electron.dialog.showErrorBox('Error during startup', err?.stack ?? err?.message ?? err);
|
||||
process.exit(1);
|
||||
});
|
||||
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'));
|
||||
151
src/app/browser/add-account-manual/index.tsx
Normal file
151
src/app/browser/add-account-manual/index.tsx
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
import React, { useCallback, useState } from 'react';
|
||||
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, useAccentColour, useColourScheme, useEventListener } from '../util.js';
|
||||
|
||||
export interface AddAccountManualPromptProps {
|
||||
authoriseurl: string;
|
||||
client_id: string;
|
||||
}
|
||||
|
||||
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) {
|
||||
props.save?.call(null, callback_url);
|
||||
}
|
||||
}, [props.save, callback_url, callback_url_valid]);
|
||||
|
||||
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={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>
|
||||
{callback_url_valid ? <View style={styles.button}>
|
||||
<Button title={t('save')}
|
||||
onPress={save}
|
||||
primary
|
||||
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
|
||||
</View> : null}
|
||||
</View>
|
||||
</View>;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
loading: {
|
||||
flex: 1,
|
||||
paddingVertical: 50,
|
||||
paddingHorizontal: 20,
|
||||
justifyContent: 'center',
|
||||
},
|
||||
|
||||
main: {
|
||||
flex: 1,
|
||||
paddingVertical: 20,
|
||||
paddingHorizontal: 20,
|
||||
},
|
||||
|
||||
header: {
|
||||
marginTop: 12,
|
||||
},
|
||||
help: {
|
||||
marginTop: 8,
|
||||
fontSize: 13,
|
||||
opacity: 0.7,
|
||||
},
|
||||
|
||||
textInput: {
|
||||
marginTop: 8,
|
||||
paddingVertical: 5,
|
||||
paddingHorizontal: 10,
|
||||
borderRadius: 3,
|
||||
fontSize: 13,
|
||||
},
|
||||
|
||||
buttons: {
|
||||
marginTop: 20,
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'flex-end',
|
||||
},
|
||||
button: {
|
||||
marginLeft: 10,
|
||||
},
|
||||
buttonSingle: {
|
||||
marginTop: 10,
|
||||
marginRight: 10,
|
||||
flexDirection: 'row',
|
||||
},
|
||||
});
|
||||
|
||||
const light = StyleSheet.create({
|
||||
text: {
|
||||
color: TEXT_COLOUR_LIGHT,
|
||||
},
|
||||
picker: {
|
||||
backgroundColor: HIGHLIGHT_COLOUR_LIGHT,
|
||||
color: TEXT_COLOUR_LIGHT,
|
||||
},
|
||||
textInput: {
|
||||
backgroundColor: HIGHLIGHT_COLOUR_LIGHT,
|
||||
color: TEXT_COLOUR_LIGHT,
|
||||
},
|
||||
});
|
||||
|
||||
const dark = StyleSheet.create({
|
||||
text: {
|
||||
color: TEXT_COLOUR_DARK,
|
||||
},
|
||||
picker: {
|
||||
backgroundColor: HIGHLIGHT_COLOUR_DARK,
|
||||
color: TEXT_COLOUR_DARK,
|
||||
},
|
||||
textInput: {
|
||||
backgroundColor: HIGHLIGHT_COLOUR_DARK,
|
||||
color: TEXT_COLOUR_DARK,
|
||||
},
|
||||
});
|
||||
|
|
@ -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,14 +1,18 @@
|
|||
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[];
|
||||
friend_nsa_id?: string;
|
||||
/** @default true */
|
||||
show_preferences_button?: boolean;
|
||||
}
|
||||
|
||||
enum DiscordSourceType {
|
||||
|
|
@ -17,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 ||
|
||||
|
|
@ -57,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);
|
||||
|
|
@ -85,94 +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}
|
||||
|
||||
<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>
|
||||
{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={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({
|
||||
|
|
@ -222,6 +251,12 @@ const styles = StyleSheet.create({
|
|||
button: {
|
||||
marginLeft: 10,
|
||||
},
|
||||
buttonPreferences: {
|
||||
marginTop: 10,
|
||||
marginLeft: 0,
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'flex-start',
|
||||
},
|
||||
});
|
||||
|
||||
const light = 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>;
|
||||
|
|
|
|||
|
|
@ -4,11 +4,15 @@ import App from './main/index.js';
|
|||
import Friend from './friend/index.js';
|
||||
import DiscordSetup from './discord/index.js';
|
||||
import AddFriend from './add-friend/index.js';
|
||||
import Preferences from './preferences/index.js';
|
||||
import AddAccountManualPrompt from './add-account-manual/index.js';
|
||||
|
||||
AppRegistry.registerComponent('App', () => App);
|
||||
AppRegistry.registerComponent('Friend', () => Friend);
|
||||
AppRegistry.registerComponent('DiscordPresence', () => DiscordSetup);
|
||||
AppRegistry.registerComponent('AddFriend', () => AddFriend);
|
||||
AppRegistry.registerComponent('Preferences', () => Preferences);
|
||||
AppRegistry.registerComponent('AddAccountManualPrompt', () => AddAccountManualPrompt);
|
||||
|
||||
const style = window.document.createElement('style');
|
||||
|
||||
|
|
|
|||
|
|
@ -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 { DiscordPresence } from '../../../discord/util.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} />)}
|
||||
|
|
|
|||
440
src/app/browser/preferences/index.tsx
Normal file
440
src/app/browser/preferences/index.tsx
Normal file
|
|
@ -0,0 +1,440 @@
|
|||
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, useAccentColour, useAsync, useColourScheme, useDiscordPresenceSource, useEventListener } from '../util.js';
|
||||
|
||||
export interface PreferencesProps {}
|
||||
|
||||
export default function PreferencesWindow(props: PreferencesProps) {
|
||||
return <Root
|
||||
title={i18n => i18n.t('preferences_window:title')} scrollable autoresize
|
||||
i18nNamespace="preferences_window"
|
||||
>
|
||||
<Preferences />
|
||||
</Root>;
|
||||
}
|
||||
|
||||
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();
|
||||
}, [ipc, login_item]);
|
||||
const setOpenAsHidden = useCallback(async (open_as_hidden: boolean | 'mixed') => {
|
||||
await ipc.setLoginItemSettings({...login_item!, startup_hidden: !!open_as_hidden});
|
||||
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]));
|
||||
|
||||
const [discord_options, , discord_options_state, forceRefreshDiscordOptions] =
|
||||
useAsync(useCallback(() => ipc.getSavedDiscordPresenceOptions(), [ipc]));
|
||||
const [has_ever_loaded_discord_options, setHasLoadedDiscordOptions] = useReducer(() => true, false);
|
||||
useEffect(() => (discord_options_state === RequestState.LOADED && setHasLoadedDiscordOptions(), undefined));
|
||||
|
||||
const [discord_friend_code, setDiscordFriendCodeValue] = useState(discord_options?.friend_code ?? '');
|
||||
const discord_friend_code_valid = !discord_friend_code || discord_friend_code.match(/^\d{4}-\d{4}-\d{4}$/);
|
||||
|
||||
useEffect(() => {
|
||||
setDiscordFriendCodeValue(discord_options?.friend_code ?? '');
|
||||
}, [discord_options]);
|
||||
|
||||
const setDiscordUser = useCallback(async (user: string | undefined) => {
|
||||
if (user === '*') user = undefined;
|
||||
await ipc.setDiscordPresenceOptions({...discord_options, user});
|
||||
forceRefreshDiscordOptions();
|
||||
}, [ipc, discord_options]);
|
||||
const setDiscordFriendCode = useCallback(async (friend_code: string | undefined) => {
|
||||
setDiscordFriendCodeValue(friend_code ?? '');
|
||||
if (friend_code && !friend_code.match(/^\d{4}-\d{4}-\d{4}$/)) return;
|
||||
if (!friend_code) friend_code = undefined;
|
||||
await ipc.setDiscordPresenceOptions({...discord_options, friend_code});
|
||||
forceRefreshDiscordOptions();
|
||||
}, [ipc, discord_options]);
|
||||
const setDiscordShowConsoleOnline = useCallback(async (show_console_online: boolean | 'mixed') => {
|
||||
await ipc.setDiscordPresenceOptions({...discord_options, show_console_online: !!show_console_online});
|
||||
forceRefreshDiscordOptions();
|
||||
}, [ipc, discord_options]);
|
||||
const setDiscordShowPlayTime = useCallback(async (show_play_time: DiscordPresencePlayTime) => {
|
||||
await ipc.setDiscordPresenceOptions({...discord_options, show_play_time});
|
||||
forceRefreshDiscordOptions();
|
||||
}, [ipc, discord_options]);
|
||||
const setDiscordEnableSplatNet3Monitor = useCallback(async (enable_splatnet3_monitoring: boolean | 'mixed') => {
|
||||
await ipc.setDiscordPresenceOptions({...discord_options, monitors: {...discord_options?.monitors,
|
||||
enable_splatnet3_monitoring: !!enable_splatnet3_monitoring}});
|
||||
forceRefreshDiscordOptions();
|
||||
}, [ipc, discord_options]);
|
||||
|
||||
const [discord_presence_source, discord_presence_source_state] = useDiscordPresenceSource();
|
||||
|
||||
const discord_presence_source_user = discord_presence_source && 'na_id' in discord_presence_source ?
|
||||
discord_presence_source.friend_nsa_id ?
|
||||
users?.find(u => u.nso?.nsoAccount.user.nsaId === discord_presence_source.friend_nsa_id)?.nso :
|
||||
users?.find(u => u.nso?.user.id === discord_presence_source.na_id)?.nso :
|
||||
null;
|
||||
|
||||
const discord_friend_code_self = discord_presence_source_user?.nsoAccount.user.links.friendCode.id;
|
||||
const [is_discord_friend_code_self, setIsDiscordFriendCodeSelf] = useState(false);
|
||||
useEffect(() => {
|
||||
setIsDiscordFriendCodeSelf(!!discord_friend_code_self &&
|
||||
(!discord_friend_code || discord_friend_code === discord_friend_code_self));
|
||||
}, [discord_presence_source, discord_friend_code_self]);
|
||||
|
||||
useEventListener(events, 'window:refresh', () => (
|
||||
forceRefreshAccounts(), forceRefreshLoginItem(),
|
||||
forceRefreshDiscordUsers(), forceRefreshDiscordOptions(),
|
||||
forceRefreshErrorAlerts()
|
||||
), []);
|
||||
|
||||
if (!users ||
|
||||
!login_item ||
|
||||
!has_ever_loaded_discord_options ||
|
||||
discord_presence_source_state !== RequestState.LOADED ||
|
||||
!ready
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
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 && user.discriminator !== '0' ? '#' + user.discriminator : '')}
|
||||
value={user.id} />);
|
||||
}
|
||||
|
||||
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]}>{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.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={!!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}>{t('discord.friend_code_self')}</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>
|
||||
<Text style={[styles.help, theme.text]}>{t('discord.inactive_presence_help')}</Text>
|
||||
|
||||
<Text style={[styles.header, theme.text]}>{t('discord.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={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>
|
||||
|
||||
<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,
|
||||
paddingVertical: 50,
|
||||
paddingHorizontal: 20,
|
||||
justifyContent: 'center',
|
||||
},
|
||||
|
||||
main: {
|
||||
flex: 1,
|
||||
paddingVertical: 20,
|
||||
paddingHorizontal: 35,
|
||||
},
|
||||
|
||||
section: {
|
||||
marginBottom: 15,
|
||||
flexDirection: 'row',
|
||||
},
|
||||
sectionLeft: {
|
||||
width: '30%',
|
||||
marginRight: 30,
|
||||
},
|
||||
label: {
|
||||
textAlign: 'right',
|
||||
},
|
||||
sectionRight: {
|
||||
flex: 1,
|
||||
},
|
||||
|
||||
header: {
|
||||
marginTop: 12,
|
||||
},
|
||||
help: {
|
||||
marginTop: 8,
|
||||
fontSize: 13,
|
||||
opacity: 0.7,
|
||||
},
|
||||
|
||||
textLinkTouchable: {
|
||||
marginBottom: 8,
|
||||
},
|
||||
textLink: {
|
||||
fontSize: 13,
|
||||
opacity: 0.85,
|
||||
},
|
||||
|
||||
picker: {
|
||||
marginTop: 8,
|
||||
paddingVertical: 4,
|
||||
paddingHorizontal: 8,
|
||||
borderWidth: 0,
|
||||
borderRadius: 3,
|
||||
fontSize: 13,
|
||||
},
|
||||
textInput: {
|
||||
marginTop: 8,
|
||||
paddingVertical: 5,
|
||||
paddingHorizontal: 10,
|
||||
borderRadius: 3,
|
||||
fontSize: 13,
|
||||
},
|
||||
checkboxContainer: {
|
||||
marginBottom: 8,
|
||||
flex: 1,
|
||||
flexBasis: 'auto',
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
},
|
||||
checkboxContainerMargin: {
|
||||
marginTop: 8,
|
||||
marginBottom: 0,
|
||||
},
|
||||
checkbox: {
|
||||
marginRight: 10,
|
||||
},
|
||||
checkboxLabel: {
|
||||
flex: 1,
|
||||
},
|
||||
checkboxLabelText: {
|
||||
},
|
||||
disabled: {
|
||||
opacity: 0.8,
|
||||
},
|
||||
|
||||
friendCodeCheckbox: {
|
||||
marginTop: 8,
|
||||
},
|
||||
friendCodeInput: {
|
||||
marginBottom: 4,
|
||||
},
|
||||
|
||||
button: {
|
||||
marginTop: 10,
|
||||
marginRight: 10,
|
||||
flexDirection: 'row',
|
||||
},
|
||||
});
|
||||
|
||||
const light = StyleSheet.create({
|
||||
text: {
|
||||
color: TEXT_COLOUR_LIGHT,
|
||||
},
|
||||
picker: {
|
||||
backgroundColor: HIGHLIGHT_COLOUR_LIGHT,
|
||||
color: TEXT_COLOUR_LIGHT,
|
||||
},
|
||||
textInput: {
|
||||
backgroundColor: HIGHLIGHT_COLOUR_LIGHT,
|
||||
color: TEXT_COLOUR_LIGHT,
|
||||
},
|
||||
});
|
||||
|
||||
const dark = StyleSheet.create({
|
||||
text: {
|
||||
color: TEXT_COLOUR_DARK,
|
||||
},
|
||||
picker: {
|
||||
backgroundColor: HIGHLIGHT_COLOUR_DARK,
|
||||
color: TEXT_COLOUR_DARK,
|
||||
},
|
||||
textInput: {
|
||||
backgroundColor: HIGHLIGHT_COLOUR_DARK,
|
||||
color: TEXT_COLOUR_DARK,
|
||||
},
|
||||
});
|
||||
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/util.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)),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,10 +1,12 @@
|
|||
import { DiscordPresencePlayTime } from '../../discord/util.js';
|
||||
import { DiscordPresencePlayTime } from '../../discord/types.js';
|
||||
|
||||
export enum WindowType {
|
||||
MAIN_WINDOW = 'App',
|
||||
FRIEND = 'Friend',
|
||||
DISCORD_PRESENCE = 'DiscordPresence',
|
||||
ADD_FRIEND = 'AddFriend',
|
||||
PREFERENCES = 'Preferences',
|
||||
ADD_ACCOUNT_MANUAL_PROMPT = 'AddAccountManualPrompt',
|
||||
}
|
||||
|
||||
interface WindowProps {
|
||||
|
|
@ -12,6 +14,8 @@ interface WindowProps {
|
|||
[WindowType.FRIEND]: import('../browser/friend/index.js').FriendProps;
|
||||
[WindowType.DISCORD_PRESENCE]: import('../browser/discord/index.js').DiscordSetupProps;
|
||||
[WindowType.ADD_FRIEND]: import('../browser/add-friend/index.js').AddFriendProps;
|
||||
[WindowType.PREFERENCES]: import('../browser/preferences/index.js').PreferencesProps;
|
||||
[WindowType.ADD_ACCOUNT_MANUAL_PROMPT]: import('../browser/add-account-manual/index.js').AddAccountManualPromptProps;
|
||||
}
|
||||
|
||||
export interface WindowConfiguration<T extends WindowType = WindowType> {
|
||||
|
|
@ -28,6 +32,7 @@ export interface DiscordPresenceConfiguration {
|
|||
show_console_online?: boolean;
|
||||
show_active_event?: boolean;
|
||||
show_play_time?: DiscordPresencePlayTime;
|
||||
monitors?: DiscordPresenceExternalMonitorsConfiguration;
|
||||
}
|
||||
|
||||
export type DiscordPresenceSource = DiscordPresenceSourceCoral | DiscordPresenceSourceUrl;
|
||||
|
|
@ -38,3 +43,18 @@ export interface DiscordPresenceSourceCoral {
|
|||
export interface DiscordPresenceSourceUrl {
|
||||
url: string;
|
||||
}
|
||||
|
||||
export interface DiscordPresenceExternalMonitorsConfiguration {
|
||||
enable_splatnet3_monitoring?: boolean;
|
||||
}
|
||||
|
||||
export interface DiscordStatus {
|
||||
error_message: string | null;
|
||||
}
|
||||
|
||||
export interface LoginItem {
|
||||
supported: boolean;
|
||||
startup_enabled: boolean;
|
||||
startup_hidden: boolean;
|
||||
}
|
||||
export type LoginItemOptions = Omit<LoginItem, 'supported'>;
|
||||
|
|
|
|||
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,8 +0,0 @@
|
|||
const electron = require('electron');
|
||||
|
||||
// Do anything that must be run before the app is ready...
|
||||
|
||||
electron.app.whenReady()
|
||||
// @ts-expect-error
|
||||
.then(() => typeof __NXAPI_BUNDLE_APP_MAIN__ !== 'undefined' ? import(__NXAPI_BUNDLE_APP_MAIN__) : import('./index.js'))
|
||||
.then(m => m.init.call(null));
|
||||
|
|
@ -1,68 +1,122 @@
|
|||
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';
|
||||
|
||||
const menu_app = new MenuItem({role: 'appMenu'});
|
||||
const menu_file = new MenuItem({role: 'fileMenu'});
|
||||
const menu_edit = new MenuItem({role: 'editMenu'});
|
||||
let appinstance: App | null;
|
||||
|
||||
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' },
|
||||
],
|
||||
});
|
||||
export function setAppInstance(app: App) {
|
||||
appinstance = app;
|
||||
}
|
||||
|
||||
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);
|
||||
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();
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
label: 'Learn More (GitHub)',
|
||||
click: async () => {
|
||||
await shell.openExternal(GITHUB_MIRROR_URL);
|
||||
},
|
||||
},
|
||||
{
|
||||
label: 'Search Issues',
|
||||
click: async () => {
|
||||
await shell.openExternal(ISSUES_URL);
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
{ type: 'separator' },
|
||||
{ role: 'services' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'hide' },
|
||||
{ role: 'hideOthers' },
|
||||
{ role: 'unhide' },
|
||||
{ type: 'separator' },
|
||||
{ role: 'quit' },
|
||||
],
|
||||
});
|
||||
|
||||
export const app_menu = Menu.buildFromTemplate([
|
||||
...(process.platform === 'darwin' ? [menu_app] : []),
|
||||
menu_file,
|
||||
menu_edit,
|
||||
menu_view,
|
||||
menu_window,
|
||||
menu_help,
|
||||
]);
|
||||
const menu_file = new MenuItem({role: 'fileMenu'});
|
||||
const menu_edit = new MenuItem({role: 'editMenu'});
|
||||
|
||||
export function createWindowMenu(window: BrowserWindow) {
|
||||
const menu_view = new MenuItem({
|
||||
label: 'View',
|
||||
const menu_window = new MenuItem({role: 'windowMenu'});
|
||||
|
||||
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();
|
||||
|
|
@ -90,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,33 +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 Menu = import('electron').Menu;
|
||||
export type MenuItem = import('electron').MenuItem;
|
||||
export type MessageBoxOptions = import('electron').MessageBoxOptions;
|
||||
export type Notification = import('electron').Notification;
|
||||
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,33 +1,78 @@
|
|||
import { app, BrowserWindow, dialog, ipcMain } 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 dotenv from 'dotenv';
|
||||
import dotenvExpand from 'dotenv-expand';
|
||||
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 { DiscordPresenceConfiguration, WindowType } from '../common/types.js';
|
||||
import { initStorage, paths } from '../../util/storage.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 { 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 { dev, dir } from '../../util/product.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 { 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');
|
||||
|
||||
export const protocol_registration_options = dev && process.platform === 'win32' ? {
|
||||
path: process.execPath,
|
||||
argv: [
|
||||
path.join(dir, 'dist', 'app', 'app-entry.cjs'),
|
||||
],
|
||||
} : null;
|
||||
export const login_item_options: Settings = {
|
||||
path: process.execPath,
|
||||
args: dev ? [
|
||||
path.join(dir, 'dist', 'app', 'app-entry.cjs'),
|
||||
'--app-open-at-login=1',
|
||||
] : [
|
||||
'--app-open-at-login=1',
|
||||
],
|
||||
};
|
||||
|
||||
enum LoginItemType {
|
||||
NATIVE,
|
||||
NATIVE_PARTIAL,
|
||||
NOT_SUPPORTED,
|
||||
}
|
||||
const login_item_type: LoginItemType =
|
||||
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);
|
||||
|
||||
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);
|
||||
}
|
||||
|
|
@ -58,6 +103,65 @@ export class App {
|
|||
|
||||
return this.main_window = window;
|
||||
}
|
||||
|
||||
preferences_window: BrowserWindow | null = null;
|
||||
|
||||
showPreferencesWindow() {
|
||||
if (this.preferences_window) {
|
||||
this.preferences_window.show();
|
||||
this.preferences_window.focus();
|
||||
return this.preferences_window;
|
||||
}
|
||||
|
||||
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() {
|
||||
|
|
@ -68,30 +172,67 @@ export async function init() {
|
|||
return;
|
||||
}
|
||||
|
||||
dotenvExpand.expand(dotenv.config({
|
||||
path: path.join(paths.data, '.env'),
|
||||
}));
|
||||
if (process.env.NXAPI_DATA_PATH) dotenvExpand.expand(dotenv.config({
|
||||
path: path.join(process.env.NXAPI_DATA_PATH, '.env'),
|
||||
}));
|
||||
|
||||
if (process.env.DEBUG) createDebug.enable(process.env.DEBUG);
|
||||
|
||||
initGlobals();
|
||||
addUserAgent('nxapi-app (Chromium ' + process.versions.chrome + '; Electron ' + process.versions.electron + ')');
|
||||
|
||||
const storage = await initStorage(process.env.NXAPI_DATA_PATH ?? paths.data);
|
||||
const appinstance = new App(storage);
|
||||
if (NXAPI_AUTH_APP_CLIENT_ID) {
|
||||
setClientAssertionProvider(new ClientAssertionProvider(NXAPI_AUTH_APP_CLIENT_ID, undefined,
|
||||
NXAPI_AUTH_APP_SCOPE));
|
||||
}
|
||||
|
||||
setupIpc(appinstance, ipcMain);
|
||||
setAboutPanelOptions();
|
||||
|
||||
const agent = buildElectronProxyAgent({
|
||||
session: session.defaultSession,
|
||||
});
|
||||
setGlobalDispatcher(agent);
|
||||
|
||||
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);
|
||||
|
||||
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);
|
||||
|
||||
|
|
@ -103,20 +244,19 @@ export async function init() {
|
|||
app.on('open-url', (event, url) => {
|
||||
debug('Open URL', url);
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
if (!tryHandleUrl(appinstance, url)) {
|
||||
appinstance.showMainWindow();
|
||||
}
|
||||
});
|
||||
|
||||
if (dev && process.platform === 'win32') {
|
||||
app.setAsDefaultProtocolClient('com.nintendo.znca', process.execPath, [
|
||||
path.join(dir, 'dist', 'app', 'main', 'app-entry.cjs'),
|
||||
]);
|
||||
} else {
|
||||
app.setAsDefaultProtocolClient('com.nintendo.znca');
|
||||
}
|
||||
app.setAsDefaultProtocolClient('com.nintendo.znca',
|
||||
protocol_registration_options?.path, protocol_registration_options?.argv);
|
||||
|
||||
app.on('activate', (event, has_visible_windows) => {
|
||||
debug('activate', has_visible_windows);
|
||||
|
||||
app.on('activate', () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) appinstance.showMainWindow();
|
||||
});
|
||||
|
||||
|
|
@ -136,49 +276,111 @@ export async function init() {
|
|||
|
||||
debug('App started');
|
||||
|
||||
appinstance.showMainWindow();
|
||||
const should_hide =
|
||||
login_item_type === LoginItemType.NATIVE ? app.getLoginItemSettings(login_item_options).wasOpenedAsHidden :
|
||||
was_opened_at_login && (await appinstance.store.getLoginItem()).startup_hidden;
|
||||
|
||||
if (!should_hide) {
|
||||
appinstance.showMainWindow();
|
||||
}
|
||||
}
|
||||
|
||||
function tryHandleUrl(app: App, url: string) {
|
||||
debug('Attempting to handle URL', url);
|
||||
|
||||
if (url.match(/^npf[0-9a-f]{16}:\/\/auth\/?($|\?|\#)/i)) {
|
||||
handleAuthUri(url);
|
||||
return true;
|
||||
}
|
||||
|
||||
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;
|
||||
|
|
@ -197,6 +399,10 @@ class Updater {
|
|||
}
|
||||
}
|
||||
|
||||
interface SavedStartupOptions {
|
||||
hide: boolean;
|
||||
}
|
||||
|
||||
interface SavedMonitorState {
|
||||
users: {
|
||||
/** Nintendo Account ID */
|
||||
|
|
@ -208,7 +414,7 @@ interface SavedMonitorState {
|
|||
}
|
||||
|
||||
export class Store extends EventEmitter {
|
||||
readonly users: Users<CoralUser>;
|
||||
readonly users: Users<CoralUser<CoralApiInterface>>;
|
||||
|
||||
constructor(
|
||||
readonly app: App,
|
||||
|
|
@ -217,7 +423,89 @@ export class Store extends EventEmitter {
|
|||
super();
|
||||
|
||||
// ratelimit = false, as most users.get calls are triggered by user interaction (or at startup)
|
||||
this.users = Users.coral(storage, process.env.ZNC_PROXY_URL, false);
|
||||
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> {
|
||||
const settings = app.getLoginItemSettings(login_item_options);
|
||||
|
||||
if (login_item_type === LoginItemType.NATIVE) {
|
||||
// Fully supported
|
||||
return {
|
||||
supported: true,
|
||||
startup_enabled: settings.openAtLogin,
|
||||
startup_hidden: settings.openAsHidden,
|
||||
};
|
||||
}
|
||||
|
||||
const startup_options: SavedStartupOptions | undefined = await this.storage.getItem('StartupOptions');
|
||||
|
||||
if (login_item_type === LoginItemType.NATIVE_PARTIAL) {
|
||||
// Partial native support
|
||||
return {
|
||||
supported: true,
|
||||
startup_enabled: settings.openAtLogin,
|
||||
startup_hidden: startup_options?.hide ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
supported: false,
|
||||
startup_enabled: was_opened_at_login,
|
||||
startup_hidden: startup_options?.hide ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
async setLoginItem(settings: LoginItemOptions) {
|
||||
if (login_item_type === LoginItemType.NATIVE) {
|
||||
// Fully supported
|
||||
app.setLoginItemSettings({
|
||||
...login_item_options,
|
||||
openAtLogin: settings.startup_enabled,
|
||||
openAsHidden: settings.startup_hidden,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (login_item_type === LoginItemType.NATIVE_PARTIAL) {
|
||||
// Partial native support
|
||||
app.setLoginItemSettings({
|
||||
...login_item_options,
|
||||
openAtLogin: settings.startup_enabled,
|
||||
});
|
||||
}
|
||||
|
||||
const startup_options: SavedStartupOptions = {
|
||||
hide: settings.startup_hidden,
|
||||
};
|
||||
|
||||
await this.storage.setItem('StartupOptions', startup_options);
|
||||
}
|
||||
|
||||
async saveMonitorState(monitors: PresenceMonitorManager) {
|
||||
|
|
@ -228,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,
|
||||
});
|
||||
|
|
@ -243,6 +531,20 @@ export class Store extends EventEmitter {
|
|||
|
||||
debug('Saving monitor state', state);
|
||||
await this.storage.setItem('AppMonitors', state);
|
||||
|
||||
if (state.discord_presence) {
|
||||
await this.storage.setItem('AppDiscordPresenceOptions', {
|
||||
...state.discord_presence,
|
||||
source: undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async getSavedDiscordPresenceOptions() {
|
||||
const options: Omit<DiscordPresenceConfiguration, 'source'> | undefined =
|
||||
await this.storage.getItem('AppDiscordPresenceOptions');
|
||||
|
||||
return options ?? null;
|
||||
}
|
||||
|
||||
async restoreMonitorState(monitors: PresenceMonitorManager) {
|
||||
|
|
@ -275,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;
|
||||
|
||||
|
|
@ -289,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,
|
||||
});
|
||||
|
|
@ -318,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,30 +1,59 @@
|
|||
import { BrowserWindow, clipboard, dialog, IpcMain, Menu, MenuItem, 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, { WebServiceIpc } from './webservices.js';
|
||||
import { createWindow, getWindowConfiguration } from './windows.js';
|
||||
import { DiscordPresenceConfiguration, DiscordPresenceSource, 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 } from './index.js';
|
||||
import { NintendoAccountUser } from '../../api/na.js';
|
||||
import { hrduration } from '../../util/misc.js';
|
||||
import { DiscordPresence } from '../../discord/util.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 { EmbeddedPresenceMonitor } from './monitor.js';
|
||||
import { AddFriendProps } from '../browser/add-friend/index.js';
|
||||
import type { AddFriendProps } from '../browser/add-friend/index.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');
|
||||
|
||||
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;
|
||||
|
||||
|
|
@ -38,139 +67,163 @@ export function setupIpc(appinstance: App, ipcMain: IpcMain) {
|
|||
sendToAllWindows('nxapi:systemPreferences:accent-colour', accent_colour);
|
||||
});
|
||||
|
||||
ipcMain.handle('nxapi:update:get', () => appinstance.updater.cache ?? appinstance.updater.check());
|
||||
ipcMain.handle('nxapi:update:check', () => appinstance.updater.check());
|
||||
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);
|
||||
|
||||
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 => dialog.showMessageBox(BrowserWindow.fromWebContents(e.sender)!, {
|
||||
type: 'error',
|
||||
title: (err instanceof Error ? err.name : 'Error') + ' opening web service',
|
||||
message: err.message,
|
||||
detail: (err instanceof Error ? err.stack ?? '' : 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}),
|
||||
}))));
|
||||
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()).then(r => r.result));
|
||||
ipcMain.handle('nxapi:coral:friendcode', (e, token: string, friendcode: string, hash?: string) => store.users.get(token).then(u => u.nso.getUserByFriendCode(friendcode, hash)).then(r => r.result));
|
||||
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: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)!);
|
||||
}
|
||||
|
||||
for (const error of show) {
|
||||
showErrorDialog({
|
||||
message: 'Error loading data',
|
||||
error,
|
||||
app: appinstance,
|
||||
window: BrowserWindow.fromWebContents(e.sender) ?? undefined,
|
||||
});
|
||||
}
|
||||
window.setContentSize(curContentWidth, height);
|
||||
window.show();
|
||||
});
|
||||
|
||||
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: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: () => askAddNsoAccount(storage)}),
|
||||
new MenuItem({label: 'Add Nintendo Switch Parental Controls account', click: () => askAddPctlAccount(storage)}),
|
||||
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(appinstance, !event.shiftKey)}),
|
||||
new MenuItem({label: t('add_account.add_account_moon')!, click:
|
||||
(item: MenuItem, window: BrowserWindow | undefined, event: KeyboardEvent) =>
|
||||
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));
|
||||
|
||||
|
|
@ -181,94 +234,81 @@ export function setupIpc(appinstance: App, ipcMain: IpcMain) {
|
|||
ipcMain.handle('nxapi:webserviceapi:requestGameWebToken', e => webserviceipc.requestGameWebToken(e));
|
||||
ipcMain.handle('nxapi:webserviceapi:restorePersistentData', e => webserviceipc.restorePersistentData(e));
|
||||
ipcMain.handle('nxapi:webserviceapi:storePersistentData', (e, data: string) => webserviceipc.storePersistentData(e, data));
|
||||
ipcMain.handle('nxapi:webserviceapi:openQrCodeReader', (e, data: QrCodeReaderOptions) => webserviceipc.openQrCodeReader(e, data));
|
||||
ipcMain.handle('nxapi:webserviceapi:closeQrCodeReader', e => webserviceipc.closeQrCodeReader(e));
|
||||
ipcMain.handle('nxapi:webserviceapi:sendMessage', (e, data: string) => webserviceipc.sendMessage(e, data));
|
||||
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;
|
||||
|
|
@ -276,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})}),
|
||||
]);
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user