Compare commits

..

558 Commits
v0.3.0 ... main

Author SHA1 Message Date
Ellie
28109239a3
Merge remote-tracking branch 'belladev/AccountSession-Resume' 2025-12-17 23:00:14 +00:00
Ellie
71be9c8795
Add arm64 deb/appimage packages 2025-12-17 22:57:34 +00:00
Ben Lawrence
c3506daad1
Add static resume method to NintendoAccountSessionAuthorisationCoral 2025-12-14 20:16:21 +13:00
Ellie
c5f86a718a
Fix setClientAuthentication with client ID only 2025-12-13 01:07:20 +00:00
Ellie
10dbc366eb
Update CurrentUser type 2025-12-10 00:25:07 +00:00
Ellie
8cae29d035
Coral 3.2.0 2025-12-09 19:47:01 +00:00
Ellie
e993706671
Add pipeline ID to package.json 2025-10-12 01:09:50 +01:00
Ellie
373a348d65
Update authors 2025-10-12 00:02:18 +01:00
Samuel Elliott
41f6182dc2
Use emulated open as hidden for macOS 13
https://github.com/samuelthomas2774/nxapi/issues/154
2025-10-02 21:24:16 +01:00
Samuel Elliott
fbaa188e13
Merge branch 'disable-error-alerts' 2025-09-17 17:35:27 +01:00
Samuel Elliott
abf6fa9ca9
Coral 3.1.0 2025-09-17 17:34:39 +01:00
Samuel Elliott
2de9ce365f
Increase nxapi-auth assertion validity 2025-09-08 02:20:33 +01:00
Samuel Elliott
d5723f9ea7
Update README.md 2025-09-08 02:16:55 +01:00
Samuel Elliott
7569d44ca9
Remove nxapi-auth client identifiers from source 2025-09-08 02:03:41 +01:00
Samuel Elliott
8b9b0cbe80
Add missing tweetnacl dependency 2025-09-08 01:45:18 +01:00
Samuel Elliott
8e1f9bde1b
Add presence server user hint header 2025-09-08 01:45:02 +01:00
Samuel Elliott
a53721f27c
Add nxapi-auth client identifiers in CI 2025-09-01 02:15:04 +01:00
Samuel Elliott
a281729a18
Add methods for setting nxapi-auth client authentication 2025-09-01 02:06:50 +01:00
Samuel Elliott
c021f20ef6
Fix checking session token expiry 2025-09-01 02:02:44 +01:00
Samuel Elliott
b683dca8b4
Add command to fetch Splatoon 3 seed data 2025-08-19 20:15:36 +01:00
Samuel Elliott
aecf9556ef
Show full version number 2025-08-19 19:49:43 +01:00
Samuel Elliott
07691de7b5
Fix user icons for new accounts 2025-08-17 22:43:07 +01:00
Samuel Elliott
7a2fe3d35c
Use show error alerts preference for SplatNet 3 presence monitoring 2025-08-17 21:41:11 +01:00
Samuel Elliott
05b254e69c
Update help text 2025-08-17 20:55:26 +01:00
Samuel Elliott
f59caa3d6f
Increase update interval after errors 2025-08-17 20:52:04 +01:00
Samuel Elliott
2e26ea2725
Merge remote-tracking branch 'belladev/disable-error-alerts' into disable-error-alerts 2025-08-17 20:20:24 +01:00
Samuel Elliott
5ba004f9ab
Add commands to fetch tokens for splatnet2statink, s3s and s3si.ts 2025-08-17 13:06:30 +01:00
Samuel Elliott
34e399932a
Update README.md 2025-08-05 20:58:18 +01:00
Samuel Elliott
af44a2cc7a
Update issue templates 2025-08-05 20:41:03 +01:00
Samuel Elliott
ec202d1ff8
Remove activity name option, remove newer Discord clients that may not have full title name set properly 2025-08-05 19:05:29 +01:00
Samuel Elliott
73feb930ac
Fix title ID validation 2025-08-05 15:53:07 +01:00
Samuel Elliott
ff777a06ab
Update Discord titles 2025-08-05 15:44:30 +01:00
Samuel Elliott
be21d69a4c
Show title name (details) under name in Discord 2025-08-05 15:43:53 +01:00
Samuel Elliott
56086c0651
Fix type error 2025-08-01 22:44:25 +01:00
Samuel Elliott
d3e3ecd280
Fix unable to fetch web service tokens in app 2025-08-01 22:41:31 +01:00
Samuel Elliott
116bae844a
Show platform in app 2025-08-01 22:30:27 +01:00
Samuel Elliott
d00c988220
Update approximate play time, date format in Discord activities 2025-08-01 21:51:09 +01:00
Samuel Elliott
2ddac1619f
Fix unable to fetch web service tokens in app 2025-08-01 21:29:04 +01:00
Samuel Elliott
3bfee7559f
Allow requesting multiple presence server users 2025-07-31 23:16:08 +01:00
Samuel Elliott
426f97ff6d
Add presence server --splatnet3-user option 2025-07-31 23:09:10 +01:00
Samuel Elliott
fd08c4ddde
Use large user icons 2025-07-31 23:04:46 +01:00
Samuel Elliott
b6490f9639
Add nxapi nxapi-auth link-url command 2025-07-29 01:57:34 +01:00
Samuel Elliott
64b6a663e5
Fix nxapi nso play-activity --json 2025-07-29 00:40:38 +01:00
Samuel Elliott
f7084107c6
Add nxapi nxapi-auth link-url command, API proxy client 2025-07-29 00:07:34 +01:00
Samuel Elliott
c809722ca8
Fix API proxy client call response type 2025-07-28 02:12:00 +01:00
Samuel Elliott
3657da89b6
Fix API proxy client request content type 2025-07-28 02:00:41 +01:00
Samuel Elliott
3cd774b299
Fix API proxy client 2025-07-28 01:21:54 +01:00
Samuel Elliott
8d5981c8f7
Add ZncProxyApi.getFriend 2025-07-27 21:57:38 +01:00
Samuel Elliott
4897aca3e6
Add updating isNew (CoralApi.deleteFriendIsNew) and isOnlineNotificationEnabled (CoralApi.updateFriendOnlineNotificationSettings) to API proxy 2025-07-27 21:53:33 +01:00
Samuel Elliott
ddaa7a5ba0
Add CoralApi.deleteFriendIsNew 2025-07-27 21:32:00 +01:00
Samuel Elliott
3746f76812
Add presence server user parameter 2025-07-27 21:31:37 +01:00
Samuel Elliott
080d110d1f
Fix renewing nxapi-auth token 2025-07-27 17:10:47 +01:00
Samuel Elliott
00ab5fc623
Coral 3.0.1 web service JS APIs 2025-07-25 23:50:08 +01:00
Samuel Elliott
8492db43d9
Update third-party API usage text 2025-07-25 21:10:34 +01:00
Samuel Elliott
706e41133d
Improve showing errors from main window 2025-07-25 21:07:34 +01:00
Samuel Elliott
e9137a41c6
Add received/sent friend requests to API proxy 2025-07-25 19:33:45 +01:00
Samuel Elliott
cd96ed7960
Fetch friend requests for the add friend window 2025-07-25 19:27:49 +01:00
Samuel Elliott
0f0f666ea6
Hide refresh_token/client_secret/naIdToken fields in logs, ignore Cloudflare HTML errors 2025-07-25 19:05:36 +01:00
Samuel Elliott
4452947187
Presence monitoring 2025-07-25 18:00:32 +01:00
Samuel Elliott
eb778f0c8e
Return response decryption data 2025-07-25 02:16:11 +01:00
Samuel Elliott
748f058d10
Fix SentFriendRequests type 2025-07-25 01:49:20 +01:00
Samuel Elliott
78b5d6748e
Coral 3.0.3 2025-07-24 00:58:46 +01:00
Samuel Elliott
b92dc5e310
Coral 3.0.3 2025-07-24 00:25:40 +01:00
Samuel Elliott
fa82661911
Show platform for inactive presence 2025-07-24 00:22:12 +01:00
Samuel Elliott
9561a9523e
Limit retrying f/encrypt requests on invalid_token 2025-07-24 00:09:44 +01:00
Samuel Elliott
9cb122c365
Show platform if not using a specific Discord client 2025-07-24 00:08:56 +01:00
Samuel Elliott
b63526e13c
Coral 3.0.3 2025-07-23 01:03:26 +01:00
Samuel Elliott
9339eb73fc
f-generation/request encryption API, allow only client ID, add nxapi-cli/app client authentication 2025-07-22 17:14:41 +01:00
Samuel Elliott
e1e2a2223e
f-generation/request encryption API 2025-07-22 03:44:29 +01:00
Samuel Elliott
4889b0d93e
f-generation/request encryption API 2025-07-22 03:27:20 +01:00
Samuel Elliott
e6c97f2924
Coral 3.0.3 2025-07-22 02:10:24 +01:00
Samuel Elliott
e55b8dc965
Update types 2025-07-22 02:10:00 +01:00
Samuel Elliott
8cac7935f2
Coral 3.0.3 2025-07-22 01:37:37 +01:00
Samuel Elliott
e00a0a6e3b
Send client compatibility version to remote config API 2025-07-22 01:37:01 +01:00
Samuel Elliott
57ce3c21de
Coral 3.0.3 2025-07-22 01:33:03 +01:00
Samuel Elliott
2959c923bb
Update coral types 2025-07-22 01:02:41 +01:00
Samuel Elliott
d482987231
Update coral types 2025-06-26 15:39:04 +01:00
Samuel Elliott
4888544f11
Add status update source 2025-04-20 21:20:54 +01:00
Samuel Elliott
059799164d
Add status update source 2025-04-20 20:55:02 +01:00
Samuel Elliott
90b520c444
Update coral types 2025-04-20 20:42:33 +01:00
Samuel Elliott
9985e32d0b
Add status update banners 2025-04-20 20:41:05 +01:00
Samuel Elliott
7666191600
Add separate Discord client for Nintendo Switch/Nintendo Switch 2 2025-04-20 20:25:48 +01:00
Samuel Elliott
8a05e4c6ef
Update dependencies 2025-04-20 20:20:10 +01:00
Bella Lawrence
8e30643bc8
Add error alert preferences and related IPC handlers 2025-04-19 22:37:19 +12:00
Samuel Elliott
a02d2f5553
Update coral types 2025-04-04 17:40:55 +01:00
Samuel Elliott
018b3b121f
Fix string_decoder import 2025-04-02 21:48:43 +01:00
Samuel Elliott
dd73e31df5
Fix presence server Splatoon 3 data 2025-04-02 18:57:43 +01:00
Samuel Elliott
cdf175a3bd
Fix presence server Splatoon 3 data 2025-04-02 18:38:14 +01:00
Samuel Elliott
93f0c56340
Update issue templates 2025-04-02 02:33:58 +01:00
Samuel Elliott
17e61eada5
Update issue templates 2025-04-02 02:28:33 +01:00
Samuel Elliott
bde495fcce
Add command/menu item to export log files 2025-04-02 00:34:00 +01:00
Samuel Elliott
83456275fb
Use NO_PROXY environment variable, never proxy Docker container names 2025-04-01 21:24:59 +01:00
Samuel Elliott
6f989104c7
Update coral types 2025-04-01 21:20:24 +01:00
Samuel Elliott
8c911d5bca
Coral 2.12.0 2025-03-29 00:49:00 +00:00
Samuel Elliott
859ecea027
Remove auto refresh option 2024-11-02 14:09:35 +00:00
Samuel Elliott
589a5ea220
Fix add friend window title 2024-10-16 17:49:55 +01:00
Samuel Elliott
88068dcf89
Remove old files 2024-10-16 17:49:45 +01:00
Samuel Elliott
02faac2782
Fix type errors 2024-10-16 00:18:24 +01:00
Samuel Elliott
445093e58a
Import sharp when used 2024-10-15 23:57:17 +01:00
Samuel Elliott
c966b7309e
Fix dependencies 2024-10-15 23:56:56 +01:00
Samuel Elliott
c3a53a7cfa
Merge branch 'pull/63' into i18n 2024-10-15 23:37:45 +01:00
Samuel Elliott
6d225b6552
Fix dependencies 2024-10-15 23:36:09 +01:00
Samuel Elliott
8276b70de7
Merge branch 'main' into i18n
# Conflicts:
#	package-lock.json
#	package.json
#	src/app/browser/main/discord-setup.tsx
#	src/app/browser/main/discord.tsx
#	src/app/main/app-menu.ts
#	src/app/main/index.ts
#	src/app/main/ipc.ts
#	src/app/main/menu.ts
#	src/app/main/monitor.ts
#	src/app/main/na-auth.ts
#	src/app/main/util.ts
#	src/app/main/webservices.ts
#	src/app/main/windows.ts
2024-10-15 23:31:28 +01:00
Samuel Elliott
bd908c130e
Merge remote-tracking branch 'github/pull/127' 2024-10-15 23:05:07 +01:00
Ludovico Gardenghi
f5773419e9 Fix typo COMPUTING -> CALCULATING. 2024-10-08 11:52:47 +02:00
Ludovico Gardenghi
dfc8ad3e83 Only set the dump timestamp for the current day.
Past days are either ACHIEVED or UNACHIEVED depending on whether the
time limit has been reached. The current day is in state COMPUTING.
2024-10-08 11:26:29 +02:00
Sophie L
4df9a4f495 fix: README review comments 2024-05-22 17:22:03 +00:00
Rexogamer
a5e98e807b
fix: README grammar 2024-04-30 15:37:01 +01:00
Rexogamer
90e41c837b
chore: bump deps, cleanup deprecation warnings 2024-04-30 15:26:08 +01:00
Samuel Elliott
e3937ae843
Update .gitlab-ci.yml 2024-04-15 02:24:57 +01:00
Samuel Elliott
865f55780a
Update .gitlab-ci.yml 2024-04-15 02:17:21 +01:00
Samuel Elliott
a12fdb2878
Update .gitlab-ci.yml 2024-04-15 02:09:44 +01:00
Samuel Elliott
9a56d04ba1
Use limited access header from nxapi-auth 2024-02-21 11:56:49 +00:00
Samuel Elliott
6be0ca949a
Fix getting auth data from API proxy returns stale data 2024-02-11 21:51:34 +00:00
Samuel Elliott
3e0ba063f8
Move CLI modules 2024-01-19 19:33:49 +00:00
Samuel Elliott
ff3f8e1704
Fix presence embed with certain Splatoon 3 schedule images 2024-01-13 00:38:34 +00:00
Samuel Elliott
4b5f1898eb
Fix friend code position 2024-01-10 13:57:52 +00:00
Samuel Elliott
38db4a0b3a
Fix downloading images from web services without a file extension 2024-01-10 13:39:46 +00:00
Samuel Elliott
1ec08c02f4
Show VS/coop setting details for Splatoon 3 presence embed 2024-01-10 13:37:06 +00:00
Samuel Elliott
e697f86359
Add scale option for PNG/JPEG/WEBP presence embeds 2024-01-07 09:42:19 +00:00
Samuel Elliott
6fd0f3f2f1
Fix Splatfest team image when converting presence embed to PNG/JPEG/WEBP 2024-01-07 09:39:23 +00:00
Samuel Elliott
b5d86bf2d6
Show Splatoon 3 Splatfest team image in presence embed 2024-01-07 08:47:04 +00:00
Samuel Elliott
597d3ba554
Fix embedding presence embed images 2023-12-27 23:36:05 +00:00
Samuel Elliott
b7afcfb175
Update documentation, add width option 2023-12-27 19:29:06 +00:00
Samuel Elliott
01fdfb1fec
Change presence embed text 2023-12-27 17:54:59 +00:00
Samuel Elliott
98af75441b
Add presence server title redirect endpoint 2023-12-27 17:09:19 +00:00
Samuel Elliott
6ee7a9382a
Show Splatoon 3 mode in presence embeds 2023-12-27 16:44:51 +00:00
Samuel Elliott
cbf6e257be
Presence embeds 2023-12-27 16:40:40 +00:00
Samuel Elliott
f122ef8c92
Disable electron-builder publish 2023-11-20 00:15:20 +00:00
Samuel Elliott
64bc2be2ec
Use GitLab CI rules instead of only/except 2023-11-19 22:02:35 +00:00
Samuel Elliott
0445ab46af
Update dependencies, update Docker image to Node.js v20 2023-11-19 21:44:49 +00:00
Samuel Elliott
5ef9101c1e
Fix Splatfest Battle (Open) presence schedule 2023-11-19 21:13:56 +00:00
Samuel Elliott
6656ca97e0
Automatically upload assets to GitHub Releases 2023-11-19 20:07:53 +00:00
Samuel Elliott
0dcf1e3598
Hide exit button in tournament manager 2023-11-16 23:42:12 +00:00
Samuel Elliott
f35f2ab549
Fix web services with a whiteList including a path component
https://github.com/samuelthomas2774/nxapi/issues/92
2023-11-16 23:41:47 +00:00
Samuel Elliott
58413a0024
Update Discord titles
https://github.com/samuelthomas2774/nxapi/issues/83
https://github.com/samuelthomas2774/nxapi/issues/85
2023-10-26 22:20:34 +01:00
Samuel Elliott
c5c870fe5c
Update README.md 2023-10-26 17:16:37 +01:00
Samuel Elliott
5d26922660
Update README.md 2023-10-26 17:16:32 +01:00
Samuel Elliott
0d2ec91019
Fix detecting Splatfest/Anarchy Battle schedule 2023-10-26 16:42:27 +01:00
Samuel Elliott
f07cd5a2e7
Update embedded remote config and splatnet3-types 2023-08-30 20:19:14 +01:00
Samuel Elliott
cb3bdda283
Add new web service APIs 2023-08-30 20:18:47 +01:00
Samuel Elliott
2680b03c46
Fix checking web service allowed hosts 2023-08-21 06:18:16 +01:00
Samuel Elliott
c5d8d25334
Set event stream reconnect time from Retry-After header 2023-07-26 10:55:17 +01:00
Samuel Elliott
2cbfdc5e04
Set event stream reconnect time from Retry-After header 2023-07-26 10:10:20 +01:00
Samuel Elliott
69afbc6d69
Fix handling errors connecting to event streams 2023-07-26 10:00:56 +01:00
Samuel Elliott
f043d8ebb0
Log coral status code 2023-07-24 17:34:07 +01:00
Samuel Elliott
c7514a0635
Wait before retrying failed requests 2023-07-24 17:10:34 +01:00
Samuel Elliott
cd6f614a99
Maybe fix EventSource reconnect 2023-07-24 17:09:38 +01:00
Samuel Elliott
fbc1bc1682
Add custom EventSource using fetch, automatically upgrade to SSE 2023-07-14 19:21:29 +01:00
Samuel Elliott
eda75b4dee
Add scripts for running the nxapi command using the app Electron binary 2023-07-14 18:54:51 +01:00
Samuel Elliott
584f0e2d89
Update dependencies 2023-07-13 02:19:52 +01:00
Samuel Elliott
7bdf9f578a
Remove uuid 2023-07-13 01:10:37 +01:00
Samuel Elliott
0a9e5d859d
Remove mkdirp 2023-07-13 00:12:21 +01:00
Samuel Elliott
d147c2a5e8
Remove node-fetch 2023-07-13 00:00:04 +01:00
Samuel Elliott
0457746e5e
Add support for HTTP proxies 2023-07-12 23:55:05 +01:00
Samuel Elliott
d7a64b9807
Switch to undici 2023-07-12 23:15:37 +01:00
Samuel Elliott
10a6784fa7
Update Discord titles
https://github.com/samuelthomas2774/nxapi/issues/75
2023-07-12 23:04:32 +01:00
Samuel Elliott
bb45ee39f5
Ignore errors from presence URLs and non-Nintendo API errors 2023-07-10 13:04:45 +01:00
Samuel Elliott
dfb2a3eea7
Show presence update errors in the main window 2023-07-10 12:40:02 +01:00
Samuel Elliott
7b838e9b3e
Send additional error information to preload script 2023-07-05 01:54:06 +01:00
Samuel Elliott
419ac22774
Update Discord titles 2023-07-05 01:18:00 +01:00
Samuel Elliott
3e1bd2621a
Improve error messages, record error history for use limits 2023-07-05 00:50:04 +01:00
Samuel Elliott
826ee51a68
Ignore HistoryRecordQuery errors when monitoring SplatNet 3 for presence data 2023-07-04 22:02:29 +01:00
Samuel Elliott
3c6025790e
API error classes 2023-07-04 22:01:22 +01:00
Samuel Elliott
5bd62cd576
Update Discord titles
https://github.com/samuelthomas2774/nxapi/issues/72
https://github.com/samuelthomas2774/nxapi/issues/73
2023-07-04 21:27:06 +01:00
Samuel Elliott
d1785ee1fc
Add CoralApiInterface 2023-07-04 21:01:25 +01:00
Samuel Elliott
865a09ee99
Discord usernames 2023-06-12 23:37:09 +01:00
Samuel Elliott
8ba5a787cf
Update mode icons for Splatoon 3 presence 2023-06-04 18:41:25 +01:00
Samuel Elliott
991a5f7a7c
Export nxapi/nintendo-account and fix error state validation 2023-06-03 22:15:22 +01:00
Samuel Elliott
72c2927de8
Save Nintendo Account tokens 2023-06-03 22:08:25 +01:00
Samuel Elliott
0af48a18ae
Add Nintendo Account authorisation helpers 2023-06-03 21:54:25 +01:00
Samuel Elliott
62d1982193
Add support for challenges for Splatoon 3 presence 2023-06-03 21:35:24 +01:00
Samuel Elliott
82021bb9c4
Fix detecting branch in CI and don't include remote-config.json in app bundle 2023-06-03 21:02:27 +01:00
Samuel Elliott
d60b0f260f
Show force language menu in CI builds
# Conflicts:
#	src/app/main/menu.ts
2023-06-03 21:02:21 +01:00
Samuel Elliott
e395a80431
Fix auto refresh text 2023-06-03 00:00:39 +01:00
Samuel Elliott
b689da3426
Merge branch 'i18n' into pull/63
# Conflicts:
#	src/app/i18n/index.ts
2023-06-02 23:30:46 +01:00
sarah
3c43019e00 update es-es.ts 2023-06-03 00:27:06 +02:00
sarah
2635632e97 update es-es.ts 2023-06-03 00:05:32 +02:00
sarah
8e5e42dfa4 update es-es.ts 2023-06-02 23:49:00 +02:00
sarah
c145a1af35 update es-es.ts 2023-06-02 23:43:38 +02:00
sarah
cf5192a9da add spanish localization 2023-06-02 23:43:38 +02:00
Samuel Elliott
fcbf6f4f7d
Merge branch 'i18n' into pull/63 2023-06-02 17:33:14 +01:00
Samuel Elliott
4acebd1608
Fix new window menu translation 2023-06-02 17:31:20 +01:00
Samuel Elliott
1af368d80e
Formatting 2023-06-02 17:15:46 +01:00
Samuel Elliott
b306d1d786
Merge branch 'i18n' into pull/63
# Conflicts:
#	src/app/i18n/index.ts
2023-06-02 17:13:02 +01:00
Samuel Elliott
c3016f9889
Fix detecting branch in CI and don't include remote-config.json in app bundle 2023-06-02 01:49:43 +01:00
Samuel Elliott
49b6d0dce2
Show force language menu in CI builds 2023-06-02 00:58:35 +01:00
Samuel Elliott
b16f77d13e
Merge remote-tracking branch 'github/pull/54' into i18n 2023-06-02 00:14:28 +01:00
Inkception
4e45c3b339
Add znca_api_use text 2023-06-02 01:01:13 +02:00
Inkception
99a511080a
Update de-de.ts 2023-06-02 00:39:58 +02:00
Inkception
0aad3e3ea6
Added missing constant 2023-06-02 00:31:47 +02:00
Inkception
9a8edb5bff
Update de-de.ts 2023-06-02 00:28:52 +02:00
Samuel Elliott
f8ab372171
Merge branch 'main' into i18n
# Conflicts:
#	src/app/main/na-auth.ts
2023-06-01 22:17:07 +01:00
Samuel Elliott
52a5ddba2d
Update third-party API use text 2023-06-01 22:16:18 +01:00
Samuel Elliott
edfd55a7a9
Translate Nintendo Account authentication window 2023-06-01 22:12:01 +01:00
Samuel Elliott
79e0a5516f
Merge branch 'main' into i18n
# Conflicts:
#	src/app/main/index.ts
#	src/app/main/ipc.ts
#	src/app/main/menu.ts
#	src/app/main/monitor.ts
#	src/app/main/webservices.ts
2023-06-01 21:42:03 +01:00
Samuel Elliott
ce0fd9cf9b
Fix modal window width on Windows 2023-06-01 20:19:33 +01:00
Samuel Elliott
95c2664678
Allow reading remote config from file URLs 2023-06-01 19:57:30 +01:00
Samuel Elliott
947c62214a
Update embedded remote config data 2023-06-01 19:49:04 +01:00
Samuel Elliott
ccbe3fb8dd
Update splatnet3-types 2023-06-01 19:33:22 +01:00
Samuel Elliott
681f9a5946
Allow reauthenticating using the Electron app 2023-06-01 19:31:33 +01:00
Samuel Elliott
1d0664e84f
Attempt to remove sensitive information from saved logs 2023-06-01 19:30:02 +01:00
Samuel Elliott
4d0b708469
Write debug logs 2023-06-01 18:45:31 +01:00
Samuel Elliott
512a9a2b60
Prevent using expired tokens 2023-05-25 14:07:32 +01:00
Samuel Elliott
f6aa9a17ab
Add na_id and coral_user_id to f generation requests 2023-05-25 13:42:48 +01:00
Samuel Elliott
8c4ba4dbc5
Translate main_window:sidebar.discord_not_connected 2023-05-23 00:11:38 +01:00
Samuel Elliott
cde3f4c7a3
Merge branch 'main' into i18n
# Conflicts:
#	src/app/browser/main/discord.tsx
2023-05-23 00:08:26 +01:00
Samuel Elliott
1518780b45
Update embedded remote config data 2023-05-22 23:58:57 +01:00
Samuel Elliott
776a635b29
Add active Eggstra Work schedule to presence server data 2023-05-22 23:58:56 +01:00
Samuel Elliott
ed33fd2a32
Fix event stream image URLs 2023-05-22 23:58:56 +01:00
Samuel Elliott
30333dec8e
HTTP server errors 2023-05-22 23:58:56 +01:00
Samuel Elliott
ed63648ddf
Send correct headers when getting a session token
https://github.com/samuelthomas2774/nxapi/issues/60
2023-05-22 23:56:23 +01:00
Samuel Elliott
7b82af5c40
Connect to Discord and show connected user when not sending an activity 2023-05-22 23:55:22 +01:00
Samuel Elliott
5379cdd805
Fix listing available Discord clients never disconnects 2023-05-22 23:51:12 +01:00
Samuel Elliott
28492f1dad
Update Discord titles
https://github.com/samuelthomas2774/nxapi/issues/57
https://github.com/samuelthomas2774/nxapi/issues/62
2023-05-22 23:50:01 +01:00
hilot06
32a5d98609 Update Japanese translation
I forgot some translation... and I added it
2023-05-18 00:32:09 +09:00
hilot06
8a86db4196 Add Japanese traslation 2023-05-18 00:12:29 +09:00
Samuel Elliott
e37830355a
Download presence server images 2023-03-28 23:02:11 +01:00
Samuel Elliott
f418583382
Filter duplicate vote records 2023-03-28 22:55:22 +01:00
Samuel Elliott
5e563d7c05
Record Splatfest voting status history 2023-03-28 21:39:14 +01:00
Samuel Elliott
66939d26fe
Fetch voting status for upcoming Splatfests 2023-03-26 02:06:02 +01:00
Samuel Elliott
36f84d563a
Add ENETUNREACH as a temporary error 2023-03-25 23:10:14 +00:00
Samuel Elliott
bb093d6b22
Add function to update user agent from package.json 2023-03-25 23:02:32 +00:00
Samuel Elliott
2da7f4f66e
v1.6.1 2023-03-01 11:15:07 +00:00
Samuel Elliott
6f6148fcad
Send coral platform/version to f generation API 2023-03-01 09:18:23 +00:00
Samuel Elliott
c6c8ff9d2d
Fix opening external links in SplatNet 3 2023-02-28 17:23:58 +00:00
Samuel Elliott
41f29328d9
Merge branch 'main' into i18n 2023-02-28 14:43:37 +00:00
Samuel Elliott
ccf0951df5
Update Discord titles
https://github.com/samuelthomas2774/nxapi/issues/55
2023-02-28 14:38:50 +00:00
Samuel Elliott
9b038c76da
Add support for Eggstra Work and Tableturf Battle for Splatoon 3 presence 2023-02-28 14:20:55 +00:00
Samuel Elliott
a7406bd850
Update SplatNet 3 version 2023-02-28 14:08:54 +00:00
Samuel Elliott
1d4781f4f6
Skip TypeScript when bundling 2023-02-28 14:05:49 +00:00
Samuel Elliott
af2535da20
Update splatnet3-types 2023-02-28 11:09:28 +00:00
Samuel Elliott
8d745845a2
Update Discord titles 2023-02-12 18:30:50 +00:00
Inkception
1272cd6b68 Last change for consistent naming 2023-01-30 04:08:06 +01:00
Inkception
8c04ecde5f Update / translate several keys 2023-01-30 04:05:51 +01:00
Inkception
23dec3773f Add missing comma 2023-01-30 03:40:29 +01:00
Inkception
693fd5d312 Changed several keys 2023-01-30 03:39:33 +01:00
Inkception
82744fec54 Added and updated (missing) keys 2023-01-30 03:20:08 +01:00
Inkception
b0603e1e82 Merge branch 'i18n' of https://github.com/Inkception/nxapi into i18n 2023-01-30 03:11:17 +01:00
Samuel Elliott
b9b9f6a8d7
Add relative time strings 2023-01-29 14:14:42 +00:00
Samuel Elliott
a661f91efb
Fix icon titles 2023-01-29 14:04:25 +00:00
Samuel Elliott
ecb7c578c9
Add a menu to override the detected language 2023-01-29 12:50:46 +00:00
Samuel Elliott
b91b98060d
Add translation credits to the about panel 2023-01-29 12:48:26 +00:00
Samuel Elliott
4dc85dace9
Fix language detection 2023-01-29 12:43:58 +00:00
Samuel Elliott
f94bf1c221
Fix add account response URL 2023-01-29 12:38:53 +00:00
Samuel Elliott
912d976aa1
Add friend code component 2023-01-29 12:38:35 +00:00
Inkception
ac3100f40e Changed several play_time values 2023-01-29 11:45:44 +01:00
Inkception
ae94bd6a8e grammar 2023-01-29 11:44:19 +01:00
Inkception
e235efebd5 Some more key corrections 2023-01-29 11:37:48 +01:00
Inkception
9849abb8e2 Change main_windows.enable_auto_refresh 2023-01-29 11:27:22 +01:00
Inkception
76ad85ee09 Escape url_help properly 2023-01-29 11:24:26 +01:00
Inkception
b4a6eac7e4
Add de-DE to languages 2023-01-29 11:16:50 +01:00
Inkception
ee73e5bc44
Update de-de.ts 2023-01-29 11:06:51 +01:00
Inkception
e4a1467d45
Update de-de.ts 2023-01-28 23:11:07 +01:00
Inkception
5d431a58d0
Add de-de.ts 2023-01-28 23:06:39 +01:00
Samuel Elliott
0b7e5b618f
App translation support
https://github.com/samuelthomas2774/nxapi/issues/40
2023-01-27 21:33:55 +00:00
Samuel Elliott
27e41f7735
Fix SplatNet 3 monitoring when no battle/coop history/album photos exist 2023-01-25 14:27:52 +00:00
Samuel Elliott
4a9c0085f1
Update splatnet3-types 2023-01-25 14:27:01 +00:00
Samuel Elliott
24a0d2bdc8
Update Discord titles
https://github.com/samuelthomas2774/nxapi/issues/52
2023-01-23 00:06:11 +00:00
Samuel Elliott
de44296d7b
Update README.md 2023-01-23 00:00:32 +00:00
Samuel Elliott
1ee984984c
Fix app development command from another directory 2023-01-22 23:03:59 +00:00
Samuel Elliott
186c34b8fd
Fix handling timeouts as a temporary error 2023-01-22 22:59:45 +00:00
Samuel Elliott
dce5af6f57
Handle non-standard Cloudflare temporary errors 2023-01-17 04:50:07 +00:00
Samuel Elliott
76114452e4
Update Tricolour stage images for Splatoon 3 Discord presence 2023-01-17 04:17:28 +00:00
Samuel Elliott
6867b6be9d
Fix update interval for friend code data 2023-01-17 04:01:23 +00:00
Samuel Elliott
2914fcc76b
Handle HTTP 502/503/504 errors as temporary 2023-01-17 04:00:32 +00:00
Samuel Elliott
67fb379e22
Fix handling timeouts as a temporary error 2023-01-16 21:38:14 +00:00
Samuel Elliott
5c6f106b78
Handle ECONNRESET as a temporary error 2023-01-16 21:37:45 +00:00
Samuel Elliott
f658befb3b
Fix presence server vote state for all users 2023-01-06 22:13:50 +00:00
Samuel Elliott
d3c4c2d1de
Skip fetching data when creating a client with a saved token and add client authentication limit 2022-12-29 14:53:23 +00:00
Samuel Elliott
788083b7f6
Add coral/SplatNet 3 client
https://github.com/samuelthomas2774/nxapi/issues/42
2022-12-26 20:55:32 +00:00
Samuel Elliott
11077b02ee
v1.6.0 2022-12-20 13:28:09 +00:00
Samuel Elliott
4e67c71dd7
Fix ZNC_PROXY_URL in docker-compose.yml 2022-12-19 11:01:13 +00:00
Samuel Elliott
14e7793b7c
Add automatic token renewal for Moon/NookLink and fix authentication limit with automatic token renewal 2022-12-19 09:15:47 +00:00
Samuel Elliott
4fcecd9f5b
Add X Ranking leaderboard queries 2022-12-18 13:18:37 +00:00
Samuel Elliott
20dd232a70
Disable automatic upgrade to presence event streams by default 2022-12-18 13:16:48 +00:00
Samuel Elliott
c5e50167dc
Add an option to show play time to the nearest hour 2022-12-18 13:06:29 +00:00
Samuel Elliott
7afc241190
Limit response data in error messages to 100 characters 2022-12-18 12:58:13 +00:00
Samuel Elliott
1e75674e08
Update docker-compose.yml 2022-12-18 12:57:08 +00:00
Samuel Elliott
9055be67c5
Track time playing current title 2022-12-18 12:17:41 +00:00
Samuel Elliott
8ab9c39f8c
Skip update check when running in Docker 2022-12-18 12:10:16 +00:00
Samuel Elliott
e0e8f712aa
Add presence server environment variables 2022-12-18 12:09:00 +00:00
Samuel Elliott
fb9cd6d76f
Add presence server SplatNet 3 proxy 2022-12-18 12:08:03 +00:00
Samuel Elliott
7035fb6b19
Get updated queries from remote configuration 2022-12-17 13:44:51 +00:00
Samuel Elliott
b9f9fd7f4a
Add rejecting removed queries 2022-12-17 13:20:36 +00:00
Samuel Elliott
cb78b3f5a7
Automatically upgrade SplatNet 3 persisted queries 2022-12-14 19:50:02 +00:00
Samuel Elliott
3fcc7b35ae
Fetch X Battle histories 2022-12-14 19:38:35 +00:00
Samuel Elliott
d23a65ba2e
Strict GraphQL query error handling 2022-12-14 19:37:30 +00:00
Samuel Elliott
bdf72352fb
Add X Ranking leaderboard and fest ranking pagination queries 2022-12-14 12:27:16 +00:00
Samuel Elliott
083f3fca17
Update SplatNet 3 revision 2022-12-12 22:54:22 +00:00
Samuel Elliott
2ab832f6b6
Update splatnet3-types 2022-12-12 22:54:01 +00:00
Samuel Elliott
205f01ebf0
Update coral
https://github.com/samuelthomas2774/nxapi/issues/35
2022-12-05 20:16:23 +00:00
Samuel Elliott
ef5da22df0
Update SplatNet 3 revision and add support for Big Run for Splatoon 3 presence 2022-12-05 20:15:34 +00:00
Samuel Elliott
7243fc3e96
Update SplatNet 3 version 2022-12-01 00:19:10 +00:00
Samuel Elliott
67276d6dee
Fix clearing activity while reconnecting to Discord 2022-11-27 16:24:48 +00:00
Samuel Elliott
d115d0d5bf
Update SplatNet 3 revision 2022-11-27 16:22:38 +00:00
Samuel Elliott
055fe2dff4
Handle timeouts as temporary errors 2022-11-27 16:19:56 +00:00
Samuel Elliott
3821a26038
Send events for errors to prevent connection timeouts 2022-11-27 15:46:40 +00:00
Samuel Elliott
496affa811
Fix clearing activity while reconnecting to Discord 2022-11-27 15:44:53 +00:00
Samuel Elliott
6d1391929f
Update dependencies 2022-11-27 15:15:57 +00:00
Samuel Elliott
890c02e3ef
Update SplatNet 3 revision 2022-11-21 10:27:36 +00:00
Samuel Elliott
827224cd80
Event stream timeout 2022-11-20 23:28:13 +00:00
Samuel Elliott
0c0a27bd8e
Add Access-Control-Allow-Origin header for browsers 2022-11-20 20:44:18 +00:00
Samuel Elliott
2dbee8bb35
Receive supported events from server 2022-11-20 20:43:47 +00:00
Samuel Elliott
3493ed09c0
Publish npm package as soon as the build job finishes 2022-11-19 12:52:24 +00:00
Samuel Elliott
c565dfbf60
Fix publishing from main and getting git revision in npm package 2022-11-19 01:48:11 +00:00
Samuel Elliott
b916e719bf
Fix stopping presence monitors with event streams 2022-11-16 16:50:45 +00:00
Samuel Elliott
fa877d5bd7
Update friends data after 10 minutes if the requested user isn't friends with the authenticated user 2022-11-16 15:23:48 +00:00
Samuel Elliott
19cb8c8775
Exclude unpacked files for macOS arm64 builds 2022-11-16 12:15:28 +00:00
Samuel Elliott
20bab43981
Handle connecting directly to the event stream URL 2022-11-16 12:13:48 +00:00
Samuel Elliott
a52c45af36
Use server sent events for presence monitoring 2022-11-16 12:10:42 +00:00
Samuel Elliott
4ac5f7f0ea
Include event stream URL in presence requests 2022-11-16 11:11:07 +00:00
Samuel Elliott
7f4b190465
Fix running presence server with default user 2022-11-16 11:07:33 +00:00
Samuel Elliott
c90a36d8d5
Fix Discord client ID validation 2022-11-12 18:59:59 +00:00
Samuel Elliott
4739eb1783
Build arm64 macOS app 2022-11-12 17:40:48 +00:00
Samuel Elliott
a8f665953b
Update Discord titles 2022-11-12 17:23:38 +00:00
Samuel Elliott
e6e1e73bdc
Add open hidden at login option for Windows and Linux
https://github.com/samuelthomas2774/nxapi/issues/19
2022-11-12 17:22:57 +00:00
Samuel Elliott
0192529020
Replace thumbnail images in presence data with original high quality images 2022-11-02 01:51:29 +00:00
Samuel Elliott
d573cf4dd0
Fix replacing images in presence data with splatoon3.ink links 2022-11-02 01:49:49 +00:00
Samuel Elliott
0e33825d27
Fix API proxy announcements 2022-10-31 17:22:05 +00:00
Samuel Elliott
f1ae5a7ea2
Fix error handling when using a presence URL 2022-10-31 16:49:12 +00:00
Samuel Elliott
1a25639440
Update documentation 2022-10-31 16:41:41 +00:00
Samuel Elliott
6c7f008617
Don't include Splatoon 3 presence if not playing Splatoon 3 2022-10-31 16:39:34 +00:00
Samuel Elliott
0935402b9d
Ignore errors from useCurrentFest/ConfigureAnalyticsQuery 2022-10-31 16:01:02 +00:00
Samuel Elliott
5014e32756
Add presence event stream 2022-10-31 02:04:24 +00:00
Samuel Elliott
2776c936a1
Add Retry-After header for temporary errors 2022-10-30 17:47:10 +00:00
Samuel Elliott
516349e5df
Move HTTP server functions to a separate class 2022-10-30 17:44:01 +00:00
Samuel Elliott
9cb4ced59f
HTTP servers 2022-10-30 03:56:01 +00:00
Samuel Elliott
a6acd99db7
v1.5.0 2022-10-28 14:45:48 +01:00
Samuel Elliott
30418d89b6
Show Splatoon 3 presence data in nxapi util discord-activity when using a presence URL 2022-10-28 02:21:40 +01:00
Samuel Elliott
e8cbbd39ca
Update SplatNet 3 revision 2022-10-28 01:58:03 +01:00
Samuel Elliott
c913540ab4
Fix Salmon Run stage images when using a presence URL 2022-10-28 01:57:45 +01:00
Samuel Elliott
82ba22b42f
Update documentation 2022-10-28 01:13:26 +01:00
Samuel Elliott
6f9afb041d
Automatically retry on temporary errors when using the presence API server 2022-10-26 17:18:12 +01:00
Samuel Elliott
9d290563d8
Add sendMessage, copyToClipboard and downloadImages web service functions 2022-10-26 16:35:46 +01:00
Samuel Elliott
628c87c97b
Update dependencies 2022-10-26 15:02:26 +01:00
Samuel Elliott
8a2e4c8090
Fix react-native-dev import with node16 module resolution 2022-10-26 14:51:39 +01:00
Samuel Elliott
462ec96fe2
Download battle details from regular/anarchy/private specific results 2022-10-26 14:30:01 +01:00
Samuel Elliott
8f6ae71061
Add a command to monitor SplatNet 3 records 2022-10-26 14:21:11 +01:00
Samuel Elliott
a33a36c4f5
Move Splatfest and photo album records to their own commands 2022-10-26 13:37:47 +01:00
Samuel Elliott
f88d10b61c
Add a command to download all player records 2022-10-26 13:29:10 +01:00
Samuel Elliott
c319e2685e
Fix publish-next 2022-10-22 01:16:30 +01:00
Samuel Elliott
0191edc9ad
Fix build-app runs before build is complete 2022-10-22 00:32:38 +01:00
Samuel Elliott
a49b4c427d
Build deb package 2022-10-22 00:20:22 +01:00
Samuel Elliott
44700fdd3a
Update package info 2022-10-22 00:20:01 +01:00
Samuel Elliott
616c40888a
Update splatnet3-types 2022-10-22 00:19:49 +01:00
Samuel Elliott
1e6cec9303
Include summaries when downloading SplatNet 3 results 2022-10-20 23:15:50 +01:00
Samuel Elliott
04e6a80496
Use SplatNet 3 types from splatnet3-types 2022-10-20 22:57:35 +01:00
Sophie L
dda504b50c fix: weird linting choices, use appId 2022-10-16 13:57:38 +00:00
Sophie L
08ff27398e fix: use correct title for Windows notifications 2022-10-16 00:38:04 +00:00
Samuel Elliott
bf48cc201b
Add command to list node-persist data 2022-10-15 22:20:54 +01:00
Samuel Elliott
65b36a384e
Add licence 2022-10-15 22:16:07 +01:00
Samuel Elliott
02e49a9554
Retry on EAI_AGAIN/SERVFAIL 2022-10-15 21:57:14 +01:00
Samuel Elliott
bc8e2ae2ac
Add note about using node16 module resolution for TypeScript 2022-10-15 20:23:17 +01:00
Samuel Elliott
e2ac4bbfb3
Use cached web service token to renew SplatNet 3 tokens and fix retrying getting web service tokens after renewing coral token 2022-10-11 20:47:26 +01:00
Samuel Elliott
79b1d9eaae
Publish main to npm 2022-10-11 16:21:41 +01:00
Samuel Elliott
cbefcad840
Publish main to npm 2022-10-11 15:43:02 +01:00
Samuel Elliott
1ed1e9c817
Publish main to npm 2022-10-11 15:32:45 +01:00
Samuel Elliott
84aa739f4b
Publish main to npm 2022-10-11 15:23:49 +01:00
Samuel Elliott
9647d9a411
Publish main to npm 2022-10-11 15:14:11 +01:00
Samuel Elliott
4fac2bb941
Publish main to npm 2022-10-11 14:56:06 +01:00
Samuel Elliott
9d6d49b44d
Update SplatNet 3 revision and query IDs 2022-10-11 12:06:50 +01:00
Samuel Elliott
5cb66f4249
Use cached web service token to renew SplatNet 3 tokens 2022-10-11 12:05:50 +01:00
Samuel Elliott
b6002cbf8b
Regenerate f when requesting a web service token after refreshing the coral token 2022-10-11 11:32:41 +01:00
Samuel Elliott
0b726a7d0e
Update coral
https://github.com/samuelthomas2774/nxapi/issues/28
2022-10-10 16:19:03 +01:00
Samuel Elliott
605ba117a0
Build Docker image 2022-10-01 19:39:17 +01:00
Samuel Elliott
32475b76d5
Move f generation server to a separate repository 2022-10-01 16:46:36 +01:00
Samuel Elliott
8bf06ae439
Update SplatNet 3 revision 2022-09-28 20:49:09 +01:00
Samuel Elliott
43cbccd9cb
Update coral
https://github.com/samuelthomas2774/nxapi/issues/25
2022-09-28 20:43:03 +01:00
Samuel Elliott
50d942ae44
Update SplatNet 3 types 2022-09-28 02:27:54 +01:00
Samuel Elliott
587b1237fb
Update SplatNet 3 types 2022-09-26 17:05:22 +01:00
Samuel Elliott
4a7277795c
Fix setting friend code when using a presence URL 2022-09-26 16:55:41 +01:00
Samuel Elliott
19f9ba74ec
Update SplatNet 3 types 2022-09-26 16:47:49 +01:00
Samuel Elliott
45c315978d
Prevent multiple Discord clients 2022-09-26 16:42:24 +01:00
Samuel Elliott
d9fb2657e6
Update SplatNet 3 types 2022-09-26 16:40:09 +01:00
Samuel Elliott
b71246719a
Don't fetch voting status for a Splatfest after it ends 2022-09-26 16:00:11 +01:00
Samuel Elliott
85d93c681e
Coral/SplatNet 3 presence proxy server 2022-09-25 19:51:05 +01:00
Samuel Elliott
85b9eb0543
Fix build error 2022-09-25 01:35:16 +01:00
Samuel Elliott
b869046f1f
Add Tricolour Battle 2022-09-25 01:17:08 +01:00
Samuel Elliott
62854fc428
Update README.md 2022-09-25 00:12:59 +01:00
Samuel Elliott
c3c42ff8d3
Prevent attempting to update SplatNet 3 data for presence if not configured 2022-09-24 23:02:45 +01:00
Samuel Elliott
72995b1a05
Use Splatoon 3 presence data from custom presence URLs 2022-09-24 23:02:24 +01:00
Samuel Elliott
a4d328c72a
Add Tricolour stage images 2022-09-24 16:42:45 +01:00
Samuel Elliott
d8fc9e352d
Allow resizing web services 2022-09-23 21:32:18 +01:00
Samuel Elliott
b26f71f930
Update documentation 2022-09-23 21:31:12 +01:00
Samuel Elliott
29b8923c5b
Prevent attempting to update SplatNet 3 data for presence if not configured
How can this happen??
2022-09-23 20:36:18 +01:00
Samuel Elliott
0d3ca779e0
Update SplatNet 3 revision 2022-09-23 12:15:23 +01:00
Samuel Elliott
a0e9bc79b2
Update SplatNet 3 types 2022-09-23 12:15:10 +01:00
Samuel Elliott
088604a509
Update dependencies 2022-09-22 22:59:41 +01:00
Samuel Elliott
9f001b83ff
Handle errors in Discord activity callbacks 2022-09-21 19:42:56 +01:00
Samuel Elliott
c85d184807
Use correct Splatfest stages and update stage images 2022-09-21 18:48:02 +01:00
Samuel Elliott
32327a0531
Fix SplatNet 3 monitor attempts to update once when stopping after an error 2022-09-21 16:35:14 +01:00
Samuel Elliott
f4447e6014
Apply saved configuration when enabling Discord presence 2022-09-21 16:11:16 +01:00
Samuel Elliott
c7fbe15047
Automatically renew SplatNet 3 tokens 2022-09-21 16:09:13 +01:00
Samuel Elliott
4e6a29f74f
Use detailed presence information from SplatNet 3 2022-09-21 15:47:42 +01:00
Samuel Elliott
e5fe9b389e
Hide unnecessary scrollbars in SplatNet 3
https://github.com/samuelthomas2774/nxapi/issues/24
2022-09-20 20:51:13 +01:00
Samuel Elliott
6f84981018
Hide menu in web services on Windows/Linux
https://github.com/samuelthomas2774/nxapi/issues/24
2022-09-20 16:36:41 +01:00
Samuel Elliott
3b9d07042f
Update SplatNet 3 types 2022-09-20 16:33:41 +01:00
Samuel Elliott
fa2854b527
Move Electron app entrypoint, handle launch errors 2022-09-20 15:51:06 +01:00
Samuel Elliott
13486a89c8
Update f generation server documentation 2022-09-19 20:13:13 +01:00
Samuel Elliott
c7948ded9e
Add an option to run adb root and add a warning if the setup script is not running as root 2022-09-19 19:17:36 +01:00
Samuel Elliott
25246be4b5
Hide Windows console window, add option to set adb path 2022-09-19 19:16:27 +01:00
Samuel Elliott
4cdc2adc30
Fix importing node-notifier 2022-09-19 19:13:23 +01:00
Samuel Elliott
99423f263b
Fix opening NookLink deep links 2022-09-19 19:12:44 +01:00
Samuel Elliott
8012dba821
Initial Splatfest types and commands 2022-09-19 19:12:22 +01:00
Samuel Elliott
c60442fa5e
Fix Nintendo Account authorisation callback handling on Windows 2022-09-15 22:14:26 +01:00
Samuel Elliott
6310485db7
Fix auth protocol registration on Windows when running from source 2022-09-15 22:12:14 +01:00
Samuel Elliott
99f263cef8
Fix preferences window never loads if Discord presence options have never been set 2022-09-15 22:10:19 +01:00
Samuel Elliott
b7299cb001
Add SplatNet 3 JSON schema generation 2022-09-14 22:18:20 +01:00
Samuel Elliott
6276cef356
Save downloaded Salmon Run records as splatnet3-coop-result-...
More consistent with filenames used for SplatNet 2 records
2022-09-14 18:16:49 +01:00
Samuel Elliott
4a993b2ca8
Merge remote-tracking branch 'github/pull/23' 2022-09-14 18:09:59 +01:00
Samuel Elliott
31926d83f4
Add an option to set how the app is started 2022-09-14 17:07:39 +01:00
Yi Huang
7d8cfa7e3b Add coop (salmon run) types and results for SplatNet 3 2022-09-13 07:48:33 +08:00
Samuel Elliott
56a991b03b
Update SplatNet 3 types, log GraphQL query ID for debugging 2022-09-12 16:55:30 +01:00
Samuel Elliott
41623b1bb3
Add support for using web service deep links while the web service is open and fix user selection menu for deep links is closed immediately 2022-09-12 16:50:21 +01:00
Samuel Elliott
07a30e89be
Use cached web services from the API for the menu
Fixes https://github.com/samuelthomas2774/nxapi/issues/21
2022-09-12 16:41:53 +01:00
Samuel Elliott
7576a16af7
Declare custom schemes for Nintendo Account authentication 2022-09-12 01:23:26 +01:00
Samuel Elliott
ccdb4bac8d
Add window for manually copying the redirect URI for Nintendo Account authentication 2022-09-12 01:22:23 +01:00
Samuel Elliott
ca0b063f58
Allow adding an account using the default browser by holding shift when pressing the add account button 2022-09-11 23:13:23 +01:00
Samuel Elliott
eaa0c0810e
Preferences window styles 2022-09-10 20:42:08 +01:00
Samuel Elliott
809658ac7b
Improve error handling when launching web services 2022-09-10 20:04:34 +01:00
Samuel Elliott
a6cc0e6254
Remove spaces 2022-09-10 19:38:09 +01:00
Samuel Elliott
ed3067ff45
Merge remote-tracking branch 'github/pull/20' 2022-09-10 18:51:30 +01:00
Adrthegamedev
1da7d5b9aa
added arms global test punch, kirby forgotten land demo, and live a live demo 2022-09-11 01:43:59 +08:00
Samuel Elliott
c9c91a874d
Fix web service ID type in token request, handle errors requesting a new token 2022-09-10 16:58:02 +01:00
Samuel Elliott
0b91bf87db
Hide the exit button in SplatNet 3 2022-09-10 15:53:28 +01:00
Samuel Elliott
b6099a7d18
Add support for triggering a refresh in SplatNet 3 by pressing Cmd+R/Ctrl+R 2022-09-10 15:45:57 +01:00
Samuel Elliott
e3b967a412
Add a command to get friends data from SplatNet 3 2022-09-10 15:42:45 +01:00
Samuel Elliott
203a54be44
Add a command to download all battle results from SplatNet 3 2022-09-09 21:53:46 +01:00
Samuel Elliott
0821235a89
Add home, settings, history, schedules and battle history types 2022-09-09 13:28:18 +01:00
Samuel Elliott
4a95c231d3
Add user and schedule SplatNet 3 commands 2022-09-09 01:43:23 +01:00
Samuel Elliott
8979c6d28e
SplatNet 3 authentication 2022-09-09 01:10:55 +01:00
Samuel Elliott
1aa4aad85a
SplatNet 3 authentication 2022-09-08 19:44:15 +01:00
Samuel Elliott
80afc62268
Add optional strict validation, automatically retry after reconnecting and report server timing for f parameter generation 2022-09-07 22:02:14 +01:00
Samuel Elliott
5b93c63c23
Use coral result object directly 2022-09-07 17:33:40 +01:00
Samuel Elliott
9112a5a02b
Return response objects and return coral result object directly 2022-09-07 17:13:53 +01:00
Samuel Elliott
4b5edd73df
Add a command to show the user's active event 2022-09-07 16:29:36 +01:00
Samuel Elliott
0421f5e565
Add a button to open the preferences window in the Discord setup window 2022-09-07 16:12:13 +01:00
Samuel Elliott
5236536222
Disable Chromium's resolver 2022-09-07 15:57:42 +01:00
Samuel Elliott
8afcd80f5a
Add preferences window 2022-09-07 15:54:38 +01:00
Samuel Elliott
87071dd5c3
Save presence data so start timestamp is not reset when restarting the app 2022-09-07 10:39:28 +01:00
Samuel Elliott
66c8efdb96
Accept numbers for the hash_method option when generating f parameters 2022-09-07 10:22:37 +01:00
Samuel Elliott
960624cae4
Update flapg API 2022-09-01 14:08:48 +01:00
Samuel Elliott
120f45d561
Update f generation server documentation 2022-08-26 16:40:02 +01:00
Samuel Elliott
89ce7936ba
v1.4.0 2022-08-24 20:35:56 +01:00
Samuel Elliott
7c010ed719
Update dependencies 2022-08-24 19:48:19 +01:00
Samuel Elliott
e5a955e666
Fix sending request_id when using nxapi's f-generation API 2022-08-24 19:21:27 +01:00
Samuel Elliott
ce6272318e
Hide the dock icon on macOS when no windows are open
https://github.com/samuelthomas2774/nxapi/issues/18
2022-08-24 18:39:52 +01:00
Samuel Elliott
a6b8dc33e8
Update imink API 2022-08-24 17:31:34 +01:00
Samuel Elliott
223faab510
Fix error traces in the packaged Electron app 2022-08-23 20:10:28 +01:00
Samuel Elliott
428f7131a1
Fix f parameter generation
This fixes `f` parameter generation with nxapi's custom server. This will also work with imink/flapg *if the system time exactly matches the imink/flapg Android device's time*. This commit also makes nxapi's API compatible with imink's API and adds some information about the Android device and NSO app to response headers.
2022-08-23 16:47:15 +01:00
Samuel Elliott
7a37d7f7df
Update documented default API for f parameter generation 2022-08-22 20:01:26 +01:00
Samuel Elliott
0eaed2adf7
Change default API for f parameter generation to imink
This will only have any effect if remote configuration is disabled. The default API will also be updated on my server which will affect all versions since remote configuration was introduced.

https://github.com/JoneWang
2022-08-22 11:44:55 +01:00
Samuel Elliott
624d60dc1b
Always check response status codes 2022-08-22 11:36:37 +01:00
Samuel Elliott
67819b4af5
Fix some issues with X Rank season calculation and add season indexes 2022-08-21 20:28:22 +01:00
Samuel Elliott
898cb6f707
Add library documentation 2022-08-21 20:15:11 +01:00
Samuel Elliott
ceed9accc2
Fix add button position 2022-08-20 20:23:10 +01:00
Samuel Elliott
f900696a79
Fix NookLink type error 2022-08-20 20:22:39 +01:00
Samuel Elliott
a8e9641b6c
Update Discord titles 2022-08-18 09:21:51 +01:00
Samuel Elliott
7423da8d98
Update NookLink 2022-08-16 18:41:45 +01:00
Samuel Elliott
0d54381c6d
Show friends relative last online time 2022-08-16 18:38:06 +01:00
Samuel Elliott
9fa92fd6cc
Fix friend context menus not updating 2022-08-16 18:18:46 +01:00
Samuel Elliott
533af4aeba
Disable client hints for web services 2022-08-16 18:17:23 +01:00
Samuel Elliott
f628d371e1
Add NookLink constructor helper functions 2022-08-16 18:16:30 +01:00
Samuel Elliott
84f7d42d79
Add missing fetch timeouts to coral requests
Fixes the issue where these requests may never complete.
2022-08-16 17:52:56 +01:00
Samuel Elliott
65d1069edf
Only request data necessary to appear as if opening Nintendo's app 2022-08-16 17:00:59 +01:00
Samuel Elliott
77f07eb1b3
Always check response status codes 2022-08-13 01:31:16 +01:00
Samuel Elliott
0697504379
Remove spaces 2022-08-13 01:27:13 +01:00
Samuel Elliott
3ae57b3546
Update README.md 2022-08-13 01:24:11 +01:00
Samuel Elliott
33958618b0
Prevent detecting a script when redirecting output 2022-08-13 00:49:22 +01:00
Samuel Elliott
f24dc2c63c
Remove unidentified-script user agent when running the API proxy server 2022-08-13 00:40:24 +01:00
Samuel Elliott
0e7b6e50c4
Fix friends list stops updating
How?
2022-08-13 00:39:27 +01:00
Samuel Elliott
5f0fd26ef6
Handle OAuth errors properly 2022-08-13 00:38:45 +01:00
Samuel Elliott
4c5203e50e
Add friend code lookup and friend requests to the Electron app 2022-08-13 00:21:03 +01:00
Samuel Elliott
ca36935f78
Fix friend code user type 2022-08-13 00:15:01 +01:00
Samuel Elliott
67b6052bf3
v1.3.0 2022-08-02 16:50:24 +01:00
Samuel Elliott
8171afc429
Export version 2022-08-02 11:36:45 +01:00
Samuel Elliott
dfef97c369
Add an option to skip building Windows app in CI 2022-08-02 11:32:38 +01:00
Samuel Elliott
225efcd4a5
Revalidate config data on update 2022-08-02 10:46:02 +01:00
Samuel Elliott
1c436c6fb7
Fix not setting Discord activity on first update 2022-07-31 21:43:56 +01:00
Samuel Elliott
4775c2de0a
Don't wait to connect to Discord 2022-07-30 17:34:10 +01:00
Samuel Elliott
91df61e500
Always install Frida in Docker images 2022-07-30 16:43:44 +01:00
Samuel Elliott
fc2dec15c0
Add SplatNet 2 constructor helper functions and always send player ID 2022-07-29 18:46:22 +01:00
Samuel Elliott
2d52f17022
Update config URL and use config data 2022-07-29 17:59:17 +01:00
Samuel Elliott
e8e5a2f5a4
Merge branch 'remote-config' 2022-07-29 16:34:33 +01:00
Samuel Elliott
d47a492242
Share custom Nintendo eShop region selection page to Discord instead of the user's own region 2022-07-28 22:04:27 +01:00
Samuel Elliott
e9218b9004
Add friend code URL to API proxy 2022-07-28 14:04:29 +01:00
Samuel Elliott
0cc39aad13
Add friend code lookup to API proxy 2022-07-28 13:57:39 +01:00
Samuel Elliott
b3efd0f15c
Update Dockerfile to use Node.js v18 2022-07-28 13:09:06 +01:00
Samuel Elliott
db449fb4db
Update dependencies 2022-07-27 18:07:08 +01:00
Samuel Elliott
4ec0693ff0
Don't limit attempts to login when adding a new account 2022-07-27 16:28:09 +01:00
Samuel Elliott
bd1cd6cf91
Increase limit for parental controls 2022-07-27 16:12:38 +01:00
Samuel Elliott
3bb18d0b46
Increase request timeout 2022-07-27 15:52:57 +01:00
Samuel Elliott
e12bb364a7
Prevent attempting to authenticate more than four times per hour
This only affects scripts - running this nxapi command in a terminal and the Electron app will ignore this limit.

https://github.com/samuelthomas2774/nxapi/issues/9
2022-07-27 15:48:19 +01:00
Samuel Elliott
d3e5a88625
Fix ZncProxyApi types 2022-07-27 14:52:00 +01:00
Samuel Elliott
163023501d
Remove spaces 2022-07-27 14:47:36 +01:00
Samuel Elliott
b6074ebed0
Add commands for friend requests/friend codes 2022-07-27 14:40:09 +01:00
Samuel Elliott
38c282bf6c
Update SplatNet 2 types 2022-07-27 14:31:54 +01:00
Samuel Elliott
85a9193328
Update coral
https://github.com/samuelthomas2774/nxapi/issues/14
2022-07-27 14:16:43 +01:00
Samuel Elliott
39ffa02e58
Remote configuration 2022-07-23 19:57:09 +01:00
Samuel Elliott
fe725f931a
Format response data in error messages 2022-07-23 18:07:25 +01:00
Samuel Elliott
a32c3dec72
Update API types 2022-07-23 17:45:20 +01:00
Samuel Elliott
dddb15aceb
Use package.json exports field 2022-07-23 17:42:41 +01:00
Samuel Elliott
d7a7d32823
Add setting a user agent using an environment variable 2022-07-23 13:40:24 +01:00
Samuel Elliott
e7dc1a99cb
Update README 2022-07-23 13:27:27 +01:00
Samuel Elliott
fd2789fb93
Update Discord titles 2022-07-23 11:06:48 +01:00
Samuel Elliott
0e630201c3
Rollup code splitting 2022-07-02 19:57:52 +01:00
Samuel Elliott
169815588e
v1.2.0 2022-07-02 13:18:44 +01:00
Samuel Elliott
1da4f463f3
Build app for Windows in CI 2022-07-01 22:33:02 +01:00
Samuel Elliott
21f5f095a0
Add helper function for setting user agent 2022-07-01 21:22:40 +01:00
Samuel Elliott
62604f3c2a
Add Discord presence/friend notification options to app context menus 2022-07-01 14:00:45 +01:00
Samuel Elliott
8d38b94dcd
Fix segfault when running app bundle 2022-06-30 18:36:00 +01:00
Samuel Elliott
4c6353c523
Include package.json/git info in Rollup bundles 2022-06-30 17:51:27 +01:00
Samuel Elliott
82e9b82e23
Add menu/tray icon 2022-06-30 16:22:02 +01:00
Samuel Elliott
bb606cfa7b
Handle errors loading data in the main window 2022-06-30 15:57:12 +01:00
Samuel Elliott
e5c54613d0
Handle errors starting/updating presence monitors 2022-06-29 09:31:31 +01:00
Samuel Elliott
b185b59d91
Handle errors from the Nintendo Account authorisation page 2022-06-28 20:25:54 +01:00
Samuel Elliott
5e25570d2d
Update SplatNet 2 types 2022-06-28 19:24:24 +01:00
Samuel Elliott
a6a69b1799
Rename most instances of znc to coral 2022-06-28 19:22:01 +01:00
Samuel Elliott
a2f3abaebd
Remove unpacked dependencies from app 2022-06-28 15:47:41 +01:00
Samuel Elliott
714b79c362
Make Frida an optional dependency and use Node.js v18 in CI 2022-06-26 18:04:39 +01:00
Samuel Elliott
1ddbe10f25
Add a command and functions to get SplatNet 2 X Rank seasons 2022-06-26 18:00:47 +01:00
Samuel Elliott
ed91f2d085
Add a command to get a NookLink user token 2022-06-26 17:55:56 +01:00
Samuel Elliott
39bfc8ab39
Add a command to get a SplatNet 2 iksm_session cookie 2022-06-26 16:14:02 +01:00
Samuel Elliott
48b2f30ffc
Fix update message still appearing after updating 2022-06-26 16:09:00 +01:00
Samuel Elliott
88076b7380
Update Discord titles
https://github.com/samuelthomas2774/nxapi/issues/6
2022-06-26 16:06:47 +01:00
Samuel Elliott
57d8556b94
v1.1.0 2022-06-19 20:49:07 +01:00
Samuel Elliott
d09b8c2cb7 Fix staying open in background and URL handling on Windows 2022-06-19 20:16:47 +01:00
Samuel Elliott
8f6a40e18d
Declare custom URI scheme and change app package name
By default the snap name is the package name, which conflicts with the CLI command name.
2022-06-18 12:49:42 +01:00
Samuel Elliott
1fc6cce5a6
Add support for all Discord presence options for the app 2022-06-18 12:46:03 +01:00
Samuel Elliott
7e5988685d
Prevent multiple instances and don't quit when all windows are closed 2022-06-18 12:20:42 +01:00
Samuel Elliott
d54ba360cf
Add Nintendo eShop link to friend modal 2022-06-16 16:26:15 +01:00
Samuel Elliott
3d8612b7b9
Add guided Discord setup 2022-06-16 16:21:01 +01:00
Samuel Elliott
961f5cc150
Don't wait for monitors to start when starting the app 2022-06-16 12:57:16 +01:00
Samuel Elliott
0195f65d63
Fix light macOS buttons 2022-06-16 12:55:10 +01:00
Samuel Elliott
f6e4769043
Update Discord titles
https://github.com/samuelthomas2774/nxapi/issues/5
2022-06-15 18:35:14 +01:00
Samuel Elliott
abb440343a
Add x-appcolorscheme header for web service requests 2022-06-12 22:08:14 +01:00
Samuel Elliott
1ebfa896a1
v1.0.0 2022-06-12 19:40:21 +01:00
Samuel Elliott
1ee6950c45
Update README.md 2022-06-12 18:51:16 +01:00
Samuel Elliott
aa08c81a2a
Don't show macOS themed buttons as pressed when the cursor isn't over them 2022-06-12 16:58:13 +01:00
Samuel Elliott
b3c9fd8d8b
Add a warning about third-party API usage when adding a Nintendo Switch Online app account 2022-06-12 16:27:40 +01:00
Samuel Elliott
4bf9908362
Fetch timeout 2022-06-12 15:36:00 +01:00
Samuel Elliott
ca35545f98
Add functions to use a specific Discord user in the app 2022-06-12 15:19:12 +01:00
Samuel Elliott
241ce19ec8
Native-like macOS buttons and Windows appearance 2022-06-12 15:15:35 +01:00
Samuel Elliott
49ee4f87b5
Windows and save presence URLs 2022-06-09 17:14:56 +01:00
Samuel Elliott
c6a91b74dc
Electron app 2022-06-09 01:27:30 +01:00
Samuel Elliott
4b67de5450
Update Discord titles 2022-06-09 01:21:47 +01:00
Samuel Elliott
065e9f6175
Electron app 2022-06-09 01:21:39 +01:00
Samuel Elliott
60c0e592db
Electron app 2022-06-05 15:04:36 +01:00
Samuel Elliott
27e8fa5401
Fix automatically renewing token never completes 2022-05-30 23:59:03 +01:00
Samuel Elliott
e46d778dd0
Add docker-compose.yml 2022-05-30 18:20:42 +01:00
Samuel Elliott
9f63fc8359
Handle simultaneous znc proxy requests properly 2022-05-30 13:16:06 +01:00
Samuel Elliott
b8f9c2c110
Automatically renew token when znc responds with a token expired error 2022-05-30 12:32:38 +01:00
Samuel Elliott
e48fba254c
Don't include the resources directory in the package 2022-05-29 20:23:41 +01:00
Samuel Elliott
1573accd73
Generate scripts for znca API server 2022-05-29 20:18:49 +01:00
Samuel Elliott
f23670047c
Update Discord titles 2022-05-29 19:30:06 +01:00
Samuel Elliott
18761bbb31
Update dependencies 2022-05-29 19:16:54 +01:00
Samuel Elliott
5328ada1e7
Show share menu for web services 2022-05-29 18:02:07 +01:00
303 changed files with 38769 additions and 12042 deletions

55
.github/ISSUE_TEMPLATE/bug.yml vendored Normal file
View 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
View 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

View File

@ -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

3
.github/funding.yml vendored Normal file
View File

@ -0,0 +1,3 @@
ko_fi: samuelelliott
custom:
- https://www.buymeacoffee.com/samuelelliott

4
.gitignore vendored
View File

@ -1,4 +1,6 @@
node_modules
dist
data
.vscode/schema
docker-compose.override.yml
.env
.vscode/schema/generated

View File

@ -1,97 +1,245 @@
image: node:17
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
- 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
- PACKAGE=`npm --color="always" pack`
- mv "$PACKAGE" nxapi.tgz
- node bin/nxapi.js util validate-discord-titles
- 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/**/*
- 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
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:
- node resources/build/ci-package-json.js
- 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
- $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

View File

@ -1,17 +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/generated/remote-config.schema.json

29
.vscode/launch.json vendored
View File

@ -10,11 +10,14 @@
"request": "launch",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
"osx": {
"runtimeExecutable": "${workspaceFolder}/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron"
},
"windows": {
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd"
"runtimeExecutable": "${workspaceFolder}/node_modules/electron/dist/electron.exe"
},
"args": [
"dist/app/main/app-entry.cjs"
"dist/app/app-entry.cjs"
],
"outputCapture": "std",
"env": {
@ -22,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"
}
]
}

View File

@ -0,0 +1,4 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$ref": "../generated/moon-types.schema.json#/definitions/DailySummary"
}

View File

@ -0,0 +1,4 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$ref": "../generated/moon-types.schema.json#/definitions/MonthlySummary"
}

View File

@ -0,0 +1,4 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$ref": "../generated/nooklink-types.schema.json#/definitions/Newspaper"
}

View File

@ -0,0 +1,4 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$ref": "../generated/splatnet2-types.schema.json#/definitions/CoopResultWithPlayerNicknameAndIcons"
}

View File

@ -0,0 +1,4 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$ref": "../generated/splatnet2-types.schema.json#/definitions/CoopResults"
}

View File

@ -0,0 +1,4 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$ref": "../generated/splatnet2-types.schema.json#/definitions/HeroRecords"
}

View File

@ -0,0 +1,4 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$ref": "../generated/splatnet2-types.schema.json#/definitions/NicknameAndIcon"
}

View File

@ -0,0 +1,4 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$ref": "../generated/splatnet2-types.schema.json#/definitions/Records"
}

View File

@ -0,0 +1,4 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$ref": "../generated/splatnet2-types.schema.json#/definitions/ResultWithPlayerNicknameAndIcons"
}

View File

@ -0,0 +1,4 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$ref": "../generated/splatnet2-types.schema.json#/definitions/Results"
}

View File

@ -0,0 +1,4 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$ref": "../generated/splatnet2-types.schema.json#/definitions/Timeline"
}

View 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"
]
}

View 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"
]
}

15
.vscode/settings.json vendored
View File

@ -49,6 +49,21 @@
"fileMatch": ["**/nooklink-newspaper-*.json"],
"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/generated/remote-config.schema.json"
},
],
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.preferences.quoteStyle": "single",
}

View File

@ -1,4 +1,4 @@
FROM node:17 as build
FROM node:20 as build
WORKDIR /app
@ -13,11 +13,7 @@ ADD tsconfig.json /app
RUN npx tsc
FROM node:17
RUN apt update && \
apt install -y android-tools-adb && \
apt-get clean
FROM node:20
WORKDIR /app
@ -28,14 +24,13 @@ RUN npm ci --production
COPY bin /app/bin
COPY resources /app/resources
COPY resources/cli/fonts /usr/local/share/fonts
COPY --from=build /app/dist /app/dist
RUN ln -s /app/bin/nxapi.js /usr/local/bin/nxapi
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
View 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/>.

865
README.md
View File

@ -1,43 +1,82 @@
nxapi
===
Access the Nintendo Switch Online and Nintendo Switch Parental Controls app APIs. Includes Discord Rich Presence, friend notifications and data downloads.
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.
[![Discord server](https://img.shields.io/discord/998657768594608138?color=5865f2&label=Discord)](https://discord.com/invite/4D82rFkXRv)
### Features
- Command line and menu bar app interfaces
- 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 splatnet2statink and flapg APIs by default.
- Alternatively the imink API or a custom server can be used.
- A custom server using a rooted Android device/emulator is included.
- 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.
- 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).
![Screenshot showing Splatoon 2 as a Discord activity](resources/Screenshot%202022-03-31%20at%2017.56.47%203.png)
- 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
![Screenshot showing a presence notification](resources/Screenshot%202022-03-31%20at%2017.56.47%202.png)
- [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.
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
------------------------------------|-----------------------------------|-----------------------------------
![Screenshot showing Splatoon 2 as a Discord activity](resources/discord-activity.png) | <img src="resources/discord-activity-splatoon3.png" alt="Screenshot showing Splatoon 3 as a Discord activity with SplatNet 3 presence information" width="308"> | ![Screenshot showing a presence notification](resources/notification.png)
#### 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
- 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
- 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
- Multiple users can be selected.
- Access game-specific services
- These will be opened in the app.
![Screenshot of the app](resources/app.png)
![Screenshot of the menu bar app with SplatNet 2 and NookLink open in the background](resources/menu-app.png)
The app includes the nxapi command line at `dist/bundle/cli-bundle.js`.
```sh
# macOS
Nintendo\ Switch\ Online.app/Contents/bin/nxapi
# 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?
@ -45,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.
@ -57,48 +106,38 @@ 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
It's required to generate some data to make Nintendo think you're using the real Nintendo Switch Online app. (This isn't required for Parental Controls data.) See the splatnet2statink and flapg section below for more information.
#### Why is data sent to non-Nintendo servers?
Currently it's too hard to do this locally. nxapi includes a service to do this using a rooted Android device/emulator. Hopefully at some point this will become easier.
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.
This is really annoying. Initially the Nintendo Switch Online app didn't perform any sort of client attestation at all, then Nintendo added a HMAC of the id_token, timestamp and request ID to app/web service login requests, using a secret key embedded in the app, which was soon discovered. Nintendo later updated the app to use a native library (`libvoip`, which is also used for the app's VoIP features) to do this, and still no one knows how it works. (To make things even more confusing, the function, `genAudioH`/`genAudioH2`, always returns a different result, even when given the same inputs.)
#### I need help using nxapi or Nintendo's APIs/I want to share something I've made using nxapi or Nintendo's APIs
The reason Nintendo added this is probably to try and stop people automating access to their app's API. I really hope that's wrong though, as then Nintendo would be prioritising that over account security, as most people seem ok with sharing account credentials to access the API. (And it's not stopping anyone accessing the API outside of the app anyway.)
I've created a Discord server for this project. Anyone interested in Nintendo's smart device app APIs is welcome to join, even if you're not interested in this project.
### Electron app
If you are creating something using Nintendo's smart device APIs: updates to Nintendo's apps are published in [#nintendo-app-versions](https://discord.com/channels/998657768594608138/998659415462916166).
nxapi includes an Electron menu bar app. Currently it can only be used by installing from source (there's no packaged version yet).
The app can currently be used to:
- 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.
- Accounts are shared with the nxapi command line interface.
- Share an authenticated Nintendo Account's presence to Discord.
- Using a custom presence URL or a friend's presence is not supported.
- Only one user can be selected - selecting another user will stop sharing the first user's presence.
- Showing notifications for an authenticated user/friend's presence.
- Multiple users can be selected, but this doesn't work yet.
- Access game-specific services.
- These will be opened in the app.
![Screenshot of the menu bar app open with SplatNet 2 and NookLink open in the background](resources/Screenshot%202022-04-17%20at%2023.56.08%202.png)
After installing nxapi from source the app can be run using this command:
```sh
nxapi app
```
This command has no options, but environment variables can still be used.
Invitation: https://discord.com/invite/4D82rFkXRv
### Install
@ -115,520 +154,47 @@ npm install --global --registry https://gitlab.fancy.org.uk/api/v4/packages/npm/
# From npm.pkg.github.com
npm install --global --registry https://npm.pkg.github.com @samuelthomas2774/nxapi
# From gitlab.com
npm install --global --registry https://gitlab.com/api/v4/packages/npm/ @samuelthomas2774/nxapi
```
#### Install from source
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
git clone https://gitlab.fancy.org.uk/samuel/nxapi.git # or download as an archive
# Don't download an archive, as nxapi detects the current git revision
git clone https://gitlab.fancy.org.uk/samuel/nxapi.git
cd nxapi
# Install locally
# Install CLI/Electron app locally
npm install
npx tsc
# CLI
# This command installs the nxapi command globally
# You can also use the CLI with node bin/nxapi.js ...
npm link
# Electron app
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 ...
```
### Nintendo Switch Online
### Usage
#### Login to the Nintendo Switch Online app
Information on the nxapi command line interface can be found at [docs/cli.md](docs/cli.md).
```sh
# Interactive login
# Generates a link to login with a Nintendo Account, asks for the link then automatically gets a session token
nxapi nso auth
# Login with an existing token
# Use with a token obtained via MITM the app, or with `nxapi nso auth --no-auth`
# The same session token as for the Nintendo Switch Parental Controls app cannot be used
nxapi nso token
# Get the authenticated user
nxapi nso user
```
#### Discord Presence
```sh
# Show the authenticated user's presence
nxapi nso presence
# Show a friend's presence
# Use `nxapi nso friends` to show all friend's Nintendo Switch account IDs
nxapi nso presence --friend-nsaid 0123456789abcdef
# Show the authenticated user's friend code in Discord
nxapi nso presence --friend-code
nxapi nso presence --friend-code -
# Show a custom friend code in Discord
# Use this if you are showing presence of a friend of the authenticated user
nxapi nso presence --friend-code 0000-0000-0000
nxapi nso presence --friend-code SW-0000-0000-0000
# Show inactive presence
# This will show a "Not playing" status if any consoles linked to the user's account is online but the user
# is not selected in a game
# Don't enable this if you are not the only user of all consoles linked to your account
nxapi nso presence --show-inactive-presence
# Also show friend notifications (see below)
nxapi nso presence --friend-notifications
nxapi nso presence --user-notifications --friend-notifications
nxapi nso presence --user-notifications
# Set update interval to 60 seconds
nxapi nso presence --update-interval 60
# Fetch presence from a custom URL (see `nxapi nso http-server`)
nxapi nso presence --presence-url "http://[::1]:12345/api/znc/user/presence"
nxapi nso presence --presence-url "http://[::1]:12345/api/znc/friend/0123456789abcdef/presence"
```
#### Friend presence notifications
This uses node-notifier to display native desktop notifications.
```sh
# Show notifications for all friends
nxapi nso notify
# Show notifications for all friends + the current user
nxapi nso notify --user-notifications
# Show notifications for only the current user
nxapi nso notify --user-notifications --no-friend-notifications
# Set update interval to 60 seconds
nxapi nso notify --update-interval 60
```
#### Friends
```sh
# Show Nintendo Switch friends in a table
nxapi nso friends
# JSON
nxapi nso friends --json
nxapi nso friends --json-pretty-print
```
#### Nintendo Switch Online app announcements/alerts
```sh
# Show app announcements in a table
nxapi nso announcements
# JSON
nxapi nso announcements --json
nxapi nso announcements --json-pretty-print
```
#### Web services/game-specific services
```sh
# Show web services in a table
nxapi nso webservices
# JSON
nxapi nso webservices --json
nxapi nso webservices --json-pretty-print
# Get an access token for a web service
# This should be sent with the first request to the web service URL in the `x-gamewebtoken` header
nxapi nso webservicetoken 5741031244955648
nxapi nso webservicetoken 5741031244955648 --json
nxapi nso webservicetoken 5741031244955648 --json-pretty-print
```
#### API proxy server
Use this to access the Nintendo Switch Online app API from a browser/other HTTP client easily.
```sh
# Start the server listening on all interfaces on a random port
nxapi nso http-server
# Start the server listening on a specific address/port
# The `--listen` option can be used multiple times
nxapi nso http-server --listen "[::1]:12345"
# Use the API proxy server in other commands
nxapi nso ... --znc-proxy-url "http://[::1]:12345/api/znc"
ZNC_PROXY_URL=http://[::1]:12345/api/znc nxapi nso ...
# Start the server using another API proxy server
nxapi nso http-server --znc-proxy-url "http://[::1]:12345/api/znc"
ZNC_PROXY_URL=http://[::1]:12345/api/znc nxapi nso http-server
# Allow requests without a Nintendo Account session token
# Anyone connecting to the API proxy server will be able to use any already authenticated user with their Nintendo Account ID
# Don't set this if anyone can connect to the server!
nxapi nso http-server --listen "[::1]:12345" --no-require-token
# Limit the frequency of friends/announcements/web services requests to 60 seconds
nxapi nso http-server --update-interval 60
# Make API requests using curl
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/auth"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/announcements"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/friends"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/friends/presence"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/friend/0123456789abcdef"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/friend/0123456789abcdef/presence"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/webservices"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/webservice/5741031244955648/token"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/activeevent"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/user"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/user/presence"
# Watch for changes to the user and all friends presence
curl --header "Authorization: na $NA_SESSION_TOKEN" --no-buffer "http://[::1]:12345/api/znc/presence/events"
# Make API requests using curl without a session token
# The `--no-require-token` must be set when running the server, and the user must have previously authenticated to the server, either with the API proxy server or using commands on the server
curl "http://[::1]:12345/api/znc/announcements?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/friends?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/friends/presence?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/friend/0123456789abcdef?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/friend/0123456789abcdef/presence?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/webservices?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/webservice/5741031244955648/token?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/activeevent?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/user?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/user/presence?user=0123456789abcdef"
curl --no-buffer "http://[::1]:12345/api/znc/presence/events?user=0123456789abcdef"
```
#### splatnet2statink and flapg
The splatnet2statink and flapg APIs are 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 these APIs to generate some data that is required to authenticate the app. These APIs run the Nintendo Switch Online app in an Android emulator 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 [imink API](https://github.com/JoneWang/imink/wiki/imink-API-Documentation) can be used by setting the `NXAPI_ZNCA_API` environment variable to `imink`. (`NXAPI_ZNCA_API=imink nxapi nso ...`)
nxapi also includes a custom server using Frida on an Android device/emulator that can be used instead of these.
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.
### 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.
#### User
```sh
# Show the authenticated SplatNet 2 user
nxapi splatnet2 user
```
#### Download user records
```sh
# Download user records to the splatnet2 directory in nxapi's data path
# Data that already exists will not be redownloaded
nxapi splatnet2 dump-records
# Download user records to data/splatnet2
nxapi splatnet2 dump-records data/splatnet2
# Don't include user records (when downloading other data)
nxapi splatnet2 dump-records --no-user-records
# Include lifetime inkage challenge images
nxapi splatnet2 dump-records --challenges
# Include profile image (share button on the home page)
nxapi splatnet2 dump-records --profile-image
nxapi splatnet2 dump-records --profile-image --favourite-stage "Starfish Mainstage" --favourite-colour purple
# Download user records even if they already exist and haven't been updated
nxapi splatnet2 dump-records --no-new-records
# Include hero (Octo Canyon) records
# If this option is included hero records will always be downloaded even if they haven't been updated
nxapi splatnet2 dump-records --hero-records
# Only download hero records
nxapi splatnet2 dump-records --no-user-records --hero-records
# Include timeline (CPOD FM on the home page)
# If this option is included the timeline will always be downloaded even if it hasn't been updated
nxapi splatnet2 dump-records --timeline
# Only download the timeline
nxapi splatnet2 dump-records --no-user-records --timeline
```
#### Download battle/Salmon Run results
```sh
# Download battle and Salmon Run results to the splatnet2 directory in nxapi's data path
# Data that already exists will not be redownloaded
nxapi splatnet2 dump-results
# Download battle and Salmon Run results to data/splatnet2
nxapi splatnet2 dump-results data/splatnet2
# Include battle summary image (share button on the battles list)
nxapi splatnet2 dump-results --battle-summary-image
# Include battle result images (share button on the battle details page)
nxapi splatnet2 dump-results --battle-images
# Only download battle results
nxapi splatnet2 dump-results --no-coop
# Only download Salmon Run results
nxapi splatnet2 dump-results --no-battles
# Download summary data even if user records haven't been updated
# Individual battle results/images/Salmon Run results still won't be redownloaded if they exist
nxapi splatnet2 dump-results --no-check-updated
```
#### Monitor SplatNet 2 for new user records/battle/Salmon Run results
This will constantly check SplatNet 2 for new data.
```sh
# Watch for new battle and Salmon Run results and download them to the splatnet2 directory in nxapi's data path
nxapi splatnet2 monitor
# Watch for new battle and Salmon Run results and download them to data/splatnet2
nxapi splatnet2 monitor data/splatnet2
# Include profile image (share button on the home page)
nxapi splatnet2 monitor --profile-image
nxapi splatnet2 monitor --profile-image --favourite-stage "Starfish Mainstage" --favourite-colour purple
# Include battle summary image (share button on the battles list)
nxapi splatnet2 monitor --battle-summary-image
# Include battle result images (share button on the battle details page)
nxapi splatnet2 monitor --battle-images
# Only download battle results
nxapi splatnet2 monitor --no-coop
# Only download Salmon Run results
nxapi splatnet2 monitor --no-battles
# Set update interval to 1800 seconds (30 minutes)
nxapi splatnet2 monitor --update-interval 1800
```
SplatNet 2 monitoring can also be used with `nxapi nso notify` and `nxapi nso presence`. Data will only be downloaded from SplatNet 2 if the authenticated user is playing Splatoon 2 online.
This can be used with `nxapi nso presence --presence-url ...` (the presence URL must return the status of the user authenticating to SplatNet 2). When used with `--friend-nsaid` the friend's presence will be shared on Discord but the authenticated user's presence will still be used to check if SplatNet 2 data should be updated.
```sh
# Watch for new battle and Salmon Run results and download them to the splatnet2 directory in nxapi's data path
# All options support both the notify and presence commands
nxapi nso notify --splatnet2-monitor
nxapi nso presence --splatnet2-monitor
# Watch for new battle and Salmon Run results and download them to data/splatnet2
nxapi nso presence --splatnet2-monitor --splatnet2-monitor-directory data/splatnet2
nxapi nso presence --splatnet2-monitor --sn2-path data/splatnet2
# Include profile image (share button on the home page)
nxapi nso presence --splatnet2-monitor --splatnet2-monitor-profile-image
nxapi nso presence --splatnet2-monitor --sn2-profile-image
nxapi nso presence --splatnet2-monitor --splatnet2-monitor-profile-image --splatnet2-monitor-favourite-stage "Starfish Mainstage" --splatnet2-monitor-favourite-colour purple
nxapi nso presence --splatnet2-monitor --sn2-profile-image --sn2-favourite-stage "Starfish Mainstage" --sn2-favourite-colour purple
# Include battle summary image (share button on the battles list)
nxapi nso presence --splatnet2-monitor --splatnet2-monitor-battle-summary-image
nxapi nso presence --splatnet2-monitor --sn2-battle-summary-image
# Include battle result images (share button on the battle details page)
nxapi nso presence --splatnet2-monitor --splatnet2-monitor-battle-images
nxapi nso presence --splatnet2-monitor --sn2-battle-images
# Only download battle results
nxapi nso presence --splatnet2-monitor --no-splatnet2-monitor-coop
nxapi nso presence --splatnet2-monitor --no-sn2-coop
# Only download Salmon Run results
nxapi nso presence --splatnet2-monitor --no-splatnet2-monitor-battles
nxapi nso presence --splatnet2-monitor --no-sn2-battles
# Set update interval to 60 seconds
nxapi nso presence --splatnet2-monitor --splatnet2-monitor-update-interval 60
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.
#### User
```sh
# Show NookLink users in a table
nxapi nooklink users
# Show the authenticated NookLink user
nxapi nooklink user
# Show the authenticated NookLink user's island and other players
nxapi nooklink island
# Use a specific NookLink user linked to the selected Nintendo Account
# If more than 1 NookLink users exist by default the first user will be used
nxapi nooklink user --islander 0x0123456789abcdef
# --user can also be used to select a different Nintendo Account
nxapi nooklink user --user 0123456789abcdef
nxapi nooklink user --user 0123456789abcdef --islander 0x0123456789abcdef
```
#### Newspapers
```sh
# Show the latest newspaper issue in a table
nxapi nooklink newspaper
# JSON
nxapi nooklink newspaper --json
nxapi nooklink newspaper --json-pretty-print
# List newspaper issues in a table
nxapi nooklink newspapers
# JSON
nxapi nooklink newspapers --json
nxapi nooklink newspapers --json-pretty-print
# Show a specific newspaper issue in a table
nxapi nooklink newspaper 00000000-0000-0000-0000-000000000000
# JSON
nxapi nooklink newspaper 00000000-0000-0000-0000-000000000000 --json
nxapi nooklink newspaper 00000000-0000-0000-0000-000000000000 --json-pretty-print
```
#### Download newspapers
```sh
# Download all island newspapers to the nooklink directory in nxapi's data path
# Data that already exists will not be redownloaded
nxapi nooklink dump-newspapers
# Download all island newspapers to data/nooklink
nxapi nooklink dump-newspapers data/nooklink
```
#### Messages
```sh
# Send a message in an online Animal Crossing: New Horizons session
nxapi nooklink keyboard "Hello"
# Ask for a message interactively
nxapi nooklink keyboard
# List available reactions
nxapi nooklink reactions
# Send a reaction
nxapi nooklink post-reaction happyflower
```
### Nintendo Switch Parental Controls
#### Login to the Nintendo Switch Parental Controls app
```sh
# Interactive login
# Generates a link to login with a Nintendo Account, asks for the link then automatically gets a session token
nxapi pctl auth
# Login with an existing token
# Use with a token obtained via MITM the app, or with `nxapi pctl auth --no-auth`
# The same session token as for the Nintendo Switch Online app cannot be used
nxapi pctl token
# Get the authenticated user
nxapi pctl user
```
#### Nintendo Switch consoles
```sh
# Show Nintendo Switch consoles in a table
nxapi pctl devices
# JSON
nxapi pctl devices --json
nxapi pctl devices --json-pretty-print
```
#### Daily summaries
```sh
# Show daily summary data in a table
# Use `nxapi pctl devices` to get the device ID
nxapi pctl daily-summaries 0123456789abcdef
# JSON
nxapi pctl daily-summaries 0123456789abcdef --json
nxapi pctl daily-summaries 0123456789abcdef --json-pretty-print
```
#### Monthly summaries
```sh
# Show monthly summaries in a table
# Use `nxapi pctl devices` to get the device ID
nxapi pctl monthly-summaries 0123456789abcdef
# JSON
nxapi pctl monthly-summaries 0123456789abcdef --json
nxapi pctl monthly-summaries 0123456789abcdef --json-pretty-print
# Show data for the February 2022 monthly summary in a table
nxapi pctl monthly-summary 0123456789abcdef 2022-02
# JSON
nxapi pctl monthly-summary 0123456789abcdef 2022-02 --json
nxapi pctl monthly-summary 0123456789abcdef 2022-02 --json-pretty-print
```
#### Download summary data
```sh
# Download all daily and monthly summary data from all devices to the summaries directory in nxapi's data path
# Data that already exists will not be redownloaded
nxapi pctl dump-summaries
# Download all daily and monthly summary data from all devices to data/summaries
nxapi pctl dump-summaries data/summaries
# Download all daily and monthly summary data from a specific device
# Use `nxapi pctl devices` to get the device ID
# The `--device` option can be used multiple times
nxapi pctl dump-summaries --device 0123456789abcdef
```
### Misc. commands/options
#### Users
```sh
# Show all known Nintendo Accounts in a table
# This will only show cached data and does not make any requests to Nintendo servers
nxapi users list
# Use a specific user in a command
nxapi ... --user 0123456789abcdef
nxapi ... --token $NA_SESSION_TOKEN
# Set the default user for commands
nxapi users set 0123456789abcdef
# Remove all data for a user
nxapi users forget 0123456789abcdef
```
The information below is relevant to both the Electron app and command line. Some environment variables are also used when using nxapi as a JavaScript library.
#### Data location
@ -640,14 +206,34 @@ nxapi --data-path ./data ...
NXAPI_DATA_PATH=`pwd`/data nxapi ...
```
Platform | Default path
----------------|----------------
macOS | `Library/Application Support/nxapi-nodejs`
Windows | `%localappdata%\nxapi-nodejs\Data`
Linux | `$XDG_DATA_HOME/nxapi-nodejs` or `.local/share/nxapi-nodejs`
nxapi will also store cached update and configuration data. This location cannot be changed.
Platform | Cache path
----------------|----------------
macOS | `Library/Caches/nxapi-nodejs`
Windows | `%localappdata%\nxapi-nodejs\Cache`
Linux | `$XDG_CACHE_HOME/nxapi-nodejs` or `.cache/nxapi-nodejs`
The Electron app will also store other data in various locations.
#### Debug logs
Logging uses the `debug` package and can be controlled using the `DEBUG` environment variable. All nxapi logging uses the `nxapi` and `cli` namespaces.
Logging uses the [debug](https://github.com/debug-js/debug) package and can be controlled using the `DEBUG` environment variable. All nxapi logging uses the `nxapi`, `cli` and `app` namespaces.
```sh
# Show all debug logs from nxapi
DEBUG=nxapi:*,cli,cli:* nxapi ...
# Start the Electron app and show all debug logs from nxapi
DEBUG=nxapi:*,app,app:* nxapi app
DEBUG=nxapi:*,app,app:* .../Nintendo\ Switch\ Online.app/Contents/MacOS/Nintendo\ Switch\ Online
# Show all API requests
DEBUG=nxapi:api:* nxapi ...
@ -655,61 +241,166 @@ DEBUG=nxapi:api:* nxapi ...
DEBUG=* nxapi ...
```
#### znca API server
By default all nxapi logs will be written to a platform-specific location:
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.
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 requires:
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.
- 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
nxapi logs may contain sensitive information such as Nintendo Account access tokens.
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}"
# 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 ...
```
#### .env file
#### 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.
### Links
This can be used with the Electron app (including when using the packaged version).
nxapi doesn't store any data itself when used as a TypeScript/JavaScript library, and doesn't attempt to read any `.env` files, however environment variables will still be used. If you want to read environment variables from a file you can use the [dotenv](https://github.com/motdotla/dotenv) and [dotenv-expand](https://github.com/motdotla/dotenv-expand) packages, or run `source .env` before running your process.
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 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 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
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.
```ts
import { addUserAgent } from 'nxapi';
addUserAgent('your-script/1.0.0 (+https://github.com/...)');
```
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).
<a name="splatnet2statink-and-flapg"></a>
### Coral client authentication
[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).
> 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.
This is really annoying. Initially the Nintendo Switch Online app didn't perform any sort of client attestation at all, then Nintendo added a HMAC of the id_token, timestamp and request ID to app/web service login requests, using a secret key embedded in the app, which was soon discovered. Nintendo later updated the app to use a native library (`libvoip`, which is also used for the app's VoIP features) to do this, and still no one knows how it works. (To make things even more confusing, the function, `gen_audio_h`/`gen_audio_h2`, always returns a different result, even when given the same inputs.)
The reason Nintendo added this is probably to try and stop people automating access to their app's API. I really hope that's wrong though, as then Nintendo would be prioritising that over account security, as most people seem ok with sharing account credentials to access the API. (And it's not stopping anyone accessing the API outside of the app anyway.)
[**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
- splatnet2statink and flapg docs
- https://github.com/frozenpandaman/splatnet2statink/wiki/api-docs
- 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~~
- https://github.com/JoneWang/imink/wiki/imink-API-Documentation - imink API docs
- HTTP debugging proxies
- Proxyman - https://proxyman.io
- mitmproxy - https://mitmproxy.org
- HTTP clients
- Paw - https://paw.cloud
- Disabling TLS certificate validation (entirely) with Frida on Android
- https://httptoolkit.tech/blog/frida-certificate-pinning/
- Other Discord Rich Presence implementations (that use znc)
- Other Discord Rich Presence implementations (that use Coral)
- https://github.com/MCMi460/NSO-RPC
- https://github.com/Quark064/NSO-Discord-Integration
- https://github.com/AAGaming00/acnhrp - doesn't use znc, 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 znc/web services
- 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)

View File

@ -1,2 +0,0 @@
#!/usr/bin/env sh
"$(dirname "$0")/../node_modules/.bin/node" "$(dirname "$0")/nxapi.js" $@

View File

@ -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');

View File

@ -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

View File

@ -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>

74
docker-compose.yml Normal file
View File

@ -0,0 +1,74 @@
version: '3'
services:
#
# Coral/znc proxy
#
znc-proxy:
build: .
command: nso http-server --listen \[::]:80
restart: unless-stopped
labels:
traefik.enable: true
traefik.http.routers.nxapi-znc.entrypoints: websecure
traefik.http.routers.nxapi-znc.rule: Host(`${TRAEFIK_HOST:-nxapi.ta.fancy.org.uk}`) && PathPrefix(`/api/znc/`)
traefik.http.routers.nxapi-znc.tls: true
traefik.http.services.nxapi-znc.loadbalancer.server.port: 80
environment:
DEBUG: '*,-express:*,-body-parser:*'
# ZNCA_API_URL: http://znca-api/api/znca
env_file: .env
volumes:
- data:/data
#
# 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
profiles:
- presence-server
labels:
traefik.enable: true
traefik.http.routers.nxapi-presence.entrypoints: websecure
traefik.http.routers.nxapi-presence.rule: Host(`${TRAEFIK_HOST:-nxapi.ta.fancy.org.uk}`) && (Path(`/api/presence`) || PathPrefix(`/api/presence/`) || PathPrefix(`/api/splatnet3/resources/`))
traefik.http.routers.nxapi-presence.tls: true
traefik.http.services.nxapi-presence.loadbalancer.server.port: 80
environment:
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
volumes:
data:

760
docs/cli.md Normal file
View File

@ -0,0 +1,760 @@
Nintendo Switch Online
---
### Login to the Nintendo Switch Online app
```sh
# Interactive login
# Generates a link to login with a Nintendo Account, asks for the link then automatically gets a session token
nxapi nso auth
# Login with an existing token
# Use with a token obtained via MITM the app, or with `nxapi nso auth --no-auth`
# The same session token as for the Nintendo Switch Parental Controls app cannot be used
nxapi nso token
# Get the authenticated user
nxapi nso user
```
### Discord Presence
```sh
# Show the authenticated user's presence
nxapi nso presence
# Show a friend's presence
# Use `nxapi nso friends` to show all friend's Nintendo Switch account IDs
nxapi nso presence --friend-nsaid 0123456789abcdef
# Show the authenticated user's friend code in Discord
nxapi nso presence --friend-code
nxapi nso presence --friend-code -
# Show a custom friend code in Discord
# Use this if you are showing presence of a friend of the authenticated user
nxapi nso presence --friend-code 0000-0000-0000
nxapi nso presence --friend-code SW-0000-0000-0000
# Show inactive presence
# This will show a "Not playing" status if any consoles linked to the user's account is online but the user
# is not selected in a game
# Don't enable this if you are not the only user of all consoles linked to your account
nxapi nso presence --show-inactive-presence
# Also show friend notifications (see below)
nxapi nso presence --friend-notifications
nxapi nso presence --user-notifications --friend-notifications
nxapi nso presence --user-notifications
# Set update interval to 60 seconds
nxapi nso presence --update-interval 60
# Fetch presence from a custom URL (see `nxapi nso http-server`)
nxapi nso presence --presence-url "http://[::1]:12345/api/znc/user/presence"
nxapi nso presence --presence-url "http://[::1]:12345/api/znc/friend/0123456789abcdef/presence"
```
### Friend presence notifications
This uses node-notifier to display native desktop notifications.
```sh
# Show notifications for all friends
nxapi nso notify
# Show notifications for all friends + the current user
nxapi nso notify --user-notifications
# Show notifications for only the current user
nxapi nso notify --user-notifications --no-friend-notifications
# Set update interval to 60 seconds
nxapi nso notify --update-interval 60
```
### Friends
```sh
# Show Nintendo Switch friends in a table
nxapi nso friends
# JSON
nxapi nso friends --json
nxapi nso friends --json-pretty-print
```
### Friend codes and friend requests
```sh
# Get a URL that can be used to open your profile in the Nintendo Switch Online app and send a friend request
# This prints an object which includes your friend code and the URL (which contains your friend code)
nxapi nso friendcode
# JSON
nxapi nso friendcode --json
nxapi nso friendcode --json-pretty-print
# Look up a user using a friend code
nxapi nso lookup 0000-0000-0000
# JSON
nxapi nso lookup 0000-0000-0000 --json
nxapi nso lookup 0000-0000-0000 --json-pretty-print
# Send a friend request
nxapi nso add-friend 0000-0000-0000
```
### Nintendo Switch Online app announcements/alerts
```sh
# Show app announcements in a table
nxapi nso announcements
# JSON
nxapi nso announcements --json
nxapi nso announcements --json-pretty-print
```
### Web services/game-specific services
```sh
# Show web services in a table
nxapi nso webservices
# JSON
nxapi nso webservices --json
nxapi nso webservices --json-pretty-print
# Get an access token for a web service
# This should be sent with the first request to the web service URL in the `x-gamewebtoken` header
nxapi nso webservicetoken 5741031244955648
nxapi nso webservicetoken 5741031244955648 --json
nxapi nso webservicetoken 5741031244955648 --json-pretty-print
```
### API proxy server
Use this to access the Nintendo Switch Online app API from a browser/other HTTP client easily.
```sh
# Start the server listening on all interfaces on a random port
nxapi nso http-server
# Start the server listening on a specific address/port
# The `--listen` option can be used multiple times
nxapi nso http-server --listen "[::1]:12345"
# Use the API proxy server in other commands
nxapi nso ... --znc-proxy-url "http://[::1]:12345/api/znc"
ZNC_PROXY_URL=http://[::1]:12345/api/znc nxapi nso ...
# Start the server using another API proxy server
nxapi nso http-server --znc-proxy-url "http://[::1]:12345/api/znc"
ZNC_PROXY_URL=http://[::1]:12345/api/znc nxapi nso http-server
# Allow requests without a Nintendo Account session token
# Anyone connecting to the API proxy server will be able to use any already authenticated user with their Nintendo Account ID
# Don't set this if anyone can connect to the server!
nxapi nso http-server --listen "[::1]:12345" --no-require-token
# Limit the frequency of friends/announcements/web services requests to 60 seconds
nxapi nso http-server --update-interval 60
# Make API requests using curl
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/auth"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/announcements"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/friends"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/friends/presence"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/friend/0123456789abcdef"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/friend/0123456789abcdef/presence"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/friendcode"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/friendcode/0000-0000-0000"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/webservices"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/webservice/5741031244955648/token"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/activeevent"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/user"
curl --header "Authorization: na $NA_SESSION_TOKEN" "http://[::1]:12345/api/znc/user/presence"
# Watch for changes to the user and all friends presence
curl --header "Authorization: na $NA_SESSION_TOKEN" --no-buffer "http://[::1]:12345/api/znc/presence/events"
# Make API requests using curl without a session token
# The `--no-require-token` must be set when running the server, and the user must have previously authenticated to the server, either with the API proxy server or using commands on the server
curl "http://[::1]:12345/api/znc/announcements?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/friends?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/friends/presence?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/friend/0123456789abcdef?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/friend/0123456789abcdef/presence?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/friendcode?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/friendcode/0000-0000-0000?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/webservices?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/webservice/5741031244955648/token?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/activeevent?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/user?user=0123456789abcdef"
curl "http://[::1]:12345/api/znc/user/presence?user=0123456789abcdef"
curl --no-buffer "http://[::1]:12345/api/znc/presence/events?user=0123456789abcdef"
```
SplatNet 2
---
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
```sh
# Show the authenticated SplatNet 2 user
nxapi splatnet2 user
```
### Download user records
```sh
# Download user records to the splatnet2 directory in nxapi's data path
# Data that already exists will not be redownloaded
nxapi splatnet2 dump-records
# Download user records to data/splatnet2
nxapi splatnet2 dump-records data/splatnet2
# Don't include user records (when downloading other data)
nxapi splatnet2 dump-records --no-user-records
# Include lifetime inkage challenge images
nxapi splatnet2 dump-records --challenges
# Include profile image (share button on the home page)
nxapi splatnet2 dump-records --profile-image
nxapi splatnet2 dump-records --profile-image --favourite-stage "Starfish Mainstage" --favourite-colour purple
# Download user records even if they already exist and haven't been updated
nxapi splatnet2 dump-records --no-new-records
# Include hero (Octo Canyon) records
# If this option is included hero records will always be downloaded even if they haven't been updated
nxapi splatnet2 dump-records --hero-records
# Only download hero records
nxapi splatnet2 dump-records --no-user-records --hero-records
# Include timeline (CPOD FM on the home page)
# If this option is included the timeline will always be downloaded even if it hasn't been updated
nxapi splatnet2 dump-records --timeline
# Only download the timeline
nxapi splatnet2 dump-records --no-user-records --timeline
```
### Download battle/Salmon Run results
```sh
# Download battle and Salmon Run results to the splatnet2 directory in nxapi's data path
# Data that already exists will not be redownloaded
nxapi splatnet2 dump-results
# Download battle and Salmon Run results to data/splatnet2
nxapi splatnet2 dump-results data/splatnet2
# Include battle summary image (share button on the battles list)
nxapi splatnet2 dump-results --battle-summary-image
# Include battle result images (share button on the battle details page)
nxapi splatnet2 dump-results --battle-images
# Only download battle results
nxapi splatnet2 dump-results --no-coop
# Only download Salmon Run results
nxapi splatnet2 dump-results --no-battles
# Download summary data even if user records haven't been updated
# Individual battle results/images/Salmon Run results still won't be redownloaded if they exist
nxapi splatnet2 dump-results --no-check-updated
```
### Monitor SplatNet 2 for new user records/battle/Salmon Run results
This will constantly check SplatNet 2 for new data.
```sh
# Watch for new battle and Salmon Run results and download them to the splatnet2 directory in nxapi's data path
nxapi splatnet2 monitor
# Watch for new battle and Salmon Run results and download them to data/splatnet2
nxapi splatnet2 monitor data/splatnet2
# Include profile image (share button on the home page)
nxapi splatnet2 monitor --profile-image
nxapi splatnet2 monitor --profile-image --favourite-stage "Starfish Mainstage" --favourite-colour purple
# Include battle summary image (share button on the battles list)
nxapi splatnet2 monitor --battle-summary-image
# Include battle result images (share button on the battle details page)
nxapi splatnet2 monitor --battle-images
# Only download battle results
nxapi splatnet2 monitor --no-coop
# Only download Salmon Run results
nxapi splatnet2 monitor --no-battles
# Set update interval to 1800 seconds (30 minutes)
nxapi splatnet2 monitor --update-interval 1800
```
SplatNet 2 monitoring can also be used with `nxapi nso notify` and `nxapi nso presence`. Data will only be downloaded from SplatNet 2 if the authenticated user is playing Splatoon 2 online.
This can be used with `nxapi nso presence --presence-url ...` (the presence URL must return the status of the user authenticating to SplatNet 2). When used with `--friend-nsaid` the friend's presence will be shared on Discord but the authenticated user's presence will still be used to check if SplatNet 2 data should be updated.
```sh
# Watch for new battle and Salmon Run results and download them to the splatnet2 directory in nxapi's data path
# All options support both the notify and presence commands
nxapi nso notify --splatnet2-monitor
nxapi nso presence --splatnet2-monitor
# Watch for new battle and Salmon Run results and download them to data/splatnet2
nxapi nso presence --splatnet2-monitor --splatnet2-monitor-directory data/splatnet2
nxapi nso presence --splatnet2-monitor --sn2-path data/splatnet2
# Include profile image (share button on the home page)
nxapi nso presence --splatnet2-monitor --splatnet2-monitor-profile-image
nxapi nso presence --splatnet2-monitor --sn2-profile-image
nxapi nso presence --splatnet2-monitor --splatnet2-monitor-profile-image --splatnet2-monitor-favourite-stage "Starfish Mainstage" --splatnet2-monitor-favourite-colour purple
nxapi nso presence --splatnet2-monitor --sn2-profile-image --sn2-favourite-stage "Starfish Mainstage" --sn2-favourite-colour purple
# Include battle summary image (share button on the battles list)
nxapi nso presence --splatnet2-monitor --splatnet2-monitor-battle-summary-image
nxapi nso presence --splatnet2-monitor --sn2-battle-summary-image
# Include battle result images (share button on the battle details page)
nxapi nso presence --splatnet2-monitor --splatnet2-monitor-battle-images
nxapi nso presence --splatnet2-monitor --sn2-battle-images
# Only download battle results
nxapi nso presence --splatnet2-monitor --no-splatnet2-monitor-coop
nxapi nso presence --splatnet2-monitor --no-sn2-coop
# Only download Salmon Run results
nxapi nso presence --splatnet2-monitor --no-splatnet2-monitor-battles
nxapi nso presence --splatnet2-monitor --no-sn2-battles
# Set update interval to 60 seconds
nxapi nso presence --splatnet2-monitor --splatnet2-monitor-update-interval 60
nxapi nso presence --splatnet2-monitor --sn2-update-interval 60
```
NookLink
---
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
```sh
# Show NookLink users in a table
nxapi nooklink users
# Show the authenticated NookLink user
nxapi nooklink user
# Show the authenticated NookLink user's island and other players
nxapi nooklink island
# Use a specific NookLink user linked to the selected Nintendo Account
# If more than 1 NookLink users exist by default the first user will be used
nxapi nooklink user --islander 0x0123456789abcdef
# --user can also be used to select a different Nintendo Account
nxapi nooklink user --user 0123456789abcdef
nxapi nooklink user --user 0123456789abcdef --islander 0x0123456789abcdef
```
### Newspapers
```sh
# Show the latest newspaper issue in a table
nxapi nooklink newspaper
# JSON
nxapi nooklink newspaper --json
nxapi nooklink newspaper --json-pretty-print
# List newspaper issues in a table
nxapi nooklink newspapers
# JSON
nxapi nooklink newspapers --json
nxapi nooklink newspapers --json-pretty-print
# Show a specific newspaper issue in a table
nxapi nooklink newspaper 00000000-0000-0000-0000-000000000000
# JSON
nxapi nooklink newspaper 00000000-0000-0000-0000-000000000000 --json
nxapi nooklink newspaper 00000000-0000-0000-0000-000000000000 --json-pretty-print
```
### Download newspapers
```sh
# Download all island newspapers to the nooklink directory in nxapi's data path
# Data that already exists will not be redownloaded
nxapi nooklink dump-newspapers
# Download all island newspapers to data/nooklink
nxapi nooklink dump-newspapers data/nooklink
```
### Messages
```sh
# Send a message in an online Animal Crossing: New Horizons session
nxapi nooklink keyboard "Hello"
# Ask for a message interactively
nxapi nooklink keyboard
# List available reactions
nxapi nooklink reactions
# Send a reaction
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
---
### Login to the Nintendo Switch Parental Controls app
```sh
# Interactive login
# Generates a link to login with a Nintendo Account, asks for the link then automatically gets a session token
nxapi pctl auth
# Login with an existing token
# Use with a token obtained via MITM the app, or with `nxapi pctl auth --no-auth`
# The same session token as for the Nintendo Switch Online app cannot be used
nxapi pctl token
# Get the authenticated user
nxapi pctl user
```
### Nintendo Switch consoles
```sh
# Show Nintendo Switch consoles in a table
nxapi pctl devices
# JSON
nxapi pctl devices --json
nxapi pctl devices --json-pretty-print
```
### Daily summaries
```sh
# Show daily summary data in a table
# Use `nxapi pctl devices` to get the device ID
nxapi pctl daily-summaries 0123456789abcdef
# JSON
nxapi pctl daily-summaries 0123456789abcdef --json
nxapi pctl daily-summaries 0123456789abcdef --json-pretty-print
```
### Monthly summaries
```sh
# Show monthly summaries in a table
# Use `nxapi pctl devices` to get the device ID
nxapi pctl monthly-summaries 0123456789abcdef
# JSON
nxapi pctl monthly-summaries 0123456789abcdef --json
nxapi pctl monthly-summaries 0123456789abcdef --json-pretty-print
# Show data for the February 2022 monthly summary in a table
nxapi pctl monthly-summary 0123456789abcdef 2022-02
# JSON
nxapi pctl monthly-summary 0123456789abcdef 2022-02 --json
nxapi pctl monthly-summary 0123456789abcdef 2022-02 --json-pretty-print
```
### Download summary data
```sh
# Download all daily and monthly summary data from all devices to the summaries directory in nxapi's data path
# Data that already exists will not be redownloaded
nxapi pctl dump-summaries
# Download all daily and monthly summary data from all devices to data/summaries
nxapi pctl dump-summaries data/summaries
# Download all daily and monthly summary data from a specific device
# Use `nxapi pctl devices` to get the device ID
# The `--device` option can be used multiple times
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
---
### Users
```sh
# Show all known Nintendo Accounts in a table
# This will only show cached data and does not make any requests to Nintendo servers
nxapi users list
# Use a specific user in a command
nxapi ... --user 0123456789abcdef
nxapi ... --token $NA_SESSION_TOKEN
# Set the default user for commands
nxapi users set 0123456789abcdef
# Remove all data for a user
nxapi users forget 0123456789abcdef
```
### Electron app
When installing nxapi from source the app can be run using this command:
```sh
nxapi app
```
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 imink/flapg APIs to generate `f` parameters for authentication.
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
View File

@ -0,0 +1 @@
index.md

122
docs/lib/coral.md Normal file
View File

@ -0,0 +1,122 @@
`nxapi/coral`
---
Using this module requires sending an authentication token (as a JSON Web Token, containing account identifiers itself) to third-party APIs. If you use this module in your own project, you must 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, and explain this to your users and provide a link to the [Coral client authentication](../../README.md#coral-client-authentication) section of nxapi's README. Do not contact any service without the user's informed consent.
### `CoralApi`
> This is exported as `default`.
Coral 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/coral.ts](../../src/api/coral.ts), [src/common/auth/coral.ts](../../src/common/auth/coral.ts) and [src/cli/nso](../../src/cli/nso) for examples of using this API. If you need any help using this API ask in [#coral](https://discordapp.com/channels/998657768594608138/998662583433318440) on Discord.
You should review HTTP captures of the Nintendo Switch Online app and attempt to match the behaviour of Nintendo's official app. For example, when opening the app it will fetch announcements, friends, web services and the active event; your project should match this.
#### `CoralApi.createWithSessionToken`
Authenticate to the Coral API using a Nintendo Account session token.
> This function should not be called often. If your project will create a new CoralApi object again for the same user before the Coral authentication token expires (usually after two hours), you must store the `data` object this returns and use `CoralApi.createWithSavedToken`.
```ts
import CoralApi, { CoralAuthData } from 'nxapi/coral';
const na_session_token: string;
const {nso, data} = await CoralApi.createWithSessionToken(na_session_token);
// nso instanceof CoralApi
// data is a plain object of type CoralAuthData
// data should be saved and reused
```
#### `CoralApi.createWithSavedToken`
Create a CoralApi instance using cached data from `CoralApi.createWithSessionToken` or `CoralApi.loginWithSessionToken`.
```ts
import CoralApi, { CoralAuthData } from 'nxapi/coral';
const auth_data: CoralAuthData;
const coral = CoralApi.createWithSavedToken(auth_data);
// coral instanceof CoralApi
```
#### `CoralApi.renewToken`
Renew the Coral authentication token. This should be called if any API requests throw a token expired error. This updates the token of the `CoralApi` object and returns a partial `CoralAuthData` object, that should replace properties of the object passed to `CoralApi.createWithSavedToken`.
> This function should not be called often. You must store the object this returns (replacing properties of the previous `CoralAuthData` object).
```ts
import CoralApi, { CoralAuthData, PartialCoralAuthData } from 'nxapi/coral';
const coral: CoralApi;
const auth_data: CoralAuthData;
const na_session_token: string;
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);
// new_auth_data is a plain object of type CoralAuthData
// 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.
The API proxy will cache data and will request certain data together to match Nintendo's app, however you should still try to only make requests that would match the behaviour of Nintendo's app as with `CoralApi`.
#### `new ZncProxyApi`
Create a `ZncProxyApi` instance with a Nintendo Account session token.
Because the API proxy server handles Nintendo Account authentication, you do not need to store any data to reuse later, and should call the constructor directly instead of using a helper function.
```ts
import { ZncProxyApi } from 'nxapi/coral';
const znc_proxy_url: string;
const na_session_token: string;
const coral = new ZncProxyApi(znc_proxy_url, na_session_token);
```
### API types
`nxapi/coral` exports all API types from [src/api/coral-types.ts](../../src/api/coral-types.ts).
### Coral client authentication
`nxapi/coral` exports it's API library and types for various APIs used for generating `f` tokens used to authenticate to the Coral API. These functions should generally not be required as they are used by nxapi internally.

196
docs/lib/index.md Normal file
View File

@ -0,0 +1,196 @@
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 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.
```sh
# From registry.npmjs.com
npm install nxapi
# From gitlab.fancy.org.uk
npm install --registry https://gitlab.fancy.org.uk/api/v4/packages/npm/ @samuel/nxapi
# From npm.pkg.github.com
npm install --registry https://npm.pkg.github.com @samuelthomas2774/nxapi
# From gitlab.com
npm install --registry https://gitlab.com/api/v4/packages/npm/ @samuelthomas2774/nxapi
```
### `nxapi`
This module contains some generic utility functions and types.
#### `getTitleIdFromEcUrl`
This function takes a https://ec.nintendo.com/apps/... URL (provided by some Nintendo APIs) and returns the title ID in the URL. `null` is returned if the URL is not a valid Nintendo eShop URL containing a title ID.
```ts
import { getTitleIdFromEcUrl } from 'nxapi';
const title_id = getTitleIdFromEcUrl('https://ec.nintendo.com/apps/0100f8f0000a2000/GB?lang=en-GB');
// title_id === '0100f8f0000a2000'
```
If you are using Nintendo eShop links but do not know the user's Nintendo eShop region, you may use nxapi's Nintendo eShop region selection page.
> https://fancy.org.uk/api/nxapi/title/0100f8f0000a2000/redirect
Please set an appropriate `source` query string parameter containing your project's name and version if you generate these links automatically.
> https://fancy.org.uk/api/nxapi/title/0100f8f0000a2000/redirect?source=myproject-1.0.0
#### `ErrorResponse`
An instance of this class is thrown when an invalid or failure response is received. This class extends from `Error`.
Note that this is only used when the HTTP response is received correctly (including for non-2xx status codes). If a request fails due to a network error or another reason node-fetch will throw a different error.
```ts
import { ErrorResponse } from 'nxapi';
try {
// ...
} catch (err) {
if (err instanceof ErrorResponse) {
// err.body is the response data as a string
// err.data is the decoded JSON response data, or undefined if JSON decoding fails
// err.response is the Response object from node-fetch
// err.name, err.message and err.stack are inherited from Error
}
}
```
#### `addUserAgent`
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.
```ts
import { version } from 'nxapi';
// version === '1.3.0'
```
### `nxapi/coral`
This module exports the Coral (Nintendo Switch Online app) API library and types.
[See docs/lib/coral.md.](coral.md)
### `nxapi/moon`
This module exports the Moon (Nintendo Switch Parental Controls app) API library and types.
[See docs/lib/moon.md.](moon.md)
### `nxapi/splatnet2`
This module exports the SplatNet 2 API library and types, as well as functions for calculating X Rank seasons, as this is done by the SplatNet 2 web app, not the API.
[See docs/lib/splatnet2.md.](splatnet2.md)
### `nxapi/nooklink`
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)

86
docs/lib/moon.md Normal file
View File

@ -0,0 +1,86 @@
`nxapi/moon`
---
### `MoonApi`
> This is exported as `default`.
Moon 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/moon.ts](../../src/api/moon.ts), [src/common/auth/moon.ts](../../src/common/auth/moon.ts) and [src/cli/pctl](../../src/cli/pctl) for examples of using this API. If you need any help using this API ask in [#moon](https://discordapp.com/channels/998657768594608138/998662782163628082) on Discord.
You should review HTTP captures of the Nintendo Switch Parental Controls app and attempt to match the behaviour of Nintendo's official app.
#### `MoonApi.createWithSessionToken`
Authenticate to the Moon API using a Nintendo Account session token.
> This function should not be called often. If your project will create a new MoonApi object again for the same user before the Moon authentication token expires (usually after 15 minutes), you must store the `data` object this returns and use `MoonApi.createWithSavedToken`.
```ts
import MoonApi, { MoonAuthData } from 'nxapi/moon';
const na_session_token: string;
const {moon, data} = await MoonApi.createWithSessionToken(na_session_token);
// moon instanceof MoonApi
// data is a plain object of type MoonAuthData
// data should be saved and reused
```
#### `MoonApi.createWithSavedToken`
Create a MoonApi instance using cached data from `MoonApi.createWithSessionToken` or `MoonApi.loginWithSessionToken`.
```ts
import MoonApi, { MoonAuthData } from 'nxapi/moon';
const auth_data: MoonAuthData;
const moon = MoonApi.createWithSavedToken(auth_data);
// moon instanceof MoonApi
```
#### `MoonApi.renewToken`
Renew the Moon authentication token. This should be called if any API requests throw a token expired error. This updates the token of the `MoonApi` object and returns a new `MoonAuthData` object.
```ts
import MoonApi, { MoonAuthData } from 'nxapi/moon';
const moon: MoonApi;
const na_session_token: string;
const data = await moon.renewToken(na_session_token);
// data is a plain object of type MoonAuthData
// 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).

171
docs/lib/nooklink.md Normal file
View File

@ -0,0 +1,171 @@
`nxapi/nooklink`
---
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.
### `NooklinkApi`
> This is exported as `default`.
NookLink NSA-level 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/nooklink.ts](../../src/api/nooklink.ts), [src/common/auth/nooklink.ts](../../src/common/auth/nooklink.ts) and [src/cli/nooklink](../../src/cli/nooklink) for examples of using this API. If you need any help using this API ask in [#nooklink](https://discordapp.com/channels/998657768594608138/998664335062741032) on Discord.
You should review HTTP captures of NookLink in the Nintendo Switch Online app and attempt to match the behaviour of Nintendo's official app.
#### `NooklinkApi.createWithCoral`
Authenticate to NookLink using a `CoralApi` instance.
> This function should not be called often. If your project will create a new NooklinkApi object again for the same user before the NookLink authentication token expires (usually after two hours), you must store the `data` object this returns and use `NooklinkApi.createWithSavedToken`.
```ts
import CoralApi, { CoralAuthData } from 'nxapi/coral';
import NooklinkApi, { NooklinkAuthData } from 'nxapi/nooklink';
const coral: CoralApi;
const coral_auth_data: CoralAuthData;
const {nooklink, data} = await NooklinkApi.createWithCoral(coral, coral_auth_data.user);
// nooklink instanceof NooklinkApi
// data is a plain object of type NooklinkAuthData
// data should be saved and reused
```
#### `NooklinkApi.createWithSavedToken`
Create a NooklinkApi instance using cached data from `NooklinkApi.createWithCoral` or `NooklinkApi.loginWithCoral`.
```ts
import NooklinkApi, { NooklinkAuthData } from 'nxapi/nooklink';
const auth_data: NooklinkAuthData;
const nooklink = NooklinkApi.createWithSavedToken(auth_data);
// nooklink instanceof NooklinkApi
```
#### `NooklinkApi.getUsers`
Retrieves a list of available NookLink-enabled users.
```ts
import NooklinkApi, { Users } from 'nxapi/nooklink';
const nooklink: Nooklink;
const users = await nooklink.getUsers();
// users is a plain object of type Users
```
#### `NooklinkApi.createUserClient`
Authenticate to NookLink and create a NooklinkUser instance.
```ts
import NooklinkApi, { NooklinkUserApi, NooklinkUserAuthData } from 'nxapi/nooklink';
const nooklink: Nooklink;
const user_id: string;
const {nooklinkuser, data} = await nooklink.createUserClient(user_id);
// nooklinkuser instanceof NooklinkUserApi
// 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.
Most of this API is intentionally undocumented. Read the source code at [src/api/nooklink.ts](../../src/api/nooklink.ts), [src/common/auth/nooklink.ts](../../src/common/auth/nooklink.ts) and [src/cli/nooklink](../../src/cli/nooklink) for examples of using this API. If you need any help using this API ask in [#nooklink](https://discordapp.com/channels/998657768594608138/998664335062741032) on Discord.
You should review HTTP captures of NookLink in the Nintendo Switch Online app and attempt to match the behaviour of Nintendo's official app.
#### `NooklinkUserApi.createWithSavedToken`
Create a NooklinkUserApi instance using cached data from `NooklinkApi.createUserClient`.
```ts
import { NooklinkUserApi, NooklinkUserAuthData } from 'nxapi/nooklink';
const auth_data: NooklinkAuthData;
const nooklinkuser = NooklinkUserApi.createWithSavedToken(auth_data);
// nooklinkuser instanceof NooklinkApi
```
#### `NooklinkUserApi.createWithCliTokenData`
Create a NooklinkUserApi instance using the output of the `nxapi nooklink user-token --json` command.
```ts
import { NooklinkUserApi, NooklinkUserCliTokenData } from 'nxapi/nooklink';
const data: NooklinkUserCliTokenData;
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).

190
docs/lib/splatnet2.md Normal file
View File

@ -0,0 +1,190 @@
`nxapi/splatnet2`
---
### `SplatNet2Api`
> This is exported as `default`.
SplatNet 2 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/splatnet2.ts](../../src/api/splatnet2.ts), [src/common/auth/splatnet2.ts](../../src/common/auth/splatnet2.ts) and [src/cli/splatnet2](../../src/cli/splatnet2) for examples of using this API. If you need any help using this API ask in [#splatnet2](https://discordapp.com/channels/998657768594608138/998663658781552670) on Discord.
You should review HTTP captures of SplatNet 2 in the Nintendo Switch Online app and attempt to match the behaviour of Nintendo's official app.
#### `SplatNet2Api.createWithCoral`
Authenticate to SplatNet 2 using a `CoralApi` instance.
> This function should not be called often. If your project will create a new SplatNet2Api object again for the same user before the SplatNet 2 session expires (usually 24 hours after last use), you must store the `data` object this returns and use `SplatNet2Api.createWithSavedToken`.
```ts
import CoralApi, { CoralAuthData } from 'nxapi/coral';
import SplatNet2Api, { SplatNet2AuthData } from 'nxapi/splatnet2';
const coral: CoralApi;
const coral_auth_data: CoralAuthData;
const {splatnet, data} = await SplatNet2Api.createWithCoral(coral, coral_auth_data.user);
// splatnet instanceof SplatNet2Api
// data is a plain object of type SplatNet2AuthData
// data should be saved and reused
```
#### `SplatNet2Api.createWithSavedToken`
Create a SplatNet2Api instance using cached data from `SplatNet2Api.createWithCoral` or `SplatNet2Api.loginWithCoral`.
```ts
import SplatNet2Api, { SplatNet2AuthData } from 'nxapi/splatnet2';
const auth_data: SplatNet2AuthData;
const splatnet = SplatNet2Api.createWithSavedToken(auth_data);
// splatnet instanceof SplatNet2Api
```
#### `SplatNet2Api.createWithCliTokenData`
Create a SplatNet2Api instance using the output of the `nxapi splatnet2 token --json` command.
```ts
import SplatNet2Api, { SplatNet2CliTokenData } from 'nxapi/splatnet2';
const data: SplatNet2CliTokenData;
const splatnet = SplatNet2Api.createWithCliTokenData(data);
// splatnet instanceof SplatNet2Api
```
#### `SplatNet2Api.createWithIksmSession`
Create a SplatNet2Api instance with an `iksm_session` and `unique_id` value.
> `SplatNet2Api.createWithCoral`/`SplatNet2Api.createWithSavedToken` or `SplatNet2Api.createWithCliTokenData` should be preferred over this as they are better able to match SplatNet 2's behaviour.
```ts
import SplatNet2Api from 'nxapi/splatnet2';
const iksm_session: string;
const unique_id: string;
const splatnet = SplatNet2Api.createWithIksmSession(iksm_session, unique_id);
// splatnet instanceof SplatNet2Api
```
### API types
`nxapi/splatnet2` exports all API types from [src/api/splatnet2-types.ts](../../src/api/splatnet2-types.ts).
### `toLeagueId`
Converts a `Date` and `LeagueType` to a string used in league ranking requests (`/league_match_ranking/{id}/{region}` or `SplatNet2Api.getLeagueMatchRanking`).
This function does not usually need to be used with `SplatNet2Api.getLeagueMatchRanking`, as a `Date` and `LeagueType` can be passed directly to it.
```ts
import { LeagueType, toLeagueId } from 'nxapi/splatnet2';
const league_id = toLeagueId(new Date(Date.UTC(2022, 0, 1, 0)), LeagueType.TEAM);
// league_id === '22010100T'
```
### `toXRankSeasonId`
Converts a year and month to a string used in X Rank leaderboard requests (`/x_power_ranking/{season}/{summary/rule}?page={page}` or `SplatNet2Api.getXPowerRankingSummary`/`SplatNet2Api.getXPowerRankingLeaderboard`).
Months in this function start from 1, instead of 0 like `Date`s.
This function does not usually need to be used with `SplatNet2Api.getXPowerRankingSummary` or `SplatNet2Api.getXPowerRankingLeaderboard`, as an `XRankSeason`/`Date` and `XPowerRankingRule` can be passed directly to it.
```ts
import { toXRankSeasonId } from 'nxapi/splatnet2';
const season_id = toXRankSeasonId(2022, 1);
// season_id === '220101T00_220201T00'
```
### `getXRankSeasons`
Returns an iterator that yields all X Rank seasons up to the current season according to the system date.
By default this will start from the current season and continue to the first season. Setting the first argument to `true` will cause this function to start from the first season and continue to the current season.
```ts
import { getXRankSeasons, XRankSeason } from 'nxapi/splatnet2';
for (const season of getXRankSeasons()) {
// season is a plain object of type XRankSeason
}
// Alternatively this can be converted to a plain array.
// The iterator should be used instead where possible as it does not require
// keeping a reference to all Season objects.
// const seasons = [...getXRankSeasons()];
```
### `getXRankSeason`
Returns an `XRankSeason` object from a `Date`, year and month, season ID string or index number.
```ts
import { getXRankSeason, XRankSeason } from 'nxapi/splatnet2';
const season = getXRankSeason(2022, 1);
// season is a plain object of type XRankSeason
// season.id === '220101T00_220201T00'
// season.key === '2022_01'
// season.index === 44
// season.start is a Date object with the UTC timestamp 2022-01-01 00:00:00
// season.end is a Date object with the UTC timestamp 2022-02-01 00:00:00
// season.complete === true, assuming the system time is after 2022-02-01 00:00:00 (UTC)
// This function can also be called like this:
const season = getXRankSeason(new Date(Date.UTC(2022, 1)));
const season = getXRankSeason('220101T00_220201T00');
const season = getXRankSeason(44);
```
### `getNextXRankSeason`
Returns an `XRankSeason` object for the season following an X Rank season from an `XRankSeason`, `Date`, year and month, season ID string or index number.
```ts
import { getNextXRankSeason, XRankSeason } from 'nxapi/splatnet2';
const season = getNextXRankSeason(2022, 1);
// season is a plain object of type XRankSeason
// season.id === '220201T00_220301T00'
// season.key === '2022_02'
// season.index === 45
// season.start is a Date object with the UTC timestamp 2022-02-01 00:00:00
// season.end is a Date object with the UTC timestamp 2022-03-01 00:00:00
// season.complete === true, assuming the system time is after 2022-03-01 00:00:00 (UTC)
// This function can also be called like this:
const season = getNextXRankSeason(new Date(Date.UTC(2022, 1)));
const season = getNextXRankSeason('220101T00_220201T00');
const season = getNextXRankSeason(44);
```
### `getPreviousXRankSeason`
Returns an `XRankSeason` object for the season following an X Rank season from an `XRankSeason`, `Date`, year and month, season ID string or index number.
```ts
import { getNextXRankSeason, XRankSeason } from 'nxapi/splatnet2';
const season = getPreviousXRankSeason(2022, 1);
// season is a plain object of type XRankSeason
// season.id === '211201T00_220101T00'
// season.key === '2021_12'
// season.index === 43
// season.start is a Date object with the UTC timestamp 2021-12-01 00:00:00
// season.end is a Date object with the UTC timestamp 2022-01-01 00:00:00
// season.complete === true, assuming the system time is after 2022-01-01 00:00:00 (UTC)
// This function can also be called like this:
const season = getPreviousXRankSeason(new Date(Date.UTC(2022, 1)));
const season = getPreviousXRankSeason('220101T00_220201T00');
const season = getPreviousXRankSeason(44);
```

123
docs/lib/splatnet3.md Normal file
View 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)).

13880
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,21 +1,34 @@
{
"name": "nxapi",
"version": "0.3.0",
"description": "",
"author": "Samuel Elliott",
"version": "1.6.1",
"description": "Nintendo Switch app APIs",
"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",
"!dist/bundle",
"bin",
"resources"
"resources/cli",
"resources/common",
"bin"
],
"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",
"./splatnet3": "./dist/exports/splatnet3.js"
},
"bin": {
"nxapi": "bin/nxapi.js"
},
@ -23,77 +36,129 @@
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"body-parser": "^1.19.2",
"@samuelthomas2774/saltpack": "^0.4.0",
"body-parser": "^1.20.2",
"cli-table": "^0.3.11",
"debug": "^4.3.3",
"debug": "^4.3.4",
"discord-rpc": "^4.0.1",
"dotenv": "^16.0.0",
"dotenv-expand": "^8.0.3",
"dotenv": "^16.4.5",
"dotenv-expand": "^11.0.6",
"env-paths": "^3.0.0",
"express": "^4.17.3",
"frida": "^15.1.17",
"mkdirp": "^1.0.4",
"node-fetch": "^3.2.2",
"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",
"uuid": "^8.3.2",
"yargs": "^17.3.1"
"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": "^21.0.3",
"@rollup/plugin-html": "^0.2.4",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^13.1.3",
"@rollup/plugin-replace": "^4.0.0",
"@rollup/plugin-typescript": "^8.3.1",
"@types/cli-table": "^0.3.0",
"@types/debug": "^4.1.7",
"@types/discord-rpc": "^4.0.0",
"@types/express": "^4.17.13",
"@types/mkdirp": "^1.0.2",
"@types/node": "^17.0.21",
"@types/node-notifier": "^8.0.2",
"@types/node-persist": "^3.1.2",
"@types/react": "^17.0.43",
"@types/react-native": "^0.67.3",
"@types/read": "^0.0.29",
"@types/uuid": "^8.3.4",
"@types/yargs": "^17.0.9",
"caxa": "^2.1.0",
"electron": "^17.2.0",
"electron-builder": "^23.0.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-native-web": "^0.17.7",
"rollup": "^2.70.1",
"rollup-plugin-polyfill-node": "^0.8.0",
"ts-json-schema-generator": "^1.0.0",
"tslib": "^2.4.0",
"typescript": "^4.7.0-dev.20220308"
"@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",
"dist/bundle",
"!dist/app/package",
"resources"
"!**/node_modules/**/*",
"resources/app",
"resources/common",
"!resources/common/remote-config.json",
"resources/cli"
],
"asar": false,
"extraMetadata": {
"main": "dist/bundle/app-main-bundle.cjs"
"name": "nxapi-app",
"main": "dist/bundle/app-entry.cjs",
"dependencies": {},
"optionalDependencies": {},
"devDependencies": {}
},
"directories": {
"output": "dist/app/package"
},
"protocols": [
{
"name": "Nintendo Switch Online",
"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"
}
}
}

View File

@ -1,26 +0,0 @@
#!/system/bin/sh
# Ensure frida-server is running
echo "Running frida-server"
killall frida-server
nohup /data/local/tmp/frida-server >/dev/null 2>&1 &
if [ "$?" != "0" ]; then
echo "Failed to start frida-server"
exit 1
fi
sleep 1
# Ensure the app is running
echo "Starting com.nintendo.znca"
am start-foreground-service com.nintendo.znca/com.google.firebase.messaging.FirebaseMessagingService
am start-service com.nintendo.znca/com.google.firebase.messaging.FirebaseMessagingService
if [ "$?" != "0" ]; then
echo "Failed to start com.nintendo.znca"
exit 1
fi
echo "Acquiring wake lock"
echo androidzncaapiserver > /sys/power/wake_lock

BIN
resources/app.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

BIN
resources/app/menu-icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 655 B

View 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" $@

View 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" $@

View 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
View File

@ -0,0 +1,6 @@
#!/bin/bash
rm -f '/usr/bin/nxapi'
# Delete the link to the binary
rm -f '/usr/bin/nxapi-app'

View 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);

View 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');

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,28 @@
{
"require_version": [],
"log_encryption_key": "E2Sii_7drCzK-68RsEoArmopiAIlZD_6TMA2F_UAAU0",
"coral": {
"znca_version": "2.12.0"
},
"coral_auth": {
"default": [
"nxapi",
"https:\/\/nxapi-znca-api.fancy.org.uk\/api\/znca"
],
"splatnet2statink": null,
"flapg": null,
"imink": {}
},
"moon": {
"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"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

View File

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 37 KiB

View File

@ -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 "$@"

View File

Before

Width:  |  Height:  |  Size: 2.4 MiB

After

Width:  |  Height:  |  Size: 2.4 MiB

View File

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 33 KiB

View File

@ -1,97 +1,181 @@
import path from 'path';
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';
import nodeResolve from '@rollup/plugin-node-resolve';
import nodePolyfill from 'rollup-plugin-polyfill-node';
import html from '@rollup/plugin-html';
import json from '@rollup/plugin-json';
const dir = path.dirname(fileURLToPath(import.meta.url));
const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf-8'));
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) {
return null;
}
const options = {cwd: dir};
const revision = child_process.execSync('git rev-parse HEAD', options).toString().trim();
const branch = child_process.execSync('git rev-parse --abbrev-ref HEAD', options).toString().trim();
const changed_files = child_process.execSync('git diff --name-only HEAD', options).toString().trim();
return {
revision,
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;
/**
* @type {import('rollup').RollupOptions}
* @type {import('@rollup/plugin-replace').RollupReplaceOptions}
*/
const cli = {
input: 'src/cli-entry.ts',
output: {
file: 'dist/bundle/cli-bundle.js',
format: 'es',
inlineDynamicImports: true,
const replace_options = {
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'),
},
plugins: [
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',
}),
json(),
nodeResolve({
browser: false,
preferBuiltins: true,
}),
],
external: [
'node-notifier',
'frida',
],
preventAssignment: true,
};
/**
* @type {import('rollup').RollupOptions['watch']}
*/
const watch = {
include: 'dist/**',
};
/**
* @type {import('rollup').RollupOptions}
*/
const app = {
input: 'src/app/main/app-entry.cts',
const main = {
input: ['dist/cli-entry.js', 'dist/app/app-init.js', 'dist/app/main/index.js'],
output: {
file: 'dist/bundle/app-main-bundle.cjs',
format: 'cjs',
inlineDynamicImports: true,
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';
},
chunkFileNames: 'chunk-[name].js',
},
plugins: [
typescript({
noEmit: true,
declaration: false,
}),
replace(replace_options),
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,
preferBuiltins: true,
}),
],
external: [
'electron',
'node-notifier',
'register-scheme',
'bindings',
],
watch,
};
/**
* @type {import('rollup').RollupOptions}
*/
const app_entry = {
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: ['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,
}),
commonjs({
esmExternals: true,
// events and stream modify module.exports
requireReturnsDefault: 'preferred',
}),
json(),
nodeResolve({
exportConditions: ['node'],
browser: false,
preferBuiltins: true,
}),
],
external: [
'electron',
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,
};
/**
* @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',
sourcemap: true,
},
plugins: [
typescript({
noEmit: true,
declaration: false,
}),
replace(replace_options),
commonjs({
// the ".ts" extension is required
extensions: ['.js', '.jsx', '.ts', '.tsx'],
esmExternals: true,
}),
nodeResolve({
@ -102,25 +186,21 @@ const app_preload = {
external: [
'electron',
],
watch,
};
/**
* @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: [
typescript({
noEmit: true,
declaration: false,
}),
replace(replace_options),
commonjs({
// the ".ts" extension is required
extensions: ['.js', '.jsx', '.ts', '.tsx'],
esmExternals: true,
}),
nodeResolve({
@ -131,34 +211,47 @@ const app_preload_webservice = {
external: [
'electron',
],
watch,
};
/**
* @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',
}),
typescript({
noEmit: true,
declaration: false,
}),
replace(replace_options),
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({
@ -166,12 +259,15 @@ const app_browser = {
preferBuiltins: false,
}),
],
watch,
};
const skip = process.env.BUNDLE_SKIP?.split(',') ?? [];
export default [
cli,
app,
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);

666
src/api/coral-types.ts Normal file
View File

@ -0,0 +1,666 @@
export interface CoralSuccessResponse<T = unknown> {
status: CoralStatus.OK;
result: T;
correlationId: string;
}
export interface CoralError {
status: CoralStatus | number;
errorMessage: string;
correlationId: string;
}
export enum CoralStatus {
OK = 0,
BAD_REQUEST = 9400,
METHOD_NOT_ALLOWED = 9401,
RESOURCE_NOT_FOUND = 9402,
INVALID_TOKEN = 9403,
TOKEN_EXPIRED = 9404,
FORBIDDEN = 9405,
UNAUTHORISED = 9406,
NSA_NOT_LINKED = 9407,
USER_NOT_FOUND = 9408,
APPLICATION_ID_NOT_SUPPORTED = 9409,
EVENT_NOT_FOUND = 9411,
EVENT_NOT_ACTIVATED = 9412,
NOT_JOINED_VOICE_CHAT = 9416,
DUPLICATE_APPLICATION_ID = 9417,
OPERATION_NOT_ALLOWED = 9422,
RATING_AGE = 9423,
USER_NOT_ACTIVATED = 9424,
INVITATION_LIMIT_EXCEEDED = 9425,
MULTIPLE_LOGIN = 9426,
UPGRADE_REQUIRED = 9427,
ACCOUNT_DISABLED = 9428,
RATE_LIMIT_EXCEEDED = 9437,
MEMBERSHIP_REQUIRED = 9450,
INVALID_FRIEND_REQUEST = 9460,
SENDER_FRIEND_LIMIT_EXCEEDED = 9461,
RECEIVER_FRIEND_LIMIT_EXCEEDED = 9462,
FRIEND_REQUEST_NOT_ACCEPTED = 9463,
DUPLICATE_FRIEND_REQUEST = 9464,
PRECONDITION_FAILED = 9465,
RESOURCE_LIMIT_EXCEEDED = 9466,
ALREADY_FRIEND = 9467,
SENDER_BLOCKS_RECEIVER_FRIEND_REQUEST = 9468,
SERVICE_CLOSED = 9499,
INTERNAL_SERVER_ERROR = 9500,
SERVICE_UNAVAILABLE = 9501,
MAINTENANCE = 9511,
UNEXPECTED = 9599,
// UNKNOWN = -1,
}
export type CoralResponse<T = unknown> = CoralSuccessResponse<T> | CoralError;
export interface AccountLoginParameter {
naIdToken: string;
naBirthday: string;
naCountry: string;
language: string;
timestamp: number;
requestId: string;
f: string;
}
/** /v3/Account/Login */
export interface AccountLogin {
user: CurrentUser<true>;
webApiServerCredential: {
accessToken: string;
expiresIn: number;
};
firebaseCredential: {
accessToken: string;
expiresIn: number;
};
}
/** /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;
timestamp: number;
requestId: string;
f: string;
}
/** /v1/Announcement/List */
export type Announcements = Announcement[];
export interface Announcement {
announcementId: number;
priority: number;
forceDisplayEndDate: number;
distributionDate: number;
title: string;
description: string;
link?: string;
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;
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;
/**
* Timestamp (in seconds) the user's presence was last updated.
* This seems to change every hour if a linked console is online, even if the user's presence doesn't change.
*/
updatedAt: number;
logoutAt: number;
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 {
/** Offline */
OFFLINE = 'OFFLINE',
/** A console linked to this account is online, but the user isn't selected in an application */
INACTIVE = 'INACTIVE',
/** The user is selected in an application */
ONLINE = 'ONLINE',
/** 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;
shopUri: string;
totalPlayTime: number;
/** 0 if never played before */
firstPlayedAt: number;
}
export interface PresenceGame extends Game {
sysDescription: string;
}
/** /v3/Friend/CreateFriendCodeUrl */
export interface FriendCodeUrl {
url: string;
friendCode: string;
}
/** /v3/Friend/GetUserByFriendCode, /v3/Friend/GetUserByFriendCodeHash */
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;
customAttributes: WebServiceAttribute[];
whiteList: string[];
name: string;
imageUri: string;
}
export interface WebService_4 extends WebService {
startDate: number;
isNotificationSupported: boolean;
isNotificationAllowed: boolean;
}
export interface WebServiceAttribute {
attrValue: string;
attrKey: string;
}
export interface WebServiceTokenParameter {
id: number;
registrationToken: string;
timestamp: number;
requestId: string;
f: string;
}
/** /v2/Game/GetWebServiceToken, /v2/Extension/Game/GetWebServiceToken, /v4/Game/GetWebServiceToken */
export interface WebServiceToken {
accessToken: string;
expiresIn: number;
}
/** /v1/Event/GetActiveEvent */
export type GetActiveEventResult = ActiveEvent | {};
export interface ActiveEvent extends Event {
activateId: string;
}
/** /v1/Event/Show */
export interface Event {
id: number;
name: string;
description: string;
shareUri: string;
ownerUserId: number;
members: EventMember[];
passCode: string;
eventType: 3; // ??
allowJoinGameWithoutCoral: boolean;
game: {
id: number;
};
imageUri: string;
}
export interface EventMember {
id: number;
name: string;
imageUri: string;
isPlaying: boolean;
isInvited: boolean;
isJoinedVoip: boolean;
}
/** /v3/User/Show */
export interface User {
id: number;
nsaId: string;
imageUri: string;
image2Uri: string;
name: string;
}
/** /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: (boolean extends WithNintendoAccount ? {
nintendoAccount?: CurrentUserNintendoAccountLink;
} : true extends WithNintendoAccount ? {
nintendoAccount: CurrentUserNintendoAccountLink;
} : {}) & {
friendCode: CurrentUserFriendCodeLink;
};
permissions: {
playLog: PlayLogPermissions;
presence: PresencePermissions;
friendRequestReception: boolean;
};
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',
SELF = 'SELF',
}
/** /v3/User/Permissions/ShowSelf */
export interface CurrentUserPermissions {
etag: string;
permissions: {
playLog: PlayLogPermissions;
presence: PresencePermissions;
friendRequestReception: boolean;
};
}
export interface UpdateCurrentUserPermissionsParameter {
permissions: {
presence: {
toValue: PresencePermissions;
fromValue: PresencePermissions;
};
};
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
//

1099
src/api/coral.ts Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -24,7 +24,7 @@ export interface User {
acceptedNotification: {
all: boolean;
};
notices: unknown[];
notices: string[];
createdAt: number;
updatedAt: number;
}
@ -71,13 +71,7 @@ export interface PairedDevice {
device: Device;
nintendoAccountId: string;
label: string;
parentalControlSettingState: {
deviceId: string;
targetEtag: string;
synchronizationStatus: 'SYNCHRONIZED';
createdAt: number;
updatedAt: number;
};
parentalControlSettingState: ParentalControlSettingState;
hasNewMonthlySummary: boolean;
hasFirstDailySummary: boolean;
createdAt: number;
@ -110,13 +104,18 @@ export interface Device {
};
lastOnlineCheckedAt: number;
alarmSetting: {
visibility: 'VISIBLE';
visibility: AlarmStatus;
invisibleUntil: number;
};
createdAt: number;
updatedAt: number;
}
export enum AlarmStatus {
VISIBLE = 'VISIBLE',
INVISIBLE = 'INVISIBLE',
}
/** GET /v1/devices/{deviceId}/daily_summaries */
export interface DailySummaries {
count: number;
@ -129,11 +128,11 @@ export interface DailySummary {
date: string; // "2022-03-14"
result: DailySummaryResult;
playingTime: number;
exceededTime: null;
exceededTime: number | null;
disabledTime: number;
miscTime: number;
importantInfos: ImportantInfo[];
notices: unknown[];
notices: Notice[];
observations: Observation[];
playedApps: PlayedTitle[];
anonymousPlayer: AnonymousPlayer | null;
@ -146,10 +145,14 @@ export interface DailySummary {
export enum DailySummaryResult {
CALCULATING = 'CALCULATING',
ACHIEVED = 'ACHIEVED',
UNACHIEVED = 'UNACHIEVED',
}
export enum ImportantInfo {
DID_WRONG_UNLOCK_CODE = 'DID_WRONG_UNLOCK_CODE',
}
export enum Notice {
DID_ALARM_MAKE_INVISIBLE = 'DID_ALARM_MAKE_INVISIBLE',
}
export interface Title {
applicationId: string;
@ -270,7 +273,14 @@ export enum MonthlySummaryTitleRankingPosition {
export interface ParentalControlSettingState {
deviceId: string;
targetEtag: string;
synchronizationStatus: 'SYNCHRONIZED';
synchronizationStatus: SynchronizationStatus;
createdAt: number;
updatedAt: number;
}
export enum SynchronizationStatus {
SYNCHRONIZED = 'SYNCHRONIZED',
NOTIFIED = 'NOTIFIED',
PENDING = 'PENDING',
FAILED = 'FAILED',
}

View File

@ -1,26 +1,56 @@
import fetch from 'node-fetch';
import createDebug from 'debug';
import { getNintendoAccountToken, getNintendoAccountUser } 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');
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 {
constructor(
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
public naId: string,
readonly znma_version = ZNMA_VERSION,
readonly znma_build = ZNMA_BUILD,
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: method,
method,
headers: Object.assign({
'Authorization': 'Bearer ' + this.token,
'Cache-Control': 'no-store',
@ -32,23 +62,40 @@ export default class MoonApi {
'X-Moon-TimeZone': 'Europe/London',
'X-Moon-Os-Language': 'en-GB',
'X-Moon-App-Language': 'en-GB',
'X-Moon-App-Display-Version': ZNMA_VERSION,
'X-Moon-App-Internal-Version': ZNMA_BUILD,
'User-Agent': 'moon_ANDROID/' + ZNMA_VERSION + ' (com.nintendo.znma; build:' + ZNMA_BUILD +
'; ANDROID 26)',
'X-Moon-App-Display-Version': this.znma_version,
'X-Moon-App-Internal-Version': this.znma_build,
'User-Agent': this.znma_useragent,
}, headers),
body: body,
});
body,
signal,
}).finally(cancel);
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 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() {
@ -79,34 +126,107 @@ export default class MoonApi {
return this.fetch<ParentalControlSettingState>('/v1/devices/' + id + '/parental_control_setting_state');
}
static async createWithSessionToken(token: string) {
const data = await this.loginWithSessionToken(token);
return {
moon: new this(data.nintendoAccountToken.access_token!, data.user.id),
data,
};
}
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;
}
static async loginWithSessionToken(token: string) {
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};
}
static createWithSavedToken(data: MoonAuthData) {
return new this(
data.nintendoAccountToken.access_token!,
data.user.id,
data.znma_version,
data.znma_build,
data.znma_useragent,
);
}
static async loginWithSessionToken(token: string): Promise<MoonAuthData> {
const { default: { moon: config } } = await import('../common/remote-config.js');
if (!config) throw new Error('Remote configuration prevents Moon authentication');
const znma_useragent = 'moon_ANDROID/' + config.znma_version +
' (com.nintendo.znma; build:' + config.znma_build + '; ANDROID 26)';
// Nintendo Account token
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,
user,
znma_version: config.znma_version,
znma_build: config.znma_build,
znma_useragent: znma_useragent,
};
}
}
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: NintendoAccountUserMoon;
znma_version: string;
znma_build: string;
znma_useragent: string;
}
export interface PartialMoonAuthData {
nintendoAccountToken: NintendoAccountToken;
}

View File

@ -1,19 +1,140 @@
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');
const [signal, cancel] = timeoutSignal();
const response = await fetch('https://accounts.nintendo.com/connect/1.0.0/api/session_token', {
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({
@ -21,22 +142,31 @@ export async function getNintendoAccountSessionToken(code: string, verifier: str
session_token_code: code,
session_token_code_verifier: verifier,
}).toString(),
});
signal,
}).finally(cancel);
const token = await response.json() as NintendoAccountSessionToken | NintendoAccountError;
if (response.status !== 200) {
throw await NintendoAccountAuthErrorResponse.fromResponse(response, '[na] Non-200 status code');
}
const token = await response.json() as NintendoAccountSessionToken | NintendoAccountAuthError | NintendoAccountError;
if ('error' in token) {
throw new NintendoAccountAuthErrorResponse('[na] ' + (token.error_description ?? token.error), response, token);
}
if ('errorCode' in token) {
throw new ErrorResponse('[na] + ' + token.detail, response, 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) {
debug('Getting Nintendo Account token');
const [signal, cancel] = timeoutSignal();
const response = await fetch('https://accounts.nintendo.com/connect/1.0.0/api/token', {
method: 'POST',
headers: {
@ -49,22 +179,32 @@ export async function getNintendoAccountToken(token: string, client_id: string)
session_token: token,
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer-session-token',
}),
});
signal,
}).finally(cancel);
const nintendoAccountToken = await response.json() as NintendoAccountToken | NintendoAccountError;
if (response.status !== 200) {
throw await NintendoAccountAuthErrorResponse.fromResponse(response, '[na] Non-200 status code');
}
const nintendoAccountToken = await response.json() as NintendoAccountToken | NintendoAccountAuthError | NintendoAccountError;
if ('error' in nintendoAccountToken) {
throw new NintendoAccountAuthErrorResponse('[na] ' + (nintendoAccountToken.error_description ??
nintendoAccountToken.error), response, nintendoAccountToken);
}
if ('errorCode' in nintendoAccountToken) {
throw new ErrorResponse('[na] + ' + nintendoAccountToken.detail, response, 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();
const response = await fetch('https://api.accounts.nintendo.com/2.0.0/users/me', {
headers: {
'Accept-Language': 'en-GB',
@ -73,17 +213,22 @@ export async function getNintendoAccountUser(token: NintendoAccountToken) {
'Accept': 'application/json',
'Authorization': 'Bearer ' + token.access_token!,
},
});
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 {
@ -91,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;
@ -105,7 +250,7 @@ export interface NintendoAccountSessionTokenJwtPayload extends JwtPayload {
}
export interface NintendoAccountToken {
scope: string[];
scope: NintendoAccountScope[];
token_type: 'Bearer';
id_token: string;
access_token?: string;
@ -120,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;
}
@ -132,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;
@ -171,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,
@ -199,74 +346,128 @@ 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: {
favoriteColor: string;
id: string;
updatedAt: number;
coreData: {
'4': string;
};
clientId: '1cfe3a55ed8924d9';
imageUriTemplate: string;
storeData: {
'3': string;
};
imageOrigin: string;
etag: string;
type: 'profile';
};
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;
};
}
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 {
id: string;
clientId: '1cfe3a55ed8924d9';
type: 'profile';
favoriteColor: MiiColour;
coreData: {
'4': string;
};
emailOptedInUpdatedAt: number;
birthday: string;
screenName: string;
gender: string;
analyticsOptedInUpdatedAt: number;
analyticsOptedIn: boolean;
clientFriendsOptedInUpdatedAt: number;
storeData: {
'3': string;
};
imageUriTemplate: string;
imageOrigin: string;
etag: string;
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 {
error: string;
error_description: string;
}
export interface NintendoAccountError {
@ -277,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> {}

View File

@ -1,57 +1,95 @@
import fetch from 'node-fetch';
import createDebug from 'debug';
import { WebServiceToken } from './znc-types.js';
import { NintendoAccountUser } from './na.js';
import { ErrorResponse } from './util.js';
import ZncApi from './znc.js';
import { fetch, FormData, Response } from 'undici';
import { WebServiceToken } from './coral-types.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';
const NOOKLINK_URL = NOOKLINK_WEBSERVICE_URL + '/api';
const BLANCO_VERSION = '2.1.0';
const BLANCO_VERSION = '2.1.1';
export default class NooklinkApi {
constructor(
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
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: method,
method,
headers: Object.assign({
'Upgrade-Insecure-Requests': '1',
'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',
'X-Blanco-Version': BLANCO_VERSION,
'X-Blanco-Version': this.client_version,
}, headers),
body: body,
});
body,
signal,
}).finally(cancel);
debug('fetch %s %s, response %s', method, url, response.status);
if (response.status !== 200 && response.status !== 201) {
throw new ErrorResponse('[nooklink] Unknown error', 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() {
@ -65,30 +103,50 @@ export default class NooklinkApi {
}
async createUserClient(user_id: string) {
const token = await this.getAuthToken(user_id);
return {
nooklinkuser: new NooklinkUserApi(user_id, token.token, this.gtoken, this.useragent),
token,
};
return NooklinkUserApi._createWithNooklinkApi(this, user_id);
}
static async createWithZnc(nso: ZncApi, user: NintendoAccountUser) {
const data = await this.loginWithZnc(nso, user);
return {
nooklink: new this(data.gtoken, data.useragent),
data,
};
async renewTokenWithCoral(coral: CoralApiInterface, user: NintendoAccountUserCoral) {
const data = await NooklinkApi.loginWithCoral(coral, user);
this.setTokenWithSavedToken(data);
return data;
}
static async loginWithZnc(nso: ZncApi, user: NintendoAccountUser) {
const webserviceToken = await nso.getWebServiceToken(NOOKLINK_WEBSERVICE_ID);
return this.loginWithWebServiceToken(webserviceToken.result, user);
async renewTokenWithWebServiceToken(webserviceToken: WebServiceToken, user: NintendoAccountUserCoral) {
const data = await NooklinkApi.loginWithWebServiceToken(webserviceToken, user);
this.setTokenWithSavedToken(data);
return data;
}
static async loginWithWebServiceToken(webserviceToken: WebServiceToken, user: NintendoAccountUser) {
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};
}
static createWithSavedToken(data: NooklinkAuthData) {
return new this(data.gtoken, data.useragent);
}
static async loginWithCoral(coral: CoralApiInterface, user: NintendoAccountUserCoral) {
const { default: { coral_gws_nooklink: config } } = await import('../common/remote-config.js');
if (!config) throw new Error('Remote configuration prevents NookLink authentication');
const webserviceToken = await coral.getWebServiceToken(NOOKLINK_WEBSERVICE_ID);
return this.loginWithWebServiceToken(webserviceToken, user);
}
static async loginWithWebServiceToken(
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');
const url = new URL(NOOKLINK_WEBSERVICE_URL);
url.search = new URLSearchParams({
lang: user.language,
@ -96,31 +154,35 @@ export default class NooklinkApi {
na_lang: user.language,
}).toString();
const [signal, cancel] = timeoutSignal();
const response = await fetch(url.toString(), {
headers: {
'Upgrade-Insecure-Requests': '1',
'User-Agent': NOOKLINK_WEBSERVICE_USERAGENT,
'x-appplatform': 'android',
'x-appcolorscheme': 'DARK',
'x-gamewebtoken': webserviceToken.accessToken,
'dnt': '1',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-GB,en-US;q=0.8',
'X-Requested-With': 'com.nintendo.znca',
},
});
signal,
}).finally(cancel);
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]);
@ -140,51 +202,90 @@ export default class NooklinkApi {
gtoken,
expires_at,
useragent: NOOKLINK_WEBSERVICE_USERAGENT,
version: config.blanco_version,
};
}
}
export class NooklinkUserApi {
constructor(
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,
public gtoken: string,
public useragent: string,
public language = 'en-GB'
public language = 'en-GB',
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: method,
method,
headers: Object.assign({
'Upgrade-Insecure-Requests': '1',
'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,
'X-Blanco-Version': BLANCO_VERSION,
'X-Blanco-Version': this.client_version,
}, headers),
body: body,
});
body,
signal,
}).finally(cancel);
debug('fetch %s %s, response %s', method, url, response.status);
if (response.status !== 200 && response.status !== 201) {
throw new ErrorResponse('[nooklink] Unknown error', 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) {
@ -212,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,
@ -230,6 +331,100 @@ export class NooklinkUserApi {
async reaction(reaction: Reaction) {
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);
return {
gtoken: client.gtoken,
useragent: client.useragent,
version: client.client_version,
user_id,
token,
language: 'en-GB',
};
}
/** @internal */
static async _createWithNooklinkApi(client: NooklinkApi, user_id: string) {
const data = await this._loginWithNooklinkApi(client, user_id);
return {nooklinkuser: this.createWithSavedToken(data), data};
}
static createWithSavedToken(data: NooklinkUserAuthData) {
return new NooklinkUserApi(
data.user_id, data.token.token,
data.gtoken, data.useragent, data.language, data.version
);
}
static createWithCliTokenData(data: NooklinkUserCliTokenData) {
return new NooklinkUserApi(
data.user_id, data.auth_token,
data.gtoken, NOOKLINK_WEBSERVICE_USERAGENT, data.language, data.version
);
}
}
export class NooklinkErrorResponse extends ErrorResponse<WebServiceError> {}
export interface NooklinkAuthData {
webserviceToken: WebServiceToken;
url: string;
cookies: string;
body: string;
gtoken: string;
expires_at: number;
useragent: string;
version: string;
}
export interface NooklinkUserAuthData {
gtoken: string;
useragent: string;
version: string;
user_id: string;
token: AuthToken;
language: string;
}
export type PartialNooklinkUserAuthData =
Pick<NooklinkUserAuthData, 'gtoken' | 'user_id' | 'token'>;
export interface NooklinkUserCliTokenData {
gtoken: string;
version: string;
auth_token: string;
expires_at: number;
user_id: string;
language: string;
}
function formatDateTime(date: Date) {

View File

@ -10,7 +10,7 @@ export interface Records {
records: {
recent_disconnect_count: number;
recent_win_count: number;
stage_stats: unknown;
stage_stats: Record<string | number, StageStats>;
update_time: number;
recent_lose_count: number;
league_stats: {
@ -28,6 +28,23 @@ export interface Records {
};
}
interface StageStats {
stage: Stage;
last_play_time: number;
// Splat Zones
area_win: number;
area_lose: number;
// Tower Control
yagura_lose: number;
yagura_win: number;
// Rainmaker
hoko_win: number;
hoko_lose: number;
// Clam Blitz
asari_win: number;
asari_lose: number;
}
interface Challenges {
next_challenge: Challenge;
archived_challenges_octa: OctaChallenge[];
@ -74,18 +91,20 @@ interface WeaponStats {
total_paint_point: number;
last_use_time: number;
lose_count: number;
weapon: Weapon;
weapon: WeaponSet;
win_count: number;
max_win_meter: number;
}
interface Weapon {
interface MainWeapon {
name: string;
id: string;
thumbnail: string;
image: string;
}
interface WeaponSet extends MainWeapon {
sub: SubWeapon;
special: SpecialWeapon;
image: string;
}
interface SubWeapon {
image_b: string;
@ -101,21 +120,21 @@ interface SpecialWeapon {
}
interface Player {
clothes: Gear & {kind: 'clothes'};
clothes: Gear & {kind: GearType.CLOTHES};
star_rank: number;
head_skills: Skills;
nickname: string;
shoes_skills: Skills;
weapon: Weapon;
weapon: WeaponSet;
player_rank: number;
max_league_point_team: number;
shoes: Gear & {kind: 'shoes'};
shoes: Gear & {kind: GearType.SHOES};
clothes_skills: Skills;
udemae_tower: Rank;
udemae_clam: Rank;
udemae_rainmaker: Rank;
player_type: PlayerType;
head: Gear & {kind: 'head'};
head: Gear & {kind: GearType.HEAD};
max_league_point_pair: number;
principal_id: string;
udemae_zones: Rank;
@ -127,9 +146,14 @@ interface Gear {
id: string;
rarity: number;
image: string;
kind: 'clothes' | 'shoes' | 'head';
kind: GearType;
thumbnail: string;
}
export enum GearType {
CLOTHES = 'clothes',
SHOES = 'shoes',
HEAD = 'head',
}
interface Brand {
image: string;
frequent_skill?: Skill;
@ -147,7 +171,7 @@ interface Skill {
}
interface Rank {
name: null;
name: string | null;
s_plus_number: null;
is_x: boolean;
number: number;
@ -191,6 +215,10 @@ export interface Timeline {
};
udemae: {
importance: number;
} | {
importance: number;
change: number;
stat: RankedMatchResults;
};
coop: {
importance: number;
@ -232,38 +260,6 @@ export interface Timeline {
};
}
interface ShopMerchandise {
skill: Skill;
end_time: number;
gear: Gear;
id: string;
price: number;
kind: string;
}
interface CoopSchedule {
weapons: CoopWeapon[];
stage: {
image: string;
name: string;
};
start_time: number;
end_time: number;
}
type CoopWeapon = CoopStandardWeapon | CoopSpecialWeapon;
interface CoopStandardWeapon {
weapon: Omit<Weapon, 'sub' | 'special'>;
id: string;
}
interface CoopSpecialWeapon {
id: string;
coop_special_weapon: {
image: string;
name: string;
};
}
interface CoopRewardGear {
available_time: number;
gear: Gear;
@ -300,17 +296,19 @@ interface ScheduleItem {
/** GET /records/hero */
export interface HeroRecords {
stage_infos: StageInfo[];
summary: {
weapon_cleared_info: Record<string, boolean>;
honor: {
code: string;
name: string;
};
clear_rate: number;
};
summary: HeroRecordsSummary;
weapon_map: Record<string, HeroWeapon>;
}
interface HeroRecordsSummary {
weapon_cleared_info: Record<string, boolean>;
honor: HeroHonor;
clear_rate: number;
}
interface HeroHonor {
code: string;
name: string;
}
interface StageInfo {
clear_weapons: Record<string, StageCleared>;
stage: HeroStage;
@ -338,21 +336,27 @@ export interface XPowerRankingSummary {
splat_zones: XPowerRankingRecords;
}
interface XPowerRankingRecords {
/** GET /x_power_ranking/{season}/{rule} */
export interface XPowerRankingRecords {
weapon_ranking: null;
season_id: string;
top_rankings_count: number;
top_rankings: XPowerRankingRecordsRanking[];
status: string;
status: XPowerRankingStatus;
rule: Rule;
start_time: number;
end_time: number;
my_ranking: null;
}
export enum XPowerRankingStatus {
CALCULATED = 'calculated',
ONGOING = 'ongoing',
}
interface XPowerRankingRecordsRanking {
name: string;
principal_id: string;
weapon: Weapon;
weapon: WeaponSet;
rank: number;
unique_id: string;
x_power: number;
@ -367,34 +371,35 @@ export interface PastFestivals {
}
interface Festival {
colors: {
middle: InkColour;
bravo: InkColour;
alpha: InkColour;
};
colors: FestivalInkColours;
festival_id: number;
names: {
bravo_short: string;
bravo_long: string;
alpha_short: string;
alpha_long: string;
};
images: {
bravo: string;
alpha: string;
panel: string;
};
times: {
start: number;
announce: number;
end: number;
result: number;
};
special_stage: {
name: string;
id: string;
image: string;
};
names: FestivalTeamNames;
images: FestivalImages;
times: FestivalTimes;
special_stage: Stage;
}
interface FestivalTeamNames {
bravo_short: string;
bravo_long: string;
alpha_short: string;
alpha_long: string;
}
interface FestivalImages {
bravo: string;
alpha: string;
panel: string;
}
interface FestivalTimes {
start: number;
announce: number;
end: number;
result: number;
}
interface FestivalInkColours {
middle: InkColour;
bravo: InkColour;
alpha: InkColour;
}
interface InkColour {
@ -450,18 +455,20 @@ interface FestivalResults1 {
/** GET /league_match_ranking/{league}/{region} */
export interface LeagueMatchRankings {
start_time: number;
league_type: {
name: string;
key: string;
};
league_ranking_region: {
code: string;
id: number;
};
league_type: LeagueType;
league_ranking_region: LeagueRankingRegion;
rankings: LeagueMatchRanking[];
league_id: string;
}
interface LeagueType {
key: string; // "team", "pair"
name: string; // "Mode: Team", "Mode: Pair"
}
interface LeagueRankingRegion {
id: number; // 0, 1, 2, 4
code: string; // ALL, JP, US, EU
}
interface LeagueMatchRanking {
tag_members: LeagueTagMember[];
point: number;
@ -470,7 +477,7 @@ interface LeagueMatchRanking {
rank: number;
}
interface LeagueTagMember {
weapon: Weapon;
weapon: WeaponSet;
unique_id: string;
principal_id: string;
}
@ -479,16 +486,18 @@ interface LeagueTagMember {
export interface Results {
results: MatchResults[];
unique_id: string;
summary: {
kill_count_average: number;
victory_count: number;
count: number;
defeat_count: number;
special_count_average: number;
victory_rate: number;
death_count_average: number;
assist_count_average: number;
};
summary: ResultsSummary;
}
interface ResultsSummary {
kill_count_average: number;
victory_count: number;
count: number;
defeat_count: number;
special_count_average: number;
victory_rate: number;
death_count_average: number;
assist_count_average: number;
}
type MatchResults = RegularMatchResults | RankedMatchResults;
@ -525,10 +534,10 @@ interface RankedMatchResults extends BaseMatchResults {
is_x: boolean;
is_number_reached: boolean;
s_plus_number: null;
name: null;
name: string | null;
number: number;
};
estimate_gachi_power: null;
estimate_gachi_power: number | null;
x_power: null;
}
interface PlayerResult {
@ -543,7 +552,7 @@ interface PlayerResult {
interface RankedPlayerResult extends PlayerResult {
player: PlayerResult['player'] & {
udemae: {
name: null;
name: string | null;
s_plus_number: null;
is_x: boolean;
};
@ -552,7 +561,7 @@ interface RankedPlayerResult extends PlayerResult {
interface SelfRankedPlayerResult extends PlayerResult {
player: PlayerResult['player'] & {
udemae: {
name: null;
name: string | null;
s_plus_number: null;
number: number; // -1;
is_number_reached: boolean;
@ -669,6 +678,18 @@ interface CoopWaveWaterLevel {
key: string;
name: string;
}
type CoopWeapon = CoopStandardWeapon | CoopSpecialWeapon;
interface CoopStandardWeapon {
weapon: MainWeapon;
id: string;
}
interface CoopSpecialWeapon {
id: string;
coop_special_weapon: {
image: string;
name: string;
};
}
interface CoopSummaryResult {
schedule: CoopSchedule;
@ -710,6 +731,15 @@ export interface CoopSchedules {
schedules: CoopScheduleTimes[];
}
interface CoopSchedule {
weapons: CoopWeapon[];
stage: {
image: string;
name: string;
};
start_time: number;
end_time: number;
}
interface CoopScheduleTimes {
start_time: number;
end_time: number;
@ -721,6 +751,15 @@ export interface ShopMerchandises {
ordered_info: null;
}
interface ShopMerchandise {
skill: Skill;
end_time: number;
gear: Gear;
id: string;
price: number;
kind: GearType;
}
/** POST /share/profile, POST /share/results/summary, POST /share/results/1 */
export interface ShareResponse {
url: string;

243
src/api/splatnet2-xrank.ts Normal file
View File

@ -0,0 +1,243 @@
//
// X Rank seasons
//
// X Rank seasons are calculated by the web app, not retrieved from the API.
//
export interface Season {
/** Season ID use by the API, e.g. "220501T00_220601T00" */
id: string;
/** Season ID use by the web app, e.g. "2022_05" */
key: string;
index: number;
start: Date;
end: Date;
complete: boolean;
}
export function* getAllSeasons(sort_ascending = false) {
let season = sort_ascending ? getFirstSeason() : getCurrentSeason();
while (season) {
yield season;
season = sort_ascending ? getNextSeason(season) : getPreviousSeason(season);
}
}
export function getSeason(year: number, month: number): Season | null
export function getSeason(start: Date): Season | null
export function getSeason(id: string | number): Season | null
export function getSeason(year: number | Date | string, month?: number): Season | null {
if (year instanceof Date) {
month = year.getUTCMonth() + 1;
year = year.getUTCFullYear();
}
if (typeof year === 'string') {
// 180401T00_180601T00
const match = year.match(/^(\d{2,})(0\d|1[012])01T00_(\d{2,})(0\d|1[012])01T00$/);
if (!match) throw new Error('Invalid season ID');
year = 2000 + parseInt(match[1]);
month = parseInt(match[2]);
const nextyear = month === 12 ? year + 1 : year;
const nextmonth = year === 2018 && month === 4 ? 6 :
month === 12 ? 1 : month + 1;
if (nextyear !== (2000 + parseInt(match[3])) || nextmonth !== parseInt(match[4])) throw new Error('Invalid season ID');
if (year === 2018 && month === 5) throw new Error('Invalid season ID');
}
const start = typeof month === 'number' ? new Date(Date.UTC(year, month - 1)) :
getSeasonStartDateByIndex(year);
if (start.getUTCFullYear() === 2018 && start.getUTCMonth() === 3) {
start.setUTCMonth(4);
}
if (Date.now() < start.getTime()) return null;
if (start.getUTCFullYear() < 2018 || (start.getUTCFullYear() === 2018 && start.getUTCMonth() < 3)) return null;
const end = new Date(Date.UTC(
start.getUTCFullYear() + (start.getUTCMonth() === 11 ? 1 : 0),
start.getUTCMonth() === 11 ? 0 : start.getUTCMonth() + 1,
));
const id = toSeasonId(start.getUTCFullYear(), start.getUTCMonth() + 1);
const key = start.getUTCFullYear() + '_' + ('' + (start.getUTCMonth() + 1)).padStart(2, '0');
if (start.getUTCFullYear() === 2018 && start.getUTCMonth() === 4) {
start.setUTCMonth(3);
}
return {
id,
key,
index: getSeasonIndex(start.getUTCFullYear(), start.getUTCMonth() + 1),
start,
end,
complete: Date.now() > end.getTime(),
};
}
export function getFirstSeason() {
return getSeason(2018, 5);
}
export function getCurrentSeason() {
return getSeason(new Date());
}
export function getNextSeason(season: Season | number): Season | null
export function getNextSeason(year: number, month: number): Season | null
export function getNextSeason(season: Season | number, month?: number): Season | null {
const current_start =
typeof season === 'number' && typeof month === 'number' ?
new Date(Date.UTC(season, month)) :
typeof season === 'number' ? getSeasonStartDateByIndex(season) :
new Date(season.start.getTime());
if (current_start.getUTCFullYear() === 2018 && current_start.getUTCMonth() === 3) {
current_start.setUTCMonth(4);
}
const start = new Date(Date.UTC(
current_start.getUTCFullYear() + (current_start.getUTCMonth() === 11 ? 1 : 0),
current_start.getUTCMonth() === 11 ? 0 : current_start.getUTCMonth() + 1,
));
if (Date.now() < start.getTime()) return null;
const end = new Date(Date.UTC(
start.getUTCFullYear() + (start.getUTCMonth() === 11 ? 1 : 0),
start.getUTCFullYear() === 2018 && start.getUTCMonth() === 3 ? 5 :
start.getUTCMonth() === 11 ? 0 : start.getUTCMonth() + 1,
));
const id = toSeasonId(start.getUTCFullYear(), start.getUTCMonth() + 1);
const key = start.getUTCFullYear() + '_' + ('' + (start.getUTCMonth() + 1)).padStart(2, '0');
return {
id,
key,
index: getSeasonIndex(start.getUTCFullYear(), start.getUTCMonth() + 1),
start,
end,
complete: Date.now() > end.getTime(),
};
}
export function getPreviousSeason(season: Season | number): Season | null
export function getPreviousSeason(year: number, month: number): Season | null
export function getPreviousSeason(season: Season | number, month?: number): Season | null {
const current_start =
typeof season === 'number' && typeof month === 'number' ?
new Date(Date.UTC(season, month)) :
typeof season === 'number' ? getSeasonStartDateByIndex(season) :
new Date(season.start.getTime());
const start = new Date(Date.UTC(
current_start.getUTCFullYear() - (current_start.getUTCMonth() === 0 ? 1 : 0),
current_start.getUTCMonth() === 0 ? 11 : current_start.getUTCMonth() - 1,
));
if (start.getUTCFullYear() < 2018 || (start.getUTCFullYear() === 2018 && start.getUTCMonth() < 3)) return null;
const end = new Date(Date.UTC(
start.getUTCFullYear() + (start.getUTCMonth() === 11 ? 1 : 0),
start.getUTCFullYear() === 2018 && start.getUTCMonth() === 3 ? 5 :
start.getUTCMonth() === 11 ? 0 : start.getUTCMonth() + 1,
));
const id = toSeasonId(start.getUTCFullYear(), start.getUTCMonth() + 1);
const key = start.getUTCFullYear() + '_' + ('' + (start.getUTCMonth() + 1)).padStart(2, '0');
if (start.getUTCFullYear() === 2018 && start.getUTCMonth() === 4) {
start.setUTCMonth(3);
}
return {
id,
key,
index: getSeasonIndex(start.getUTCFullYear(), start.getUTCMonth() + 1),
start,
end,
complete: Date.now() > end.getTime(),
};
}
export function getSeasonIndex(year: number, month: number) {
const nextyear = month === 12 ? year + 1 : year;
if (year < 2000) throw new Error('Invalid season ID');
if (nextyear >= 2100) throw new Error('Invalid season ID');
if (month < 1) throw new Error('Invalid season ID');
if (month > 12) throw new Error('Invalid season ID');
if (year < 2018) throw new Error('Invalid season ID');
if (year === 2018 && month < 4) throw new Error('Invalid season ID');
const now = new Date();
if (year > now.getUTCFullYear()) throw new Error('Invalid season ID');
if (year === now.getUTCFullYear() && month > (now.getUTCMonth() + 1)) throw new Error('Invalid season ID');
if (year === 2018 && month === 4) month = 5;
const i = year * 12 + (month - 1);
return i - 24220;
}
export function getSeasonStartDateByIndex(index: number) {
if (index < 0) throw new Error('Invalid season index');
if (index === 0) return new Date(Date.UTC(2018, 3));
const i = index + 24220;
const year = Math.floor(i / 12);
const month = (i % 12) + 1;
if (year < 2018) throw new Error('Invalid season index');
if (year === 2018 && month < 4) throw new Error('Invalid season index');
const now = new Date();
if (year > now.getUTCFullYear()) throw new Error('Invalid season index');
if (year === now.getUTCFullYear() && month > (now.getUTCMonth() + 1)) throw new Error('Invalid season index');
return new Date(Date.UTC(year, month - 1));
}
export function toSeasonId(year: number, month: number) {
if (year === 2018 && month === 4) month = 5;
const nextyear = month === 12 ? year + 1 : year;
const nextmonth = month === 12 ? 1 : month + 1;
if (year < 2000) throw new Error('Invalid season ID');
if (nextyear >= 2100) throw new Error('Invalid season ID');
if (month < 1) throw new Error('Invalid season ID');
if (month > 12) throw new Error('Invalid season ID');
if (year < 2018) throw new Error('Invalid season ID');
if (year === 2018 && month < 4) throw new Error('Invalid season ID');
const now = new Date();
if (year > now.getUTCFullYear()) throw new Error('Invalid season ID');
if (year === now.getUTCFullYear() && month > (now.getUTCMonth() + 1)) throw new Error('Invalid season ID');
if (year === 2018 && month === 5) month = 4;
return ('' + (year - 2000)).padStart(2, '0') +
('' + month).padStart(2, '0') +
'01T00_' +
('' + (nextyear - 2000)).padStart(2, '0') +
('' + nextmonth).padStart(2, '0') +
'01T00';
}
export enum Rule {
SPLAT_ZONES = 'splat_zones',
TOWER_CONTROL = 'tower_control',
RAINMAKER = 'rainmaker',
CLAM_BLITZ = 'clam_blitz',
}

View File

@ -1,15 +1,16 @@
import fetch from 'node-fetch';
import createDebug from 'debug';
import { v4 as uuidgen } from 'uuid';
import { WebServiceToken } from './znc-types.js';
import { NintendoAccountUser } from './na.js';
import { ErrorResponse } from './util.js';
import ZncApi from './znc.js';
import { ActiveFestivals, CoopResult, CoopResults, CoopSchedules, HeroRecords, NicknameAndIcons, PastFestivals, Records, Result, Results, Schedules, ShareResponse, ShopMerchandises, Stages, Timeline, WebServiceError, XPowerRankingSummary } from './splatnet2-types.js';
import { randomUUID } from 'node:crypto';
import { Cookie, fetch, FormData, getSetCookies } from 'undici';
import { WebServiceToken } from './coral-types.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';
@ -23,30 +24,45 @@ export const updateIksmSessionLastUsed: {
} = {};
export default class SplatNet2Api {
constructor(
protected _session_expired = false;
protected constructor(
public iksm_session: string,
public useragent: 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: method,
method,
headers: Object.assign({
'Upgrade-Insecure-Requests': '1',
'User-Agent': this.useragent,
'Cookie': 'iksm_session=' + encodeURIComponent(this.iksm_session),
'dnt': '1',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept': '*/*',
'Accept-Language': 'en-GB,en-US;q=0.8',
'X-Requested-With': 'com.nintendo.znca',
'Referrer': 'https://app.splatoon2.nintendo.net/home',
'X-Requested-With': 'XMLHttpRequest',
// 'X-Timezone-Offset': (new Date()).getTimezoneOffset().toString(),
'X-Timezone-Offset': '0',
'X-Unique-Id': this.unique_id,
}, headers),
body: body,
});
body,
signal,
}).finally(cancel);
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] Unknown error', response, await response.text());
throw await SplatNet2ErrorResponse.fromResponse(response, '[splatnet2] Non-200 status code');
}
updateIksmSessionLastUsed.handler?.call(null, this.iksm_session);
@ -54,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() {
@ -89,7 +105,11 @@ export default class SplatNet2Api {
return this.fetch<HeroRecords>('/records/hero');
}
async getXPowerRankingSummary(season: string | Date) {
async getXPowerRankingSummary(season: string | Date | Season) {
if (typeof season === 'object' && 'start' in season) {
season = season.id;
}
if (season instanceof Date) {
season = toSeasonId(season.getUTCFullYear(), season.getUTCMonth() + 1);
}
@ -106,7 +126,11 @@ export default class SplatNet2Api {
return this.fetch<XPowerRankingSummary>('/x_power_ranking/' + season + '/summary');
}
async getXPowerRankingLeaderboard(season: string | Date, rule: XPowerRankingRule, page: number = 1) {
async getXPowerRankingLeaderboard(season: string | Date | Season, rule: XPowerRankingRule, page: number = 1) {
if (typeof season === 'object' && 'start' in season) {
season = season.id;
}
if (season instanceof Date) {
season = toSeasonId(season.getUTCFullYear(), season.getUTCMonth() + 1);
}
@ -120,19 +144,27 @@ export default class SplatNet2Api {
throw new Error('Invalid season ID');
}
return this.fetch<unknown>('/x_power_ranking/' + season + '/' + rule + '?page=' + page);
return this.fetch<XPowerRankingRecords>('/x_power_ranking/' + season + '/' + rule + '?page=' + page);
}
async getPastFestivals() {
return this.fetch<PastFestivals>('/festivals/pasts');
}
async getLeagueMatchRanking(id: string, region: LeagueRegion) {
async getLeagueMatchRanking(id: string, region: LeagueRegion): Promise<LeagueMatchRankings>
async getLeagueMatchRanking(date: Date, type: LeagueType, region: LeagueRegion): Promise<LeagueMatchRankings>
async getLeagueMatchRanking(id: string | Date, arg1: LeagueRegion | LeagueType, arg2?: LeagueRegion) {
const region = id instanceof Date ? arg2! : arg1 as LeagueRegion;
if (id instanceof Date) {
id = toLeagueId(id, arg1 as LeagueType);
}
if (!id.match(LEAGUE_ID)) {
throw new Error('Invalid league ID');
}
return this.fetch<PastFestivals>('/league_match_ranking/' + id + '/' + region);
return this.fetch<LeagueMatchRankings>('/league_match_ranking/' + id + '/' + region);
}
async getResults() {
@ -160,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"
@ -207,22 +239,44 @@ ${colour}
});
}
static async createWithZnc(nso: ZncApi, user: NintendoAccountUser) {
const data = await this.loginWithZnc(nso, user);
return {
splatnet: new this(data.iksm_session, data.useragent),
data,
};
static async createWithCoral(coral: CoralApiInterface, user: NintendoAccountUserCoral) {
const data = await this.loginWithCoral(coral, user);
return {splatnet: this.createWithSavedToken(data), data};
}
static async loginWithZnc(nso: ZncApi, user: NintendoAccountUser) {
const webserviceToken = await nso.getWebServiceToken(SPLATNET2_WEBSERVICE_ID);
return this.loginWithWebServiceToken(webserviceToken.result, user);
static createWithSavedToken(data: SplatNet2AuthData) {
return new this(
data.iksm_session,
data.user_id,
data.useragent,
);
}
static async loginWithWebServiceToken(webserviceToken: WebServiceToken, user: NintendoAccountUser) {
static createWithCliTokenData(data: SplatNet2CliTokenData) {
return new this(
data.iksm_session,
data.user_id,
SPLATNET2_WEBSERVICE_USERAGENT,
);
}
static createWithIksmSession(iksm_session: string, unique_id: string) {
return new this(
iksm_session,
unique_id,
SPLATNET2_WEBSERVICE_USERAGENT,
);
}
static async loginWithCoral(coral: CoralApiInterface, user: NintendoAccountUserCoral) {
const webserviceToken = await coral.getWebServiceToken(SPLATNET2_WEBSERVICE_ID);
return this.loginWithWebServiceToken(webserviceToken, user);
}
static async loginWithWebServiceToken(
webserviceToken: WebServiceToken, user: NintendoAccountUserCoral
): Promise<SplatNet2AuthData> {
const url = new URL(SPLATNET2_WEBSERVICE_URL);
url.search = new URLSearchParams({
lang: user.language,
@ -230,41 +284,40 @@ ${colour}
na_lang: user.language,
}).toString();
const [signal, cancel] = timeoutSignal();
const response = await fetch(url.toString(), {
headers: {
'Upgrade-Insecure-Requests': '1',
'User-Agent': SPLATNET2_WEBSERVICE_USERAGENT,
'x-appplatform': 'android',
'x-appcolorscheme': 'DARK',
'x-gamewebtoken': webserviceToken.accessToken,
'dnt': '1',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-GB,en-US;q=0.8',
'X-Requested-With': 'com.nintendo.znca',
},
});
signal,
}).finally(cancel);
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, 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);
@ -272,45 +325,60 @@ ${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);
debug('SplatNet 2 user', {language, region, user_id, nsa_id});
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,
region,
user_id: user_id?.replace(/^(.{6}).*/, '$1****'),
nsa_id: nsa_id?.replace(/^(.{6}).*/, '$1****'),
});
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 function toSeasonId(year: number, month: number) {
const nextyear = month === 12 ? year + 1 : year;
const nextmonth = month === 12 ? 1 : month + 1;
export class SplatNet2ErrorResponse extends ErrorResponse<WebServiceError> {}
if (year < 2000) throw new Error('Invalid season ID');
if (nextyear >= 2100) throw new Error('Invalid season ID');
export interface SplatNet2AuthData {
webserviceToken: WebServiceToken;
url: string;
cookies: string | Cookie[];
body: string;
return ('' + (year - 2000)).padStart(2, '0') +
('' + month).padStart(2, '0') +
'01T00_' +
('' + (nextyear - 2000)).padStart(2, '0') +
('' + nextmonth).padStart(2, '0') +
'01T00';
language: string;
region: string;
/** Splatoon 2 player ID aka. unique_id */
user_id: string;
nsa_id: string;
iksm_session: string;
expires_at: number;
useragent: string;
}
export enum XPowerRankingRule {
SPLAT_ZONES = 'splat_zones',
TOWER_CONTROL = 'tower_control',
RAINMAKER = 'rainmaker',
CLAM_BLITZ = 'clam_blitz',
export interface SplatNet2CliTokenData {
iksm_session: string;
language: string;
region: string;
user_id: string;
nsa_id: string;
}
export function toLeagueId(date: Date, type: LeagueType) {

View 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

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,18 @@
import { Response as NodeFetchResponse } from 'node-fetch';
import * as util from 'node:util';
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;
@ -6,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 {
@ -19,15 +48,32 @@ export class ErrorResponse<T = unknown> extends Error {
} else if (typeof body !== 'undefined') {
this.data = body;
}
const stack = this.stack ?? (this.name + ': ' + message);
const lines = stack.split('\n');
const head = lines.shift()!;
Object.defineProperty(this, 'stack', {
value: head + '\n' +
' 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;
},
});

View File

@ -1,166 +1,349 @@
import fetch from 'node-fetch';
import createDebug from 'debug';
import { ActiveEvent, Announcements, CurrentUser, Event, Friend, Presence, PresencePermissions, User, WebService, WebServiceToken, ZncStatus, ZncSuccessResponse } from './znc-types.js';
import { ErrorResponse } from './util.js';
import ZncApi from './znc.js';
import { version } from '../util/product.js';
import { NintendoAccountUser } from './na.js';
import { SavedToken } from '../common/auth/nso.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 ZncApi {
static useragent: string | null = null;
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 = ZncProxyApi.useragent
) {}
async fetch<T = unknown>(url: string, method = 'GET', body?: string, headers?: object) {
const response = await fetch(this.url + url, {
method: method,
headers: Object.assign({
'Authorization': 'na ' + this.token,
'User-Agent': (this.useragent ? this.useragent + ' ' : '') + 'nxapi/' + version,
}, headers),
body: body,
});
debug('fetch %s %s, response %s', method, url, response.status);
if (response.status === 204) return null!;
if (response.status !== 200) {
throw new ErrorResponse('[zncproxy] Unknown error', response, await response.text());
}
const data = await response.json() as T;
return data;
public useragent = getAdditionalUserAgents()
) {
super();
}
async call<T = unknown>(url: string, parameter = {}): Promise<ZncSuccessResponse<T>> {
throw new Error('Not supported in ZncProxyApi');
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');
}
const [signal, cancel] = timeoutSignal();
const response = await fetch(new URL(url, base_url), {
method,
headers,
body,
signal,
}).finally(cancel);
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.ok) {
throw await ZncProxyErrorResponse.fromResponse(response, '[zncproxy] Non-2xx status code');
}
const data = (response.status === 204 ? {} : await response.json()) as T;
return defineResponse(data, response);
}
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: ZncStatus.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: ZncStatus.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: ZncStatus.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: ZncStatus.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: ZncStatus.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: ZncStatus.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: ZncStatus.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: ZncStatus.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 result = await this.fetchProxyApi<{user: FriendCodeUser}>('friendcode/' + friend_code);
return createResult(result, result.user);
}
// async sendFriendRequest(nsa_id: string): Promise<Result<{}>> {
// throw new Error('Not supported in ZncProxyApi');
// }
async getCurrentUser() {
const response = await this.fetch<{user: CurrentUser}>('/user');
return {status: ZncStatus.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 result = await this.fetchProxyApi<{friendcode: FriendCodeUrl}>('friendcode');
return createResult(result, result.friendcode);
}
async getCurrentUserPermissions() {
const user = await this.getCurrentUser();
return {
status: ZncStatus.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<ZncSuccessResponse<{}>> {
// 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: ZncStatus.OK as const, result: response.token, correlationId: ''};
}
async getToken(token: string, user: NintendoAccountUser): ReturnType<ZncApi['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;
friends?: string[];
friends_presence?: string[];
}
export enum ZncPresenceEventStreamEvent {
FRIEND_ONLINE = '0',
FRIEND_OFFLINE = '1',
FRIEND_TITLE_CHANGE = '2',
FRIEND_TITLE_STATECHANGE = '3',
PRESENCE_UPDATED = '4',
}
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) {
const response = await fetch(presence_url);
export async function getPresenceFromUrl(presence_url: string, useragent?: string) {
const [signal, cancel, controller] = timeoutSignal();
const response = await fetch(presence_url, {
headers: {
'User-Agent': getUserAgent(useragent),
},
signal,
}).finally(cancel);
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 :
@ -170,5 +353,5 @@ export async function getPresenceFromUrl(presence_url: string) {
throw new Error('Invalid presence data');
}
return [presence, user] as const;
return defineResponse([presence, user, data as unknown] as const, response);
}

View File

@ -1,206 +0,0 @@
export interface ZncSuccessResponse<T = unknown> {
status: ZncStatus.OK;
result: T;
correlationId: string;
}
export interface ZncErrorResponse {
status: ZncStatus | number;
errorMessage: string;
correlationId: string;
}
export enum ZncStatus {
OK = 0,
BAD_REQUEST = 9400,
INVALID_TOKEN = 9403,
TOKEN_EXPIRED = 9404,
UPGRADE_REQUIRED = 9427,
}
export type ZncResponse<T = unknown> = ZncSuccessResponse<T> | ZncErrorResponse;
/** /v3/Account/Login */
export interface AccountLogin {
user: CurrentUser;
webApiServerCredential: {
accessToken: string;
expiresIn: number;
};
firebaseCredential: {
accessToken: string;
expiresIn: number;
};
}
/** /v3/Account/GetToken */
export type AccountToken = AccountLogin;
/** /v1/Announcement/List */
export type Announcements = Announcement[];
export interface Announcement {
announcementId: number;
priority: number;
forceDisplayEndDate: number;
distributionDate: number;
title: string;
description: string;
}
/** /v3/Friend/List */
export interface Friends {
friends: Friend[];
}
export interface Friend {
id: number;
nsaId: string;
imageUri: string;
name: string;
isFriend: boolean;
isFavoriteFriend: boolean;
isServiceUser: boolean;
friendCreatedAt: number;
presence: Presence;
}
export interface Presence {
state: PresenceState;
updatedAt: number;
logoutAt: number;
game: Game | {};
}
export enum PresenceState {
/** Offline */
OFFLINE = 'OFFLINE',
/** A console linked to this account is online, but the user isn't selected in an application */
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?)
*/
PLAYING = 'PLAYING',
}
export interface Game {
name: string;
imageUri: string;
shopUri: string;
totalPlayTime: number;
/** 0 if never played before */
firstPlayedAt: number;
sysDescription: string;
}
/** /v1/Game/ListWebServices */
export type WebServices = WebService[];
export interface WebService {
id: number;
uri: string;
customAttributes: WebServiceAttribute[];
whiteList: string[];
name: string;
imageUri: string;
}
export interface WebServiceAttribute {
attrValue: string;
attrKey: string;
}
/** /v1/Event/GetActiveEvent */
export type GetActiveEventResult = ActiveEvent | {};
export interface ActiveEvent extends Event {
activateId: string;
}
/** /v1/Event/Show */
export interface Event {
id: number;
name: string;
description: string;
shareUri: string;
ownerUserId: number;
members: EventMember[];
passCode: string;
eventType: 3; // ??
allowJoinGameWithoutCoral: boolean;
game: {
id: number;
};
imageUri: string;
}
export interface EventMember {
id: number;
name: string;
imageUri: string;
isPlaying: boolean;
isInvited: boolean;
isJoinedVoip: boolean;
}
/** /v3/User/Show */
export interface User {
id: number;
nsaId: string;
imageUri: string;
name: string;
}
/** /v3/User/ShowSelf */
export interface CurrentUser {
id: number;
nsaId: string;
imageUri: string;
name: string;
supportId: string;
isChildRestricted: boolean;
etag: string;
links: {
nintendoAccount: {
membership: {
active: {
active: boolean;
} | boolean;
};
};
friendCode: {
regenerable: boolean;
regenerableAt: number;
id: string;
};
};
permissions: {
presence: PresencePermissions;
};
presence: Presence;
}
export enum PresencePermissions {
FRIENDS = 'FRIENDS',
FAVORITE_FRIENDS = 'FAVORITE_FRIENDS',
SELF = 'SELF',
}
/** /v3/User/Permissions/ShowSelf */
export interface CurrentUserPermissions {
etag: string;
permissions: {
presence: PresencePermissions;
};
}
/** /v2/Game/GetWebServiceToken */
export interface WebServiceToken {
accessToken: string;
expiresIn: number;
}

View File

@ -1,283 +0,0 @@
import fetch from 'node-fetch';
import { v4 as uuidgen } from 'uuid';
import createDebug from 'debug';
import { f, FlapgIid } from './f.js';
import { AccountLogin, AccountToken, Announcements, CurrentUser, CurrentUserPermissions, Event, Friends, GetActiveEventResult, PresencePermissions, User, WebServices, WebServiceToken, ZncResponse, ZncStatus } from './znc-types.js';
import { getNintendoAccountToken, getNintendoAccountUser, NintendoAccountUser } from './na.js';
import { ErrorResponse } from './util.js';
import { JwtPayload } from '../util/jwt.js';
const debug = createDebug('nxapi:api:znc');
const ZNCA_PLATFORM = 'Android';
const ZNCA_PLATFORM_VERSION = '8.0.0';
const ZNCA_VERSION = '2.1.1';
const ZNCA_USER_AGENT = `com.nintendo.znca/${ZNCA_VERSION}(${ZNCA_PLATFORM}/${ZNCA_PLATFORM_VERSION})`;
const ZNC_URL = 'https://api-lp1.znc.srv.nintendo.net';
export const ZNCA_CLIENT_ID = '71b963c1b7b6d119';
export default class ZncApi {
static useragent: string | null = null;
constructor(
public token: string,
public useragent: string | null = ZncApi.useragent
) {}
async fetch<T = unknown>(url: string, method = 'GET', body?: string, headers?: object) {
const response = await fetch(ZNC_URL + url, {
method: method,
headers: Object.assign({
'X-Platform': ZNCA_PLATFORM,
'X-ProductVersion': ZNCA_VERSION,
'Authorization': 'Bearer ' + this.token,
'Content-Type': 'application/json; charset=utf-8',
'User-Agent': ZNCA_USER_AGENT,
}, headers),
body: body,
});
debug('fetch %s %s, response %s', method, url, response.status);
const data = await response.json() as ZncResponse<T>;
if ('errorMessage' in data) {
throw new ErrorResponse('[znc] ' + data.errorMessage, response, data);
}
if (data.status !== ZncStatus.OK) {
throw new ErrorResponse('[znc] Unknown error', response, data);
}
return data;
}
async call<T = unknown>(url: string, parameter = {}) {
const uuid = uuidgen();
return this.fetch<T>(url, 'POST', JSON.stringify({
parameter,
requestId: uuid,
}));
}
async getAnnouncements() {
return this.call<Announcements>('/v1/Announcement/List');
}
async getFriendList() {
return this.call<Friends>('/v3/Friend/List');
}
async addFavouriteFriend(nsaid: string) {
return this.call<{}>('/v3/Friend/Favorite/Create', {
nsaId: nsaid,
});
}
async removeFavouriteFriend(nsaid: string) {
return this.call<{}>('/v3/Friend/Favorite/Delete', {
nsaId: nsaid,
});
}
async getWebServices() {
return this.call<WebServices>('/v1/Game/ListWebServices');
}
async getActiveEvent() {
return this.call<GetActiveEventResult>('/v1/Event/GetActiveEvent');
}
async getEvent(id: number) {
return this.call<Event>('/v1/Event/Show', {
id,
});
}
async getUser(id: number) {
return this.call<User>('/v3/User/Show', {
id,
});
}
async getCurrentUser() {
return this.call<CurrentUser>('/v3/User/ShowSelf');
}
async getCurrentUserPermissions() {
return this.call<CurrentUserPermissions>('/v3/User/Permissions/ShowSelf');
}
async updateCurrentUserPermissions(to: PresencePermissions, from: PresencePermissions, etag: string) {
return this.call<{}>('/v3/User/Permissions/UpdateSelf', {
permissions: {
presence: {
toValue: to,
fromValue: from,
},
},
etag,
});
}
async getWebServiceToken(id: string) {
const uuid = uuidgen();
const timestamp = '' + Math.floor(Date.now() / 1000);
const useragent = this.useragent ?? undefined;
const data = await f(this.token, timestamp, uuid, FlapgIid.APP, useragent);
const req = {
id,
registrationToken: this.token,
f: data.f,
requestId: uuid,
timestamp,
};
return this.call<WebServiceToken>('/v2/Game/GetWebServiceToken', req);
}
async getToken(token: string, user: NintendoAccountUser) {
const uuid = uuidgen();
const timestamp = '' + Math.floor(Date.now() / 1000);
// Nintendo Account token
const nintendoAccountToken = await getNintendoAccountToken(token, ZNCA_CLIENT_ID);
const id_token = nintendoAccountToken.id_token;
const useragent = this.useragent ?? undefined;
const fdata = await f(id_token, timestamp, uuid, FlapgIid.NSO, useragent);
const req = {
naBirthday: user.birthday,
timestamp,
f: fdata.f,
requestId: uuid,
naIdToken: id_token,
};
const data = await this.call<AccountToken>('/v3/Account/GetToken', req);
return {
uuid,
timestamp,
nintendoAccountToken,
// user,
f: fdata,
nsoAccount: data.result,
credential: data.result.webApiServerCredential,
};
}
static async createWithSessionToken(token: string, useragent = ZncApi.useragent) {
const data = await this.loginWithSessionToken(token, useragent);
return {
nso: new this(data.credential.accessToken, useragent),
data,
};
}
async renewToken(token: string, user: NintendoAccountUser) {
const data = await this.getToken(token, user);
this.token = data.credential.accessToken;
return data;
}
static async loginWithSessionToken(token: string, useragent = ZncApi.useragent) {
const uuid = uuidgen();
const timestamp = '' + Math.floor(Date.now() / 1000);
// Nintendo Account token
const nintendoAccountToken = await getNintendoAccountToken(token, ZNCA_CLIENT_ID);
// Nintendo Account user data
const user = await getNintendoAccountUser(nintendoAccountToken);
const id_token = nintendoAccountToken.id_token;
const fdata = await f(id_token, timestamp, uuid, FlapgIid.NSO, useragent ?? undefined);
debug('Getting Nintendo Switch Online app token');
const response = await fetch(ZNC_URL + '/v3/Account/Login', {
method: 'POST',
headers: {
'X-Platform': ZNCA_PLATFORM,
'X-ProductVersion': ZNCA_VERSION,
'Content-Type': 'application/json; charset=utf-8',
'User-Agent': ZNCA_USER_AGENT,
},
body: JSON.stringify({
parameter: {
naIdToken: nintendoAccountToken.id_token,
naBirthday: user.birthday,
naCountry: user.country,
language: user.language,
timestamp,
requestId: uuid,
f: fdata.f,
},
}),
});
debug('fetch %s %s, response %s', 'POST', '/v3/Account/Login', response.status);
const data = await response.json() as ZncResponse<AccountLogin>;
if ('errorMessage' in data) {
throw new ErrorResponse('[znc] ' + data.errorMessage, response, data);
}
if (data.status !== 0) {
throw new ErrorResponse('[znc] Unknown error', response, data);
}
debug('Got Nintendo Switch Online app token', data);
return {
uuid,
timestamp,
nintendoAccountToken,
user,
f: fdata,
nsoAccount: data.result,
credential: data.result.webApiServerCredential,
};
}
}
export interface ZncJwtPayload extends JwtPayload {
isChildRestricted: boolean;
membership: {
active: boolean;
};
aud: string;
exp: number;
iat: number;
iss: 'api-lp1.znc.srv.nintendo.net';
/** User ID (CurrentUser.id, not CurrentUser.nsaID) */
sub: number;
typ: 'id_token';
}
export interface ZncWebServiceJwtPayload extends JwtPayload {
isChildRestricted: boolean;
aud: string;
exp: number;
iat: number;
iss: 'api-lp1.znc.srv.nintendo.net';
jti: string;
/** User ID (CurrentUser.id, not CurrentUser.nsaID) */
sub: number;
links: {
networkServiceAccount: {
/** NSA ID (CurrentUser.nsaID) */
id: string;
};
};
typ: 'id_token';
membership: {
active: boolean;
};
}

View File

@ -1,9 +1,9 @@
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/app-main-bundle.cjs` (with the command line executable at `dist/bundle/cli-bundle.js`).
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) 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
View 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
View 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'));

View 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,
},
});

View File

@ -0,0 +1,368 @@
import React, { useCallback, useEffect, useState } from 'react';
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 from '../ipc.js';
import { RequestState, Root, useAccentColour, useAsync, useColourScheme } from '../util.js';
export interface AddFriendProps {
user: string;
friendcode?: string;
}
enum SendFriendRequestState {
NOT_LOADING,
SENDING,
SENT,
ERROR,
}
type SendFriendRequestStateArray =
[SendFriendRequestState.NOT_LOADING] |
[SendFriendRequestState.SENDING, FriendCodeUser, string] |
[SendFriendRequestState.SENT, FriendCodeUser, string, Friend | null] |
[SendFriendRequestState.ERROR, FriendCodeUser, string, Error];
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 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 [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]));
const [friends, , friends_state, forceRefreshFriends] = useAsync(useCallback(() => token ?
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(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 (!props.lookupUser) return;
setSendFriendRequestState([SendFriendRequestState.SENDING, props.lookupUser, props.friendcode]);
try {
const {result, friend} = await ipc.addNsoFriend(props.token, props.lookupUser.nsaId);
setSendFriendRequestState([SendFriendRequestState.SENT, props.lookupUser, props.friendcode, friend]);
} catch (err) {
setSendFriendRequestState([SendFriendRequestState.ERROR, props.lookupUser, props.friendcode, err as Error]);
}
}, [props.token, props.lookupUser, props.friendcode, send_state]);
const showSendFriendRequestErrorDetails = useCallback(() => {
if (send_state[0] !== SendFriendRequestState.ERROR) return;
alert(send_state[3]);
}, [send_state]);
const onFriendCodeKeyPress = useCallback((event: NativeSyntheticEvent<TextInputKeyPressEventData>) =>
event.nativeEvent.key === 'Escape' && window.close(), []);
return <View style={styles.main}>
{props.setFriendCode ? <>
<Text style={theme.text}>{t('title')}</Text>
<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>
</> : 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}
{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} />
<View style={styles.targetUserDetail}>
<Text style={[styles.targetUserName, theme.text]}>{props.lookupUser.name}</Text>
<Text style={[styles.targetUserNsaId, theme.text]}>
{t('nsa_id')}: <Text style={styles.targetUserNsaIdValue}>{props.lookupUser.nsaId}</Text>
</Text>
<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>
{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]}>
<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>
</View>;
}
const styles = StyleSheet.create({
loading: {
flex: 1,
paddingVertical: 50,
paddingHorizontal: 20,
justifyContent: 'center',
},
main: {
flex: 1,
paddingVertical: 20,
paddingHorizontal: 20,
},
help: {
marginTop: 8,
fontSize: 13,
opacity: 0.7,
},
friendCodeInputContainer: {
marginTop: 16,
flexDirection: 'row',
justifyContent: 'center',
},
friendCodeInput: {
marginTop: 0,
flex: 1,
fontSize: 18,
fontFamily: 'monospace',
paddingVertical: 8,
paddingHorizontal: 14,
},
activityIndicator: {
marginLeft: 10,
},
iconTouchable: {
marginLeft: 10,
justifyContent: 'center',
},
icon: {
fontSize: 20,
},
textInput: {
marginTop: 8,
paddingVertical: 5,
paddingHorizontal: 10,
borderRadius: 3,
fontSize: 13,
},
lookupErrorNoFriendCodeField: {
},
lookupErrorIcon: {
marginRight: 10,
},
targetUser: {
marginTop: 20,
padding: 14,
borderRadius: 3,
flexDirection: 'row',
},
targetUserNoFriendCodeField: {
marginTop: 0,
},
targetUserImage: {
marginRight: 14,
width: 100,
},
targetUserDetail: {
flex: 1,
},
targetUserName: {
fontSize: 18,
fontWeight: '500',
marginBottom: 8,
},
targetUserNsaId: {
fontSize: 13,
opacity: 0.7,
},
targetUserNsaIdValue: {
fontFamily: 'monospace',
userSelect: 'all',
},
targetUserCoralId: {
fontSize: 13,
opacity: 0.7,
},
targetUserCoralIdValue: {
fontFamily: 'monospace',
userSelect: 'all',
},
friendRequestState: {
marginTop: 10,
},
friendRequestActivityIndicator: {
marginRight: 10,
},
friendRequestStateIcon: {
marginRight: 10,
},
buttons: {
marginTop: 20,
flexDirection: 'row',
justifyContent: 'flex-end',
},
button: {
marginLeft: 10,
},
});
const light = StyleSheet.create({
text: {
color: TEXT_COLOUR_LIGHT,
},
textInput: {
backgroundColor: HIGHLIGHT_COLOUR_LIGHT,
color: TEXT_COLOUR_LIGHT,
},
targetUser: {
backgroundColor: HIGHLIGHT_COLOUR_LIGHT,
},
});
const dark = StyleSheet.create({
text: {
color: TEXT_COLOUR_DARK,
},
textInput: {
backgroundColor: HIGHLIGHT_COLOUR_DARK,
color: TEXT_COLOUR_DARK,
},
targetUser: {
backgroundColor: HIGHLIGHT_COLOUR_DARK,
},
});

View File

@ -1,70 +0,0 @@
import React, { useCallback } from 'react';
import { StyleSheet, Text, useColorScheme, View } from 'react-native';
import { NintendoAccountUser } from '../../api/na.js';
import { SavedToken } from '../../common/auth/nso.js';
import { SavedMoonToken } from '../../common/auth/moon.js';
import ipc from './ipc.js';
import { useAsync } from './util.js';
export interface AppProps {
//
}
async function getAccounts() {
const ids = await ipc.listNintendoAccounts();
const accounts: {
user: NintendoAccountUser;
nso: SavedToken | null;
moon: SavedMoonToken | null;
}[] = [];
for (const id of ids ?? []) {
const nsotoken = await ipc.getNintendoAccountNsoToken(id);
const moontoken = await ipc.getNintendoAccountMoonToken(id);
const nso = nsotoken ? await ipc.getSavedNsoToken(nsotoken) ?? null : null;
const moon = moontoken ? await ipc.getSavedMoonToken(moontoken) ?? null : null;
if (!nso && !moon) continue;
accounts.push({user: nso?.user ?? moon!.user, nso, moon});
}
return accounts;
}
function App(props: AppProps) {
const theme = useColorScheme() === 'light' ? light : dark;
const [users] = useAsync(useCallback(() => getAccounts(), [ipc]));
console.log(users);
return <View style={styles.app}>
<Text>Hello from React!</Text>
{users?.map(u => <Text key={u.user.id} style={theme.text}>
{u.user.id} - {u.user.nickname}
</Text>)}
</View>;
}
const styles = StyleSheet.create({
app: {
},
});
const light = StyleSheet.create({
text: {
color: '#212121',
},
});
const dark = StyleSheet.create({
text: {
color: '#f5f5f5',
},
});
export default App;

View File

@ -0,0 +1,190 @@
import React, { useCallback, useContext, useState } from 'react';
import { Button as NativeButton, Platform, Pressable, StyleSheet, Text, View } from 'react-native';
import { TEXT_COLOUR_LIGHT } from '../constants.js';
import ipc from '../ipc.js';
import { useAccentColour, useColourScheme, WindowFocusedContext } from '../util.js';
function ButtonMac(props: {
title: string;
primary?: boolean;
color?: string;
autoFocus?: boolean;
onPress?: () => void;
}) {
const styles = styles_mac;
const window_focused = useContext(WindowFocusedContext);
const colour_scheme = useColourScheme();
const accent_colour = useAccentColour();
const [hovered, setMouseOver] = useState(false);
const onMouseOver = useCallback(() => setMouseOver(true), []);
const onMouseOut = useCallback(() => setMouseOver(false), []);
const [pressed, setPressIn] = useState(false);
const onPressIn = useCallback(() => setPressIn(true), []);
const onPressOut = useCallback(() => setPressIn(false), []);
const pressed_appearance = window_focused && pressed && hovered;
const active = window_focused && (props.primary || pressed_appearance);
return <Pressable
style={[
styles.button,
colour_scheme === 'light' ? styles.buttonLight : null,
active ? {backgroundColor: props.color ?? accent_colour} : null,
]}
// @ts-expect-error react-native-web
onMouseOver={onMouseOver}
onMouseOut={onMouseOut}
onPress={props.onPress}
onPressIn={onPressIn}
onPressOut={onPressOut}
>
<View style={[
styles.inner,
active ? styles.innerActive : null,
active && pressed_appearance ? styles.innerPressed : null,
]}>
<Text style={[
styles.text,
colour_scheme === 'light' && !active ? styles.textLight : null,
]}>{props.title}</Text>
</View>
</Pressable>;
}
const styles_mac = StyleSheet.create({
button: {
// @ts-expect-error react-native-web
cursor: 'default',
lineHeight: 19,
borderRadius: 3,
boxShadow: '#00000030 0px 0px 1px',
},
buttonLight: {
backgroundColor: '#ffffff',
boxShadow: '#0000008a 0px 0px 1px',
},
inner: {
paddingHorizontal: 14,
paddingVertical: 2,
borderRadius: 3,
backgroundColor: '#ffffff40',
borderTopWidth: 0.5,
borderTopColor: '#ffffff3a',
},
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)',
},
text: {
fontSize: 13,
color: '#eaeaea',
textAlign: 'center',
},
textLight: {
color: '#0a0a0a',
},
});
function ButtonWindows(props: {
title: string;
primary?: boolean;
color?: string;
autoFocus?: boolean;
onPress?: () => void;
}) {
const styles = styles_windows;
const window_focused = useContext(WindowFocusedContext);
const colour_scheme = useColourScheme();
const accent_colour = useAccentColour();
const [hovered, setMouseOver] = useState(false);
const onMouseOver = useCallback(() => setMouseOver(true), []);
const onMouseOut = useCallback(() => setMouseOver(false), []);
const [pressed, setPressIn] = useState(false);
const onPressIn = useCallback(() => setPressIn(true), []);
const onPressOut = useCallback(() => setPressIn(false), []);
const active = window_focused && (props.primary || pressed);
return <Pressable
style={[
styles.button,
colour_scheme === 'light' ? styles.buttonLight : null,
window_focused && hovered ? styles.buttonHover : null,
colour_scheme === 'light' && window_focused && hovered ? styles.buttonLightHover : null,
active ? {backgroundColor: props.color ?? accent_colour} : null,
]}
// @ts-expect-error react-native-web
onMouseOver={onMouseOver}
onMouseOut={onMouseOut}
onPress={props.onPress}
onPressIn={onPressIn}
onPressOut={onPressOut}
>
<Text style={[
styles.text,
colour_scheme === 'light' && !active ? styles.textLight : null,
]}>{props.title}</Text>
</Pressable>;
}
const styles_windows = StyleSheet.create({
button: {
backgroundColor: '#ffffff20',
minWidth: 180,
paddingVertical: 8,
paddingHorizontal: 12,
justifyContent: 'center',
alignItems: 'center',
textAlign: 'center',
},
buttonLight: {
backgroundColor: '#00000020',
},
buttonHover: {
backgroundColor: '#ffffff30',
},
buttonLightHover: {
backgroundColor: '#00000030',
},
text: {
color: '#eaeaea',
textAlign: 'center',
},
textLight: {
color: TEXT_COLOUR_LIGHT,
},
});
function ButtonNative(props: {
title: string;
color?: string;
onPress?: () => void;
}) {
const accent_colour = useAccentColour();
return <NativeButton
title={props.title}
color={props.color ?? accent_colour}
onPress={props.onPress}
/>;
}
export default
Platform.OS === 'web' && ipc.platform === 'darwin' ? React.memo(ButtonMac) :
Platform.OS === 'web' && ipc.platform === 'win32' ? React.memo(ButtonWindows) :
React.memo(ButtonNative);

View 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',
},
});

View File

@ -0,0 +1,14 @@
import React from 'react';
import { Platform, Text } from 'react-native';
import { svg_styles } from './util.js';
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);

View File

@ -0,0 +1,9 @@
import React from 'react';
export const svg_styles: React.CSSProperties = {
height: '1.2em',
width: 'auto',
fill: 'currentColor',
alignSelf: 'center',
verticalAlign: -4,
};

View File

@ -0,0 +1,14 @@
import React from 'react';
import { Platform, Text } from 'react-native';
import { svg_styles } from './util.js';
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);

View File

@ -0,0 +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';

View 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',
},
});

View File

@ -0,0 +1,26 @@
import ipc from './ipc.js';
export const NSO_COLOUR = '#e60012';
export const NSO_COLOUR_DARK: `${typeof NSO_COLOUR}e0` = `${NSO_COLOUR}e0`;
export const DISCORD_COLOUR = '#5865f2';
export const BACKGROUND_COLOUR_MAIN_LIGHT = ipc.platform === 'win32' ? '#ffffff' : '#ececec';
export const BACKGROUND_COLOUR_MAIN_DARK = ipc.platform === 'win32' ? '#000000' : '#252424';
export const BACKGROUND_COLOUR_SECONDARY_LIGHT = '#ffffff';
export const BACKGROUND_COLOUR_SECONDARY_DARK = '#353535';
export const UPDATE_COLOUR = '#006064e0';
export const HIGHLIGHT_COLOUR_LIGHT = '#00000020';
export const HIGHLIGHT_COLOUR_DARK = '#ffffff20';
export const BORDER_COLOUR_LIGHT = '#00000020';
export const BORDER_COLOUR_DARK = '#00000080';
export const BORDER_COLOUR_SECONDARY_DARK = '#ffffff20';
export const TEXT_COLOUR_LIGHT = '#212121';
export const TEXT_COLOUR_DARK = '#f5f5f5';
export const TEXT_COLOUR_ACTIVE = '#3ba55d';
export const DEFAULT_ACCENT_COLOUR = NSO_COLOUR.substr(1).toUpperCase() + 'FF';

View File

@ -0,0 +1,288 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
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, 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 {
CORAL,
URL,
NONE,
}
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();
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.friendNsaId ?? null);
const [presenceUrl, setPresenceUrl] = useState('');
useEffect(() => {
if (!props.discordPresenceSource) {
setSelectedMode(props.friendNsaId ? DiscordSourceType.CORAL : DiscordSourceType.NONE);
} else if ('na_id' in props.discordPresenceSource) {
setSelectedMode(DiscordSourceType.CORAL);
setSelectedUserId(props.discordPresenceSource.na_id);
setSelectedFriendNsaId(props.discordPresenceSource.friend_nsa_id ?? null);
} else if ('url' in props.discordPresenceSource) {
setSelectedMode(DiscordSourceType.URL);
setPresenceUrl(props.discordPresenceSource.url);
}
}, [props.discordPresenceSource]);
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 ||
f.nsaId === selectedFriendNsaId), [friends, selectedFriendNsaId]);
const friend = useMemo(() => selectedFriendNsaId ? friends?.find(f => f.nsaId === selectedFriendNsaId) : undefined,
[selectedFriendNsaId, friends]);
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', () => forceRefreshFriends(), []);
useEffect(() => {
if (filtered_users?.length && !user) setSelectedUserId(filtered_users[0].user.id);
}, [filtered_users, user]);
useEffect(() => {
if (friends?.length && !friend) setSelectedFriendNsaId(friends[0].nsaId);
}, [friends, user]);
const save = useCallback(async () => {
if (selectedMode === DiscordSourceType.CORAL) {
if (!selectedUserId?.match(/^[0-9a-f]{16}$/)) throw new Error('Invalid Nintendo Account ID');
if (!selectedFriendNsaId?.match(/^[0-9a-f]{16}$/)) throw new Error('Invalid friend Network Service Account ID');
await ipc.setDiscordPresenceSource({na_id: selectedUserId, friend_nsa_id: selectedFriendNsaId});
} else if (selectedMode === DiscordSourceType.URL) {
await ipc.setDiscordPresenceSource({url: presenceUrl});
} else {
await ipc.setDiscordPresenceSource(null);
}
window.close();
}, [selectedMode, selectedUserId, selectedFriendNsaId, presenceUrl]);
return <View style={styles.main}>
<Text style={theme.text}>{t('title')}</Text>
<Text style={[styles.header, theme.text]}>{t('mode_heading')}</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>
{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<string> selectedValue={selectedUserId ?? ''} onValueChange={setSelectedUserId}
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}
/>)}
</Picker>
{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={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]}
>
{friends_with_presence.map(f => <Picker.Item key={f.nsaId} label={f.name} value={f.nsaId} />)}
</Picker>
</> : null}
</> : null}
{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}
{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>
</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,
},
picker: {
marginTop: 8,
paddingVertical: 4,
paddingHorizontal: 8,
borderWidth: 0,
borderRadius: 3,
fontSize: 13,
},
textInput: {
marginTop: 8,
paddingVertical: 5,
paddingHorizontal: 10,
borderRadius: 3,
fontSize: 13,
},
buttons: {
marginTop: 20,
flexDirection: 'row',
justifyContent: 'flex-end',
},
button: {
marginLeft: 10,
},
buttonPreferences: {
marginTop: 10,
marginLeft: 0,
flexDirection: 'row',
justifyContent: 'flex-start',
},
});
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,
},
});

View File

@ -0,0 +1,375 @@
/// <reference path="../react-native-web.d.ts" />
import React, { useCallback, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { ActivityIndicator, Image, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { CheckBox } from 'react-native-web';
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';
import ipc, { events } from '../ipc.js';
import { RequestState, Root, useAccentColour, useAsync, useColourScheme, useDiscordPresenceSource, useEventListener, useTimeSince } from '../util.js';
export interface FriendProps {
user: string;
friend: string;
}
export default function FriendWindow(props: FriendProps) {
const [accent_colour, setAccentColour] = React.useState(() => ipc.getAccentColour());
useEventListener(events, 'systemPreferences:accent-colour', setAccentColour, []);
const [discord_presence_source, discord_presence_source_state] = useDiscordPresenceSource();
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 [friends, , friends_state, forceRefreshFriends] = useAsync(useCallback(() => token ?
ipc.getNsoFriends(token) : Promise.resolve(null), [ipc, token]));
const friend = friends?.find(f => f.nsaId === props.friend);
useEffect(() => {
if (friends_state !== RequestState.LOADED) return;
const timeout = setTimeout(forceRefreshFriends, 40 * 1000);
return () => clearTimeout(timeout);
}, [ipc, token, friends_state]);
useEventListener(events, 'window:refresh', forceRefreshFriends, []);
useEffect(() => {
const handler = (event: KeyboardEvent) => event.key === 'Escape' && window.close();
window.addEventListener('keydown', handler);
return () => window.removeEventListener('keydown', handler);
}, []);
if (friends && !friend) throw new Error('Unknown friend');
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)} />
</View>
</Root>;
}
const discord_presence_active = discord_presence_source && 'na_id' in discord_presence_source &&
discord_presence_source.na_id === user.user.id &&
discord_presence_source.friend_nsa_id === friend.nsaId;
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 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>;
}
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.buttons}>
{props.showDiscordPresenceSetup ? <View style={styles.discord}>
<CheckBox
value={props.discordPresenceActive ?? false}
onValueChange={v => props.setDiscordPresenceActive?.(!!v)}
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}
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>
</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), 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) && 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]}>{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: 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);
}, [ipc, props.game.shopUri]);
const titleid = getTitleIdFromEcUrl(props.game.shopUri);
const first_played = props.game.firstPlayedAt ? new Date(props.game.firstPlayedAt * 1000) : null;
return <View style={styles.game}>
<Image source={{uri: props.game.imageUri, width: 80, height: 80}} style={styles.gameIcon} />
<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]}>
{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={t('game_shop')} onPress={openShop} color={'#' + accent_colour} />
</View>
</View>
</View>;
}
const styles = StyleSheet.create({
loading: {
flex: 1,
paddingVertical: 50,
paddingHorizontal: 20,
justifyContent: 'center',
},
main: {
paddingVertical: 20,
paddingHorizontal: 20,
flexDirection: 'row',
},
friend: {
marginRight: 20,
width: 130,
},
friendImage: {
marginBottom: 14,
},
friendName: {
fontSize: 18,
fontWeight: '500',
textAlign: 'center',
},
noPresence: {
marginTop: 8,
textAlign: 'center',
fontSize: 12,
opacity: 0.7,
},
right: {
flex: 1,
},
detail: {
flex: 1,
},
friendNsaId: {
fontSize: 13,
opacity: 0.7,
},
friendNsaIdValue: {
fontFamily: 'monospace',
userSelect: 'all',
},
friendCoralId: {
fontSize: 13,
opacity: 0.7,
},
friendCoralIdValue: {
fontFamily: 'monospace',
userSelect: 'all',
},
friendCreatedAt: {
marginTop: 8,
fontSize: 13,
opacity: 0.7,
},
presenceUpdatedAt: {
fontSize: 13,
opacity: 0.7,
},
canSeeUserPresence: {
marginTop: 8,
fontSize: 13,
opacity: 0.7,
},
buttons: {
marginTop: 20,
flexDirection: 'row',
justifyContent: 'flex-end',
},
discord: {
flex: 1,
marginRight: 20,
flexDirection: 'row',
alignItems: 'center',
},
discordCheckbox: {
marginRight: 10,
},
presenceText: {
marginTop: 8,
textAlign: 'center',
fontSize: 12,
},
presenceTextOnline: {
color: TEXT_COLOUR_ACTIVE,
},
presenceTextOffline: {
opacity: 0.7,
},
game: {
marginBottom: 15,
flexDirection: 'row',
},
gameIcon: {
marginRight: 15,
},
gameDetail: {
flex: 1,
},
gameName: {
fontSize: 16,
fontWeight: '400',
userSelect: 'text',
},
gameActivity: {
marginTop: 5,
fontSize: 13,
userSelect: 'text',
},
gameTotalPlayTime: {
marginTop: 5,
fontSize: 13,
},
gameFirstPlayed: {
marginTop: 2,
fontSize: 13,
},
gameTitleId: {
marginTop: 5,
fontSize: 13,
},
gameTitleIdValue: {
fontFamily: 'monospace',
userSelect: 'all',
},
gameShopButton: {
marginTop: 10,
flexDirection: 'row',
},
});
const light = StyleSheet.create({
text: {
color: TEXT_COLOUR_LIGHT,
},
});
const dark = StyleSheet.create({
text: {
color: TEXT_COLOUR_DARK,
},
});

View File

@ -1,8 +1,37 @@
import { AppRegistry } from 'react-native';
import { config } from './ipc.js';
import App from './app.jsx';
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');
style.textContent = `
:root {
user-select: none;
overflow-x: hidden;
}
*:focus-visible {
outline-style: solid;
outline-width: medium;
}
input,
input:focus-visible {
outline: none 0;
}
`;
window.document.head.appendChild(style);
const rootTag = window.document.createElement('div');

View File

@ -1,4 +1,4 @@
import type { EventEmitter } from 'events';
import { EventEmitter } from 'node:events';
import createDebug from 'debug';
import type { NxapiElectronIpc } from '../preload/index.js';
@ -10,7 +10,21 @@ declare global {
}
}
const ipc = window.nxapiElectronIpc;
export const events = new EventEmitter();
events.setMaxListeners(0);
const ipc = {
...window.nxapiElectronIpc,
events,
};
events.on('newListener', (event: string, listener: (...args: any[]) => void) => {
ipc.registerEventListener(event, listener);
});
events.on('removeListener', (event: string, listener: (...args: any[]) => void) => {
ipc.removeEventListener(event, listener);
});
export default ipc;

View File

@ -0,0 +1,113 @@
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, NintendoSwitchUser, NintendoSwitchUsers } from '../components/index.js';
export default function SetupDiscordPresence(props: {
user: User;
friends: Friend[] | null;
}) {
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();
const [users, ,, forceRefreshAccounts] = useAsync(useCallback(() => getAccounts(), [ipc]));
useEventListener(events, 'update-nintendo-accounts', forceRefreshAccounts, []);
const added_friends = useMemo(() => users?.filter(u => u.nso && props.friends?.find(f => {
if (f.nsaId !== u.nso?.nsoAccount.user.nsaId) return false;
return props.user.nso!.nsoAccount.user.permissions.presence === PresencePermissions.FRIENDS ||
(props.user.nso!.nsoAccount.user.permissions.presence === PresencePermissions.FAVORITE_FRIENDS &&
f.isFavoriteFriend);
})), [users, props.friends]);
const auth_user = source && 'na_id' in source ? users?.find(u => u.user.id === source.na_id)?.nso : null;
const friend = source && 'na_id' in source && source.na_id === props.user.user.id && source.friend_nsa_id ?
props.friends?.find(f => f.nsaId === source.friend_nsa_id) : null;
if (!props.friends || discord_presence_source_state !== RequestState.LOADED || !users) return null;
const content = !source && added_friends?.length ? <>
<Text style={[styles.text, theme.text]}>
<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={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]}>{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]}>{t('active_self')}</Text>
</> : source && 'na_id' in source && source.na_id === props.user.user.id && friend ? <>
<Text style={[styles.text, theme.text]}>
<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]}>{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]}>
<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={t('title')}>
<View style={styles.content}>
{content}
{source ? <View style={styles.button}>
<Button title={t('disable')}
onPress={() => ipc.setDiscordPresenceSource(null)} color={'#' + accent_colour} />
</View> : null}
</View>
</Section> : null;
}
const styles = StyleSheet.create({
content: {
marginTop: -4,
paddingBottom: 16,
paddingHorizontal: ipc.platform === 'win32' ? 24 : 20,
},
text: {
fontSize: 13,
opacity: 0.7,
},
button: {
marginTop: 10,
flexDirection: 'row',
},
});
const light = StyleSheet.create({
text: {
color: TEXT_COLOUR_LIGHT,
},
});
const dark = StyleSheet.create({
text: {
color: TEXT_COLOUR_DARK,
},
});

View File

@ -0,0 +1,224 @@
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, 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}
{status?.error_message ?
<DiscordPresenceError message={status?.error_message} onPress={showErrorDetails} /> : null}
</View>
</TouchableOpacity>;
}
function renderDiscordPresenceSource(source: DiscordPresenceSource | null) {
if (source && 'na_id' in source) {
return <DiscordPresenceSourceCoral source={source} />;
} else if (source && 'url' in source) {
return <DiscordPresenceSourceUrl source={source} />;
} else {
return <DiscordPresenceInactive />;
}
}
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 ?
ipc.getNsoFriends(token) : Promise.resolve(null), [ipc, token]));
const friend = friends?.find(f => f.nsaId === props.source.friend_nsa_id);
useEffect(() => {
if (friends_state !== RequestState.LOADED) return;
const timeout = setTimeout(forceRefreshFriends, 60 * 1000);
return () => clearTimeout(timeout);
}, [ipc, token, friends_state]);
useEventListener(events, 'window:refresh', forceRefreshFriends, []);
return <View style={styles.discordSource}>
{friend ? <Text style={styles.discordSourceText}>
<Trans i18nKey="main_window:sidebar.discord_active_friend">
<NintendoSwitchUser friend={friend} />
</Trans>
</Text> : <Text style={styles.discordSourceText}>
{t('discord_active')}
</Text>}
</View>;
}
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">
{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}>{t('discord_not_active')}</Text>
</View>;
}
function DiscordPresence(props: {
presence: DiscordPresence | null;
user: User | null;
}) {
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 : undefined;
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">{t('discord_playing')}</Text>
</View> : null}
{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 && 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({
discord: {
backgroundColor: DISCORD_COLOUR,
paddingVertical: 16,
paddingHorizontal: 20,
},
discordInactive: {
opacity: 0.7,
},
discordSource: {
},
discordSourceText: {
color: TEXT_COLOUR_DARK,
},
discordSourceUrlValue: {
fontFamily: 'monospace',
fontSize: 12,
userSelect: 'all',
},
discordPresenceContainer: {
marginTop: 2,
},
discordPresence: {
marginTop: 10,
flexDirection: 'row',
alignItems: 'center',
},
discordPresenceImage: {
marginRight: 10,
borderRadius: 2,
},
discordPresenceText: {
color: TEXT_COLOUR_DARK,
},
discordUser: {
marginTop: 10,
flexDirection: 'row',
alignItems: 'center',
},
discordUserImage: {
marginRight: 10,
borderRadius: 9,
},
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,
},
});

View File

@ -0,0 +1,93 @@
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';
import { TEXT_COLOUR_DARK, TEXT_COLOUR_LIGHT } from '../constants.js';
import Section from './section.js';
import { Button } from '../components/index.js';
export default function Event(props: {
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={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]}>
{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]}>
{t(voip_members ? 'app_join' : 'app_start')}
</Text>
{props.event.shareUri ? <View style={styles.shareButton}>
<Button title={t('share')} onPress={() => ipc.share({urls: [props.event.shareUri]})}
color={'#' + accent_colour} />
</View> : null}
</View>
</View>
</Section>;
}
const styles = StyleSheet.create({
content: {
paddingBottom: 16,
paddingHorizontal: ipc.platform === 'win32' ? 24 : 20,
flexDirection: 'row',
},
image: {
marginRight: 20,
borderRadius: 2,
},
detail: {
flex: 1,
},
eventName: {
fontSize: 16,
fontWeight: '500',
marginBottom: 5,
},
eventMembers: {
marginBottom: 5,
fontSize: 13,
},
eventInstruction: {
fontSize: 13,
opacity: 0.7,
},
shareButton: {
marginTop: 10,
flexDirection: 'row',
},
});
const light = StyleSheet.create({
text: {
color: TEXT_COLOUR_LIGHT,
},
});
const dark = StyleSheet.create({
text: {
color: TEXT_COLOUR_DARK,
},
});

View File

@ -0,0 +1,190 @@
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_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<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 title={t('add')!} /></Text>
</TouchableOpacity>;
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]}>{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]}>
<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_4;
user?: User<true>;
}) {
const theme = useColourScheme() === 'light' ? light : dark;
const onPress = useCallback(() => {
ipc.showFriendModal({
user: props.user!.user.id,
friend: props.friend.nsaId,
});
}, [ipc, props.user?.user.id, props.friend.nsaId]);
const onContextMenu = useCallback(() => {
ipc.showFriendMenu(props.user!.user, props.user!.nso!.nsoAccount.user, props.friend);
}, [ipc, props.user?.user, props.user?.nso?.nsoAccount.user, props.friend]);
const game = 'name' in props.friend.presence.game ? props.friend.presence.game : null;
const content = <View style={styles.friend}>
<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>
{props.friend.presence.updatedAt ? <FriendPresence presence={props.friend.presence} /> : null}
</View>;
const touchable = props.user ? <TouchableOpacity onPress={onPress}>
{content}
</TouchableOpacity> : content;
const contextmenu = Platform.OS === 'web' && props.user ? <View
// @ts-expect-error react-native-web
onContextMenu={onContextMenu}
>{touchable}</View> : touchable;
return <View style={styles.friendContainer}>
{contextmenu}
</View>;
}
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, 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]}>{t('presence_playing')}</Text>;
}
return <Text style={[styles.presenceText, styles.presenceTextOffline, theme.text]}>{logout ? since_logout : t('presence_offline')}</Text>;
}
const styles = StyleSheet.create({
iconTouchable: {
marginLeft: 10,
},
icon: {
fontSize: HEADER_SIZE,
},
footer: {
paddingBottom: 16,
paddingHorizontal: ipc.platform === 'win32' ? 24 : 20,
},
friendCode: {
fontSize: 12,
opacity: 0.7,
},
content: {
paddingBottom: 16,
paddingLeft: ipc.platform === 'win32' ? 24 : 20,
paddingRight: ipc.platform === 'win32' ? 4 : 0,
flexDirection: 'row',
},
noFriends: {
paddingVertical: 32,
marginBottom: 20,
},
noFriendsText: {
textAlign: 'center',
},
noFriendsFriendCodeText: {
marginTop: 10,
},
friendContainer: {
marginRight: 20,
},
friend: {
minWidth: 55,
maxWidth: 80,
alignItems: 'center',
},
friendImage: {
borderRadius: 25,
marginBottom: 12,
},
presenceImage: {
position: 'absolute',
marginTop: 32,
marginLeft: 32,
borderRadius: 2,
},
presenceText: {
marginTop: 5,
fontSize: 12,
textAlign: 'center',
},
presenceTextOnline: {
color: TEXT_COLOUR_ACTIVE,
},
presenceTextOffline: {
opacity: 0.7,
},
});
const light = StyleSheet.create({
text: {
color: TEXT_COLOUR_LIGHT,
},
});
const dark = StyleSheet.create({
text: {
color: TEXT_COLOUR_DARK,
},
});

View File

@ -0,0 +1,96 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { ScrollView, StyleSheet, Text, useColorScheme, View } from 'react-native';
import ipc, { events } from '../ipc.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;
insetTitleBarControls?: boolean;
}
export default function App(props: AppProps) {
const colour_scheme = useColorScheme();
const theme = colour_scheme === 'light' ? light : dark;
const [users, ,, forceRefreshAccounts] = useAsync(useCallback(() => getAccounts(), [ipc]));
useEventListener(events, 'update-nintendo-accounts', forceRefreshAccounts, []);
useEventListener(events, 'window:refresh', forceRefreshAccounts, []);
const [selectedUserId, setSelectedUserId] = useState<string | undefined>(undefined);
const selectedUser = useMemo(() => users?.find(u => u.user.id === selectedUserId), [users, selectedUserId]);
const [focused, setFocused] = useState(ipc.getWindowFocused());
useEventListener(events, 'window:focused', setFocused, []);
useEffect(() => {
if (!selectedUser) setSelectedUserId(users?.[0]?.user.id);
}, [users, selectedUser]);
return <Root
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.main, theme.main]}>
<ScrollView style={styles.scroller} contentContainerStyle={styles.scrollerContent}>
<StatusUpdates />
<Update />
{selectedUser ? <Main key={selectedUser.user.id} user={selectedUser}
autoRefresh={focused ? REFRESH_INTERVAL : undefined} /> : null}
</ScrollView>
</View>
</Root>;
}
const styles = StyleSheet.create({
app: {
flexDirection: 'row',
},
main: {
flex: 1,
},
scroller: {
flex: 1,
},
scrollerContent: {
flex: 1,
},
});
const light = StyleSheet.create({
appNoVibrancy: {
backgroundColor: BACKGROUND_COLOUR_SECONDARY_LIGHT,
},
main: {
backgroundColor: BACKGROUND_COLOUR_MAIN_LIGHT,
},
text: {
color: TEXT_COLOUR_LIGHT,
},
});
const dark = StyleSheet.create({
appNoVibrancy: {
backgroundColor: BACKGROUND_COLOUR_SECONDARY_DARK,
},
main: {
backgroundColor: BACKGROUND_COLOUR_MAIN_DARK,
},
text: {
color: TEXT_COLOUR_DARK,
},
});

View File

@ -0,0 +1,179 @@
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';
import WebServices from './webservices.js';
import Event from './event.js';
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';
export default function Main(props: {
user: User;
autoRefresh?: number;
}) {
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]));
const [friends, friends_error, friends_state, forceRefreshFriends] = useAsync(useCallback(() => props.user.nsotoken ?
ipc.getNsoFriends(props.user.nsotoken) : Promise.resolve(null), [ipc, props.user.nsotoken]));
const [webservices, webservices_error, webservices_state, forceRefreshWebServices] = useAsync(useCallback(() => props.user.nsotoken ?
ipc.getWebServices(props.user.nsotoken) : Promise.resolve(null), [ipc, props.user.nsotoken]));
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]);
useEffect(() => {
if (loading || !props.autoRefresh) return;
const timeout = setTimeout(refresh, props.autoRefresh);
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(() => {
ipc.showCoralErrors(props.user.nsotoken!, ['friends', 'webservices', 'activeevent']);
}, [friends_error, webservices_error, active_event_error]);
if (!friends || !webservices || !active_event) {
if (loading) {
return <View style={styles.loading}>
<ActivityIndicator size="large" color={'#' + accent_colour} />
</View>;
}
if (friends_error || webservices_error || active_event_error) {
const 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]}>{t('error.title')}</Text>
<Text style={[styles.errorMessage, theme.text]}>{t('error.message', {errors})}</Text>
<View style={styles.errorActions}>
<Button title={t('error.retry')} onPress={refresh} color={'#' + accent_colour} primary />
<TouchableOpacity onPress={showErrorDetails} style={styles.errorViewDetailsTouchable}>
<Text style={theme.text}>{t('error.view_details')}</Text>
</TouchableOpacity>
</View>
</View>;
}
}
return <View>
{!props.user.nso && props.user.moon ? <MoonOnlyUser /> : null}
{props.user.nso ? <SetupDiscordPresence user={props.user} friends={friends} /> : null}
{props.user.nso && friends ? <Friends user={props.user} friends={friends}
loading={friends_state === RequestState.LOADING} error={friends_error ?? undefined} /> : null}
{props.user.nso && webservices ? <WebServices user={props.user} webservices={webservices}
loading={webservices_state === RequestState.LOADING} error={webservices_error ?? undefined} /> : null}
{props.user.nso && active_event && 'id' in active_event ? <Event user={props.user} event={active_event}
loading={active_event_state === RequestState.LOADING} error={active_event_error ?? undefined} /> : null}
</View>;
}
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={t('title')}>
<View style={styles.moonOnlyUser}>
<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={t('login')} onPress={() => ipc.addCoralAccount()} color={'#' + accent_colour} primary />
</View>
</View>
</Section>;
}
const styles = StyleSheet.create({
loading: {
flex: 1,
paddingVertical: 16,
paddingHorizontal: 20,
justifyContent: 'center',
},
container: {
paddingVertical: 16,
paddingHorizontal: 20,
},
moonOnlyUser: {
paddingVertical: 32,
paddingHorizontal: 20,
marginBottom: 20,
},
moonOnlyUserText: {
marginBottom: 10,
textAlign: 'center',
},
moonOnlyUserButton: {
marginTop: 10,
flexDirection: 'row',
justifyContent: 'center',
},
error: {
flex: 1,
paddingVertical: 16,
paddingHorizontal: 20,
justifyContent: 'center',
},
errorHeader: {
marginBottom: 16,
fontSize: 16,
textAlign: 'center',
},
errorMessage: {
marginBottom: 16,
textAlign: 'center',
},
errorActions: {
alignItems: 'center',
},
errorViewDetailsTouchable: {
marginTop: 10,
},
});
const light = StyleSheet.create({
text: {
color: TEXT_COLOUR_LIGHT,
},
});
const dark = StyleSheet.create({
text: {
color: TEXT_COLOUR_DARK,
},
});

View File

@ -0,0 +1,83 @@
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';
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(() => {
props.errorKey ? ipc.showCoralErrors(...props.errorKey) : alert(props.error);
}, [props.error]);
return <View style={[styles.container, theme.container]}>
<View style={styles.header}>
<Text style={[styles.headerText, theme.text]}>{props.title}</Text>
{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 title={t('section_error')!} /></Text>
</TouchableOpacity> : null}
{props.headerButtons}
</View>
{props.children}
</View>;
}
export const HEADER_SIZE = ipc.platform === 'win32' ? 24 : 14;
const styles = StyleSheet.create({
container: {
marginBottom: ipc.platform === 'win32' ? 10 : 0,
borderBottomWidth: ipc.platform === 'win32' ? 0 : 1,
},
header: {
paddingVertical: ipc.platform === 'win32' ? 20 : 16,
paddingHorizontal: ipc.platform === 'win32' ? 24 : 20,
flexDirection: 'row',
},
headerText: {
flex: 1,
fontSize: HEADER_SIZE,
},
activityIndicator: {
marginLeft: 10,
},
iconTouchable: {
marginLeft: 10,
},
icon: {
fontSize: HEADER_SIZE,
},
});
const light = StyleSheet.create({
container: {
borderBottomColor: BORDER_COLOUR_LIGHT,
},
text: {
color: TEXT_COLOUR_LIGHT,
},
});
const dark = StyleSheet.create({
container: {
borderBottomColor: BORDER_COLOUR_SECONDARY_DARK,
},
text: {
color: TEXT_COLOUR_DARK,
},
});

View File

@ -0,0 +1,228 @@
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';
import { BORDER_COLOUR_DARK, BORDER_COLOUR_LIGHT, HIGHLIGHT_COLOUR_DARK, HIGHLIGHT_COLOUR_LIGHT, NSO_COLOUR, NSO_COLOUR_DARK, TEXT_COLOUR_DARK, TEXT_COLOUR_LIGHT } from '../constants.js';
export default function Sidebar(props: {
users?: User[] | null;
selectedUser?: string;
onSelectUser?: (na_id: string) => void;
insetTitleBarControls?: boolean;
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();
const discord_user = useActiveDiscordUser();
return <View style={[styles.sidebar, theme.sidebar]}>
<View style={[styles.top, theme.top, props.insetTitleBarControls ? styles.insetTitleBarControls : null]}>
<Text style={styles.topText}>nxapi</Text>
<Text style={styles.topText}>Nintendo Switch Online</Text>
</View>
<ScrollView style={styles.scroller}>
<View style={styles.main}>
{discord_presence_source_state === RequestState.LOADED ?
<DiscordPresenceSource source={discord_presence_source}
presence={presence} user={discord_user} /> : null}
{props.users?.length ? <View style={styles.users}>
{props.users.map(u => <User
key={u.user.id}
user={u}
selected={props.selectedUser === u.user.id}
onPress={() => props.onSelectUser?.call(null, u.user.id)}
/>)}
</View> : null}
{props.users ? <TouchableOpacity onPress={() => ipc.showAddUserMenu()} style={styles.addUser}>
<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}>{t('discord_setup')}</Text>
</TouchableOpacity> : null}
{props.children}
</View>
</ScrollView>
</View>;
}
function User(props: {
user: User;
selected?: boolean;
onPress?: () => void;
}) {
const theme = useColourScheme() === 'light' ? light : dark;
const onContextMenu = useCallback(() => {
ipc.showUserMenu(props.user.user, props.user.nso?.nsoAccount.user);
}, [ipc, props.user.user, props.user.nso?.nsoAccount.user]);
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' :
'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,
};
const touchable = <TouchableOpacity onPress={props.onPress}>
<View style={[styles.user, props.selected ? theme.userSelected : null]}>
<View style={styles.userMii}>
<Image source={miiImageSource} style={styles.userMiiImage} />
</View>
<View style={styles.userMain}>
<Text style={[styles.userName, theme.text]}>{props.user.user.nickname}</Text>
{props.user.nso ? <View style={styles.userNso}>
<View style={styles.userNsoImage}>
<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>
</View> : null}
</View>
</View>
</TouchableOpacity>;
return Platform.OS === 'web' ? <View
// @ts-expect-error react-native-web
onContextMenu={onContextMenu}
>{touchable}</View> : touchable;
}
const styles = StyleSheet.create({
sidebar: {
flex: 1,
maxWidth: 250,
borderRightWidth: ipc.platform === 'win32' ? 0 : 1,
},
top: {
backgroundColor: NSO_COLOUR,
paddingVertical: 28,
paddingHorizontal: 20,
},
insetTitleBarControls: {
paddingTop: 58,
},
topText: {
fontSize: 16,
fontWeight: '600',
color: TEXT_COLOUR_DARK,
},
scroller: {
flex: 1,
},
main: {
paddingBottom: 16,
},
users: {
marginTop: 16,
},
addUser: {
marginTop: 10,
paddingVertical: 6,
paddingHorizontal: 20,
},
addUserButton: {
marginTop: 5,
},
discordSetup: {
marginTop: 10,
paddingVertical: 6,
paddingHorizontal: 20,
},
user: {
flexDirection: 'row',
paddingVertical: 8,
paddingHorizontal: 20,
alignItems: 'center',
},
userMii: {
marginRight: 14,
},
userMiiImage: {
borderRadius: 16,
},
userMain: {
flex: 1,
},
userName: {
},
userNso: {
flexDirection: 'row',
flex: 1,
alignItems: 'center',
marginTop: 5,
},
userNsoImage: {
marginRight: 7,
},
userNsoName: {
opacity: 0.7,
fontSize: 12,
},
});
const light = StyleSheet.create({
sidebar: {
borderRightColor: BORDER_COLOUR_LIGHT,
},
top: {
},
userSelected: {
backgroundColor: HIGHLIGHT_COLOUR_LIGHT,
},
text: {
color: TEXT_COLOUR_LIGHT,
},
});
const dark = StyleSheet.create({
sidebar: {
borderRightColor: BORDER_COLOUR_DARK,
},
top: {
backgroundColor: NSO_COLOUR_DARK,
},
userSelected: {
backgroundColor: HIGHLIGHT_COLOUR_DARK,
},
text: {
color: TEXT_COLOUR_DARK,
},
});

Some files were not shown because too many files have changed in this diff Show More