Compare commits

..

No commits in common. "main" and "v0.3.0" have entirely different histories.
main ... v0.3.0

303 changed files with 11945 additions and 38672 deletions

View File

@ -1,55 +0,0 @@
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

View File

@ -1,15 +0,0 @@
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,18 +8,11 @@ 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.
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.
validations:
required: true
@ -40,7 +33,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` (Nintendo Switch) or `0400` (Nintendo Switch 2) and end with `0000`, `2000`, `4000`, `6000`, `8000`, `a000`, `c000` or `e000`.
Application title IDs are 16 hexadecimal digits, and should start with `0100` and end with `0000`, `2000`, `4000`, `6000`, `8000`, `a000`, `c000` or `e000`.
placeholder: |
0100d2f00d5c0000 Nintendo Switch Sports
01000ee017182000 Nintendo Switch Sports Online Play Test
@ -56,3 +49,13 @@ 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
View File

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

4
.gitignore vendored
View File

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

View File

@ -1,245 +1,97 @@
image: node:18
image: node:17
cache:
paths:
- node_modules/
paths:
- node_modules/
before_script:
- npm --color="always" install --force
- npm --color="always" install --force
build:
stage: build
script:
- npx tsc
# Uses CI_COMMIT_TAG, NXAPI_AUTH_CLI_CLIENT_ID, NXAPI_AUTH_APP_CLIENT_ID
- NODE_ENV=production npx rollup --config
stage: build
script:
- npx tsc
- npx rollup --config
- node bin/nxapi.js util validate-discord-titles
- PACKAGE=`npm --color="always" pack`
- mv "$PACKAGE" nxapi.tgz
- export VERSION=`[ "$CI_COMMIT_BRANCH" != "main" ] || node resources/build/ci-main-version.js`
- node resources/build/ci-package-json.js
- PACKAGE=`npm --color="always" pack`
- mv "$PACKAGE" nxapi.tgz
artifacts:
paths:
- dist
- nxapi.tgz
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
- 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/**/*
publish-npm:
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
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
publish-gitlab:
stage: deploy
script:
# Update the package.json and package-lock.json
- node resources/build/ci-package-json.js 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')\""
- 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
- 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
publish-github:
stage: deploy
script:
# Update the package.json and package-lock.json
- node resources/build/ci-package-json.js 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')\""
- 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
- 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

View File

@ -1,10 +1,17 @@
#!/bin/sh
mkdir -p .vscode/schema/generated
mkdir -p .vscode/schema/{moon,splatnet2,nooklink}
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/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/common/remote-config.ts --type NxapiRemoteConfig --no-type-check > .vscode/schema/generated/remote-config.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

29
.vscode/launch.json vendored
View File

@ -10,14 +10,11 @@
"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/electron/dist/electron.exe"
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd"
},
"args": [
"dist/app/app-entry.cjs"
"dist/app/main/app-entry.cjs"
],
"outputCapture": "std",
"env": {
@ -25,28 +22,6 @@
"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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,12 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"result": {
"$ref": "../generated/splatnet3-types.schema.json#/definitions/CoopHistoryDetail"
}
},
"required": [
"result"
]
}

View File

@ -1,12 +0,0 @@
{
"$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,21 +49,6 @@
"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:20 as build
FROM node:17 as build
WORKDIR /app
@ -13,7 +13,11 @@ ADD tsconfig.json /app
RUN npx tsc
FROM node:20
FROM node:17
RUN apt update && \
apt install -y android-tools-adb && \
apt-get clean
WORKDIR /app
@ -24,13 +28,14 @@ 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
View File

@ -1,661 +0,0 @@
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,82 +1,43 @@
nxapi
===
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)
Access the Nintendo Switch Online and Nintendo Switch Parental Controls app APIs. Includes Discord Rich Presence, friend notifications and data downloads.
### Features
- Command line and Electron app interfaces
- Command line and menu bar 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 [nxapi-znca-api.fancy.org.uk](https://github.com/samuelthomas2774/nxapi-znca-api) API by default.
- Alternatively a custom server can be used.
- 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.
- Get Nintendo Switch account information, friends list and game-specific services
- 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 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 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 and presence server
- Nintendo Switch Online app API proxy 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 personal SplatNet 2 and SplatNet 3 data, including battle and Salmon Run results
- 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 island newspapers from and send messages and reactions using NookLink
- Download all Nintendo Switch Parental Controls usage records
The API library and types are exported for use in JavaScript/TypeScript software. The app/commands properly cache access tokens and try to handle requests to appear as Nintendo's apps - if using nxapi as a library you will need to handle this yourself. [More information.](#usage-as-a-typescriptjavascript-library)
Discord presence | Additional data for Splatoon 3 | Friend notifications
------------------------------------|-----------------------------------|-----------------------------------
![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 ...
```
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.
#### Do I need a Nintendo Switch Online membership?
@ -84,20 +45,10 @@ 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 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 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.
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.
@ -106,38 +57,48 @@ 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/SplatNet 3 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 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.
A secondary account is required for Discord Rich Presence; you don't need to sign in to your main account.
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.
> [!CAUTION]
>
> **Update 08/09/2023**
>
> Nintendo has banned a small number of users from accessing SplatNet 3. Nintendo has not sent any notification to affected users. This is only known to have affected users of one application unrelated to nxapi.
>
> SplatNet 3 returns `401 Unauthorized` (`ERROR_INVALID_GAME_WEB_TOKEN`... which causes the official app to retry repeatedly); there is no specific error message for banned users. No other Nintendo services are affected.
>
> If you only use nxapi for Discord Rich Presence, your main account is safe, because nxapi does not use it to fetch presence data. nxapi requires a secondary account to fetch your main account's presence data, so even if that account was banned you could just create another one without losing anything.
>
> More information:
>
> - https://tkgstrator.work/article/2023/09/announcement.html
> - https://github.com/frozenpandaman/s3s/issues/146
#### Why is a token sent to one/two different non-Nintendo servers?
#### Why is data sent to non-Nintendo servers?
It's required to generate some data to make Nintendo think you're using the real Nintendo Switch Online app. (This isn't required for Parental Controls data.) See the splatnet2statink and flapg section below for more information.
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.
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.
#### I need help using nxapi or Nintendo's APIs/I want to share something I've made using nxapi or Nintendo's APIs
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'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.
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.)
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).
### Electron app
Invitation: https://discord.com/invite/4D82rFkXRv
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.
### Install
@ -154,47 +115,520 @@ 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
# Don't download an archive, as nxapi detects the current git revision
git clone https://gitlab.fancy.org.uk/samuel/nxapi.git
git clone https://gitlab.fancy.org.uk/samuel/nxapi.git # or download as an archive
cd nxapi
# Install CLI/Electron app locally
# Install 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 registry.fancy.org.uk/samuel/nxapi
docker build . --tag gitlab.fancy.org.uk:5005/samuel/nxapi
# # Run in Docker
# docker run -it --rm -v ./data:/data registry.fancy.org.uk/samuel/nxapi ...
# docker run -it --rm -v ./data:/data gitlab.fancy.org.uk:5005/samuel/nxapi ...
```
### Usage
### Nintendo Switch Online
Information on the nxapi command line interface can be found at [docs/cli.md](docs/cli.md).
#### Login to the Nintendo Switch Online app
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.
```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
```
#### Data location
@ -206,34 +640,14 @@ 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](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.
Logging uses the `debug` package and can be controlled using the `DEBUG` environment variable. All nxapi logging uses the `nxapi` and `cli` 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 ...
@ -241,166 +655,61 @@ DEBUG=nxapi:api:* nxapi ...
DEBUG=* nxapi ...
```
By default all nxapi logs will be written to a platform-specific location:
#### znca API server
Platform | Log path
----------------|----------------
macOS | `Library/Logs/nxapi-nodejs`
Windows | `%localappdata%\nxapi-nodejs\Log`
Linux | `$XDG_STATE_HOME/nxapi-nodejs` or `.local/state/nxapi-nodejs`
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.
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.
This requires:
nxapi logs may contain sensitive information such as Nintendo Account access tokens.
- 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
#### Environment variables
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
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.
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
### Links
- Nintendo Switch Online app API docs
- https://github.com/ZekeSnider/NintendoSwitchRESTAPI
- https://dev.to/mathewthe2/intro-to-nintendo-switch-rest-api-2cm7
- nxapi includes TypeScript definitions 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
- splatnet2statink and flapg docs
- https://github.com/frozenpandaman/splatnet2statink/wiki/api-docs
- Disabling TLS certificate validation (entirely) with Frida on Android
- https://httptoolkit.tech/blog/frida-certificate-pinning/
- Other Discord Rich Presence implementations (that use Coral)
- Other Discord Rich Presence implementations (that use znc)
- https://github.com/MCMi460/NSO-RPC
- https://github.com/Quark064/NSO-Discord-Integration
- https://github.com/AAGaming00/acnhrp - doesn't use Coral, instead attempts to send a message in Animal Crossing: New Horizons every 10 seconds to check if the user is playing that game online
- Other projects using Coral/web services
- (Due to frequent breaking changes to Nintendo's API many of these do not work. In particular anything not updated since [23/08/2022](https://github.com/samuelthomas2774/nxapi/discussions/10#discussioncomment-3464443) will not be able to authenticate to Nintendo's API.)
- https://github.com/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/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 znc.srv.nintendo.net](https://github.com/search?q=znc.srv.nintendo.net&type=code)
- ... 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)

2
bin/caxa Executable file
View File

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

View File

@ -1,3 +1,7 @@
#!/usr/bin/env node
import('../dist/cli-entry.js');
import createDebug from 'debug';
createDebug.log = console.warn.bind(console);
import('../dist/cli.js').then(cli => cli.main.call(null));

41
data-api/Dockerfile Normal file
View File

@ -0,0 +1,41 @@
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

@ -0,0 +1,13 @@
<!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>

View File

@ -1,74 +0,0 @@
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:

View File

@ -1,760 +0,0 @@
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.

View File

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

View File

@ -1,122 +0,0 @@
`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.

View File

@ -1,196 +0,0 @@
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)

View File

@ -1,86 +0,0 @@
`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).

View File

@ -1,171 +0,0 @@
`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).

View File

@ -1,190 +0,0 @@
`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);
```

View File

@ -1,123 +0,0 @@
`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)).

13670
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,34 +1,21 @@
{
"name": "nxapi",
"version": "1.6.1",
"description": "Nintendo Switch app APIs",
"license": "AGPL-3.0-or-later",
"author": "Ellie <ellie+nxapi@fancy.org.uk>",
"version": "0.3.0",
"description": "",
"author": "Samuel Elliott",
"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",
"resources/cli",
"resources/common",
"bin"
"bin",
"resources"
],
"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"
},
@ -36,129 +23,77 @@
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"@samuelthomas2774/saltpack": "^0.4.0",
"body-parser": "^1.20.2",
"body-parser": "^1.19.2",
"cli-table": "^0.3.11",
"debug": "^4.3.4",
"debug": "^4.3.3",
"discord-rpc": "^4.0.1",
"dotenv": "^16.4.5",
"dotenv-expand": "^11.0.6",
"dotenv": "^16.0.0",
"dotenv-expand": "^8.0.3",
"env-paths": "^3.0.0",
"express": "^4.19.2",
"murmurhash": "^2.0.1",
"express": "^4.17.3",
"frida": "^15.1.17",
"mkdirp": "^1.0.4",
"node-fetch": "^3.2.2",
"node-notifier": "^10.0.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"
"node-persist": "^3.1.0",
"read": "^1.0.7",
"supports-color": "^8.1.1",
"uuid": "^8.3.2",
"yargs": "^17.3.1"
},
"devDependencies": {
"@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"
"@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"
},
"build": {
"appId": "uk.org.fancy.nxapi.app",
"productName": "Nintendo Switch Online",
"copyright": "Copyright © 2023 Ellie",
"copyright": "Copyright © 2022 Samuel Elliott",
"npmRebuild": false,
"files": [
"dist/app/bundle",
"dist/bundle",
"!dist/app/package",
"!**/node_modules/**/*",
"resources/app",
"resources/common",
"!resources/common/remote-config.json",
"resources/cli"
"resources"
],
"asar": false,
"extraMetadata": {
"name": "nxapi-app",
"main": "dist/bundle/app-entry.cjs",
"dependencies": {},
"optionalDependencies": {},
"devDependencies": {}
"main": "dist/bundle/app-main-bundle.cjs"
},
"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

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 33 KiB

View File

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 37 KiB

View File

Before

Width:  |  Height:  |  Size: 2.4 MiB

After

Width:  |  Height:  |  Size: 2.4 MiB

View File

@ -0,0 +1,26 @@
#!/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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 655 B

View File

@ -1,8 +0,0 @@
#!/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

@ -1,8 +0,0 @@
#!/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

@ -1,12 +0,0 @@
#!/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

View File

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

View File

@ -1,69 +0,0 @@
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

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

View File

@ -1,28 +0,0 @@
{
"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.

Before

Width:  |  Height:  |  Size: 74 KiB

View File

@ -2,9 +2,4 @@
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

@ -1,181 +1,97 @@
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 path from 'path';
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/plugin-replace').RollupReplaceOptions}
*/
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'),
},
preventAssignment: true,
};
/**
* @type {import('rollup').RollupOptions['watch']}
*/
const watch = {
include: 'dist/**',
};
/**
* @type {import('rollup').RollupOptions}
*/
const main = {
input: ['dist/cli-entry.js', 'dist/app/app-init.js', 'dist/app/main/index.js'],
const cli = {
input: 'src/cli-entry.ts',
output: {
dir: 'dist/bundle',
file: 'dist/bundle/cli-bundle.js',
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',
inlineDynamicImports: true,
},
plugins: [
replace(replace_options),
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(),
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',
'frida',
],
watch,
};
/**
* @type {import('rollup').RollupOptions}
*/
const app_entry = {
input: 'dist/app/app-entry.cjs',
const app = {
input: 'src/app/main/app-entry.cts',
output: {
file: 'dist/bundle/app-entry.cjs',
format: 'iife',
file: 'dist/bundle/app-main-bundle.cjs',
format: 'cjs',
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,
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({
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: 'dist/app/preload/index.js',
input: 'src/app/preload/index.ts',
output: {
file: 'dist/app/bundle/preload.cjs',
format: 'cjs',
sourcemap: true,
},
plugins: [
replace(replace_options),
typescript({
noEmit: true,
declaration: false,
}),
commonjs({
// the ".ts" extension is required
extensions: ['.js', '.jsx', '.ts', '.tsx'],
esmExternals: true,
}),
nodeResolve({
@ -186,21 +102,25 @@ const app_preload = {
external: [
'electron',
],
watch,
};
/**
* @type {import('rollup').RollupOptions}
*/
const app_preload_webservice = {
input: 'dist/app/preload-webservice/index.js',
input: 'src/app/preload-webservice/index.ts',
output: {
file: 'dist/app/bundle/preload-webservice.cjs',
format: 'cjs',
},
plugins: [
replace(replace_options),
typescript({
noEmit: true,
declaration: false,
}),
commonjs({
// the ".ts" extension is required
extensions: ['.js', '.jsx', '.ts', '.tsx'],
esmExternals: true,
}),
nodeResolve({
@ -211,47 +131,34 @@ const app_preload_webservice = {
external: [
'electron',
],
watch,
};
/**
* @type {import('rollup').RollupOptions}
*/
const app_browser = {
input: 'dist/app/browser/index.js',
input: 'src/app/browser/index.ts',
output: {
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',
file: 'dist/app/bundle/browser.js',
format: 'iife',
},
plugins: [
html({
title: 'nxapi',
}),
replace(replace_options),
typescript({
noEmit: true,
declaration: false,
}),
commonjs({
// the ".ts" extension is required
extensions: ['.js', '.jsx', '.ts', '.tsx'],
esmExternals: true,
}),
nodePolyfill(),
alias({
entries: [
// 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'},
{find: 'react-native', replacement: path.resolve(__dirname, 'node_modules', 'react-native-web')},
],
}),
nodeResolve({
@ -259,15 +166,12 @@ const app_browser = {
preferBuiltins: false,
}),
],
watch,
};
const skip = process.env.BUNDLE_SKIP?.split(',') ?? [];
export default [
!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);
cli,
app,
app_preload,
app_preload_webservice,
app_browser,
];

View File

@ -1,666 +0,0 @@
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
//

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

View File

@ -1,56 +1,26 @@
import { fetch, Response } from 'undici';
import { generateAuthData, getNintendoAccountToken, getNintendoAccountUser, NintendoAccountSessionAuthorisation, NintendoAccountToken, NintendoAccountUser } from './na.js';
import { defineResponse, ErrorResponse, HasResponse } from './util.js';
import fetch from 'node-fetch';
import createDebug from 'debug';
import { getNintendoAccountToken, getNintendoAccountUser } from './na.js';
import { ErrorResponse } 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';
export const ZNMA_VERSION = '1.17.0';
const ZNMA_VERSION = '1.17.0';
const ZNMA_BUILD = '261';
const ZNMA_USER_AGENT = 'moon_ANDROID/' + ZNMA_VERSION + ' (com.nintendo.znma; build:' + ZNMA_BUILD +
'; ANDROID 26)';
export default class MoonApi {
onTokenExpired: ((data?: MoonError, res?: Response) => Promise<MoonAuthData | PartialMoonAuthData | void>) | null = null;
/** @internal */
_renewToken: Promise<void> | null = null;
protected _token_expired = false;
protected constructor(
constructor(
public token: string,
public naId: string,
readonly znma_version = ZNMA_VERSION,
readonly znma_build = ZNMA_BUILD,
readonly znma_useragent = ZNMA_USER_AGENT,
public naId: string
) {}
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();
async fetch<T = unknown>(url: string, method = 'GET', body?: string, headers?: object) {
const response = await fetch(MOON_URL + url, {
method,
method: method,
headers: Object.assign({
'Authorization': 'Bearer ' + this.token,
'Cache-Control': 'no-store',
@ -62,40 +32,23 @@ 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': this.znma_version,
'X-Moon-App-Internal-Version': this.znma_build,
'User-Agent': this.znma_useragent,
'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)',
}, headers),
body,
signal,
}).finally(cancel);
body: body,
});
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 MoonErrorResponse('[moon] ' + data.title, response, data);
throw new ErrorResponse('[moon] ' + data.title, response, data);
}
return defineResponse(data, response);
return data;
}
async getUser() {
@ -126,107 +79,34 @@ 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.setTokenWithSavedToken(data);
this.token = data.nintendoAccountToken.access_token!;
this.naId = data.user.id;
return data;
}
private setTokenWithSavedToken(data: MoonAuthData | PartialMoonAuthData) {
this.token = data.nintendoAccountToken.access_token!;
if ('user' in data) this.naId = data.user.id;
this._token_expired = false;
}
static async createWithSessionToken(token: string) {
const data = await this.loginWithSessionToken(token);
return {moon: this.createWithSavedToken(data), data};
}
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)';
static async loginWithSessionToken(token: string) {
// Nintendo Account token
const nintendoAccountToken = await getNintendoAccountToken(token, ZNMA_CLIENT_ID);
// Nintendo Account user data
const user = await getNintendoAccountUser<never>(nintendoAccountToken);
const user = await getNintendoAccountUser(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,140 +1,19 @@
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 fetch from 'node-fetch';
import createDebug from 'debug';
import { ErrorResponse } from './util.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',
'Accept': 'application/json',
'X-Platform': 'Android',
'X-ProductVersion': '2.0.0',
'User-Agent': 'NASDKAPI; Android',
},
body: new URLSearchParams({
@ -142,31 +21,22 @@ export async function getNintendoAccountSessionToken(code: string, verifier: str
session_token_code: code,
session_token_code_verifier: verifier,
}).toString(),
signal,
}).finally(cancel);
});
if (response.status !== 200) {
throw await NintendoAccountAuthErrorResponse.fromResponse(response, '[na] Non-200 status code');
}
const token = await response.json() as NintendoAccountSessionToken | NintendoAccountError;
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 NintendoAccountErrorResponse('[na] ' + token.detail, response, token);
throw new ErrorResponse('[na] + ' + token.detail, response, token);
}
debug('Got Nintendo Account session token', token);
return defineResponse(token, response);
return token;
}
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: {
@ -179,32 +49,22 @@ 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);
});
if (response.status !== 200) {
throw await NintendoAccountAuthErrorResponse.fromResponse(response, '[na] Non-200 status code');
}
const nintendoAccountToken = await response.json() as NintendoAccountToken | NintendoAccountError;
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 NintendoAccountErrorResponse('[na] ' + nintendoAccountToken.detail, response, nintendoAccountToken);
throw new ErrorResponse('[na] + ' + nintendoAccountToken.detail, response, nintendoAccountToken);
}
debug('Got Nintendo Account token', nintendoAccountToken);
return defineResponse(nintendoAccountToken, response);
return nintendoAccountToken;
}
export async function getNintendoAccountUser<S extends NintendoAccountScope>(token: NintendoAccountToken) {
export async function getNintendoAccountUser(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',
@ -213,22 +73,17 @@ export async function getNintendoAccountUser<S extends NintendoAccountScope>(tok
'Accept': 'application/json',
'Authorization': 'Bearer ' + token.access_token!,
},
signal,
}).finally(cancel);
});
if (response.status !== 200) {
throw await NintendoAccountErrorResponse.fromResponse(response, '[na] Non-200 status code');
}
const user = await response.json() as NintendoAccountUser<S> | NintendoAccountError;
const user = await response.json() as NintendoAccountUser | NintendoAccountError;
if ('errorCode' in user) {
throw new NintendoAccountErrorResponse('[na] ' + user.detail, response, user);
throw new ErrorResponse('[na] + ' + user.detail, response, user);
}
debug('Got Nintendo Account user info', user);
return defineResponse(user, response);
return user;
}
export interface NintendoAccountSessionToken {
@ -236,11 +91,11 @@ export interface NintendoAccountSessionToken {
code: string;
}
export interface NintendoAccountSessionTokenJwtPayload extends JwtPayload {
jti: number;
jti: string;
typ: 'session_token';
iss: 'https://accounts.nintendo.com';
/** Unknown - scopes the token is valid for? */
'st:scp': NintendoAccountJwtScope[];
'st:scp': number[];
/** Subject (Nintendo Account ID) */
sub: string;
exp: number;
@ -250,7 +105,7 @@ export interface NintendoAccountSessionTokenJwtPayload extends JwtPayload {
}
export interface NintendoAccountToken {
scope: NintendoAccountScope[];
scope: string[];
token_type: 'Bearer';
id_token: string;
access_token?: string;
@ -265,7 +120,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;
}
@ -277,7 +132,7 @@ export interface NintendoAccountAccessTokenJwtPayload extends JwtPayload {
sub: string;
iat: number;
'ac:grt': number; // ??
'ac:scp': NintendoAccountJwtScope[];
'ac:scp': number[]; // ??
exp: number;
/** Audience (client ID) */
aud: string;
@ -316,12 +171,10 @@ 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,
@ -346,128 +199,74 @@ export enum NintendoAccountJwtScope {
// 'pointWallet' = -1,
// 'userNotificationMessage:anyClients' = -1,
// 'userNotificationMessage:anyClients:write' = -1,
// 1, 31
// 'offline' = -1,
// 'user.links.nintendoNetwork.id' = -1,
}
export interface NintendoAccountUser<S extends NintendoAccountScope = never> {
id: string;
nickname: string;
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;
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;
export interface NintendoAccountUser {
emailOptedIn: boolean;
emailOptedInUpdatedAt: number;
eachEmailOptedIn: Record<NintendoAccountEmailType, NintendoAccountEmailOptedIn>;
language: string;
country: string;
timezone: {
name: string;
id: string;
utcOffsetSeconds: number;
utcOffset: string;
};
region: null;
nickname: string;
clientFriendsOptedIn: boolean;
clientFriendsOptedInUpdatedAt: number;
analyticsOptedIn: boolean;
mii: {
favoriteColor: string;
id: string;
updatedAt: number;
coreData: {
'4': string;
};
clientId: '1cfe3a55ed8924d9';
imageUriTemplate: string;
storeData: {
'3': string;
};
imageOrigin: string;
etag: string;
type: 'profile';
};
isChild: boolean;
eachEmailOptedIn: {
survey: {
updatedAt: number;
optedIn: boolean;
};
deals: {
updatedAt: number;
optedIn: boolean;
};
};
updatedAt: number;
candidateMiis: unknown[];
id: string;
createdAt: number;
emailVerified: boolean;
analyticsPermissions: {
internalAnalysis: {
updatedAt: number;
permitted: boolean;
};
targetMarketing: {
updatedAt: number;
permitted: boolean;
};
};
emailOptedInUpdatedAt: number;
birthday: string;
screenName: string;
gender: string;
analyticsOptedInUpdatedAt: number;
analyticsPermissions: Record<NintendoAccountAnalyticsType, NintendoAccountAnalyticsPermission>;
createdAt: number;
updatedAt: number;
}
enum NintendoAccountGender {
UNKNOWN = 'unknown',
FEMALE = 'female',
MALE = 'male',
}
enum NintendoAccountLinkType {
NINTENDO_NETWORK = 'nintendoNetwork',
APPLE = 'apple',
GOOGLE = 'google',
}
interface NintendoAccountLink {
id: string;
createdAt: number;
}
type NintendoAccountLinkScope = {
[NintendoAccountScope.USER_LINKS_NNID]: NintendoAccountLinkType.NINTENDO_NETWORK;
};
type NintendoAccountLinkTypes<S extends NintendoAccountScope = NintendoAccountScope.USER_LINKS> =
S extends keyof NintendoAccountLinkScope ? NintendoAccountLinkScope[S] : never;
interface NintendoAccountTimezone {
id: string;
name: string;
utcOffset: string;
utcOffsetSeconds: number;
}
enum NintendoAccountEmailType {
SURVEY = 'survey',
DEALS = 'deals',
}
interface NintendoAccountEmailOptedIn {
optedIn: boolean;
updatedAt: number;
}
enum NintendoAccountAnalyticsType {
INTERNAL_ANALYSIS = 'internalAnalysis',
TARGET_MARKETING = 'targetMarketing',
}
interface NintendoAccountAnalyticsPermission {
updatedAt: number;
permitted: boolean;
}
export interface Mii {
id: string;
clientId: '1cfe3a55ed8924d9';
type: 'profile';
favoriteColor: MiiColour;
coreData: {
'4': string;
};
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;
analyticsOptedIn: boolean;
clientFriendsOptedInUpdatedAt: number;
}
export interface NintendoAccountError {
@ -478,15 +277,3 @@ 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,95 +1,57 @@
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 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 { 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.1';
const BLANCO_VERSION = '2.1.0';
export default class NooklinkApi {
onTokenExpired: ((data?: WebServiceError, res?: Response) => Promise<NooklinkAuthData | void>) | null = null;
/** @internal */
_renewToken: Promise<void> | null = null;
protected _token_expired = false;
protected constructor(
constructor(
public gtoken: string,
public useragent: string,
readonly client_version = BLANCO_VERSION,
public useragent: string
) {}
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();
async fetch<T = unknown>(url: string, method = 'GET', body?: string | FormData, headers?: object) {
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': 'application/json, text/plain, */*',
'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',
'Origin': 'https://web.sd.lp1.acbaa.srv.nintendo.net',
'Content-Type': 'application/json',
'X-Blanco-Version': this.client_version,
'X-Blanco-Version': BLANCO_VERSION,
}, headers),
body,
signal,
}).finally(cancel);
body: body,
});
debug('fetch %s %s, response %s', method, url, response.status);
if (response.status === 401 && _autoRenewToken && !_attempt && this.onTokenExpired) {
this._token_expired = true;
const data = await response.json() as WebServiceError;
// _renewToken will be awaited when calling fetch
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');
if (response.status !== 200 && response.status !== 201) {
throw new ErrorResponse('[nooklink] Unknown error', response, await response.text());
}
const data = await response.json() as T | WebServiceError;
if ('code' in data) {
throw new NooklinkErrorResponse('[nooklink] Error ' + data.code, response, data);
throw new ErrorResponse('[nooklink] Error ' + data.code, response, data);
}
return defineResponse(data, response);
return data;
}
async getUsers() {
@ -103,50 +65,30 @@ export default class NooklinkApi {
}
async createUserClient(user_id: string) {
return NooklinkUserApi._createWithNooklinkApi(this, user_id);
const token = await this.getAuthToken(user_id);
return {
nooklinkuser: new NooklinkUserApi(user_id, token.token, this.gtoken, this.useragent),
token,
};
}
async renewTokenWithCoral(coral: CoralApiInterface, user: NintendoAccountUserCoral) {
const data = await NooklinkApi.loginWithCoral(coral, user);
this.setTokenWithSavedToken(data);
return data;
static async createWithZnc(nso: ZncApi, user: NintendoAccountUser) {
const data = await this.loginWithZnc(nso, user);
return {
nooklink: new this(data.gtoken, data.useragent),
data,
};
}
async renewTokenWithWebServiceToken(webserviceToken: WebServiceToken, user: NintendoAccountUserCoral) {
const data = await NooklinkApi.loginWithWebServiceToken(webserviceToken, 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);
}
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');
static async loginWithWebServiceToken(webserviceToken: WebServiceToken, user: NintendoAccountUser) {
const url = new URL(NOOKLINK_WEBSERVICE_URL);
url.search = new URLSearchParams({
lang: user.language,
@ -154,35 +96,31 @@ 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);
if (response.status !== 200) {
throw await NooklinkErrorResponse.fromResponse(response, '[nooklink] Non-200 status code');
}
const body = await response.text();
if (response.status !== 200) {
throw new ErrorResponse('[nooklink] Unknown error', response, body);
}
const cookies = response.headers.get('Set-Cookie');
const match = cookies?.match(/\b_gtoken=([^;]*)(;(\s*((?!expires)[a-z]+=([^;]*));?)*(\s*(expires=([^;]*));?)?|$)/i);
if (!match) {
throw new NooklinkErrorResponse('[nooklink] Response didn\'t include _gtoken cookie', response, body);
throw new ErrorResponse('[nooklink] Response didn\'t include _gtoken cookie', response, body);
}
const gtoken = decodeURIComponent(match[1]);
@ -202,90 +140,51 @@ export default class NooklinkApi {
gtoken,
expires_at,
useragent: NOOKLINK_WEBSERVICE_USERAGENT,
version: config.blanco_version,
};
}
}
export class NooklinkUserApi {
onTokenExpired: ((data?: WebServiceError, res?: Response) => Promise<NooklinkUserAuthData | PartialNooklinkUserAuthData | void>) | null = null;
/** @internal */
_renewToken: Promise<void> | null = null;
protected _token_expired = false;
protected constructor(
constructor(
public user_id: string,
public auth_token: string,
public gtoken: string,
public useragent: string,
public language = 'en-GB',
readonly client_version = BLANCO_VERSION,
public language = 'en-GB'
) {}
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();
async fetch<T = unknown>(url: string, method = 'GET', body?: string | FormData, headers?: object) {
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': 'application/json, text/plain,*/*',
'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',
'Origin': 'https://web.sd.lp1.acbaa.srv.nintendo.net',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.auth_token,
'X-Blanco-Version': this.client_version,
'X-Blanco-Version': BLANCO_VERSION,
}, headers),
body,
signal,
}).finally(cancel);
body: body,
});
debug('fetch %s %s, response %s', method, url, response.status);
if (response.status === 401 && _autoRenewToken && !_attempt && this.onTokenExpired) {
this._token_expired = true;
const data = await response.json() as WebServiceError;
// _renewToken will be awaited when calling fetch
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());
if (response.status !== 200 && response.status !== 201) {
throw new ErrorResponse('[nooklink] Unknown error', response, await response.text());
}
const data = await response.json() as T | WebServiceError;
if ('code' in data) {
throw new NooklinkErrorResponse('[nooklink] Error ' + data.code, response, data);
throw new ErrorResponse('[nooklink] Error ' + data.code, response, data);
}
return defineResponse(data, response);
return data;
}
async getUserProfile(id?: string) {
@ -313,7 +212,7 @@ export class NooklinkUserApi {
}
async postMessage(body: string, type: MessageType, destination_user_id?: string) {
return this.fetch('/sd/v1/messages', 'POST', JSON.stringify({
return this.fetch<unknown>('/sd/v1/messages', 'POST', JSON.stringify({
type,
body,
userId: destination_user_id,
@ -331,100 +230,6 @@ 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: Record<string | number, StageStats>;
stage_stats: unknown;
update_time: number;
recent_lose_count: number;
league_stats: {
@ -28,23 +28,6 @@ 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[];
@ -91,20 +74,18 @@ interface WeaponStats {
total_paint_point: number;
last_use_time: number;
lose_count: number;
weapon: WeaponSet;
weapon: Weapon;
win_count: number;
max_win_meter: number;
}
interface MainWeapon {
interface Weapon {
name: string;
id: string;
thumbnail: string;
image: string;
}
interface WeaponSet extends MainWeapon {
sub: SubWeapon;
special: SpecialWeapon;
image: string;
}
interface SubWeapon {
image_b: string;
@ -120,21 +101,21 @@ interface SpecialWeapon {
}
interface Player {
clothes: Gear & {kind: GearType.CLOTHES};
clothes: Gear & {kind: 'clothes'};
star_rank: number;
head_skills: Skills;
nickname: string;
shoes_skills: Skills;
weapon: WeaponSet;
weapon: Weapon;
player_rank: number;
max_league_point_team: number;
shoes: Gear & {kind: GearType.SHOES};
shoes: Gear & {kind: 'shoes'};
clothes_skills: Skills;
udemae_tower: Rank;
udemae_clam: Rank;
udemae_rainmaker: Rank;
player_type: PlayerType;
head: Gear & {kind: GearType.HEAD};
head: Gear & {kind: 'head'};
max_league_point_pair: number;
principal_id: string;
udemae_zones: Rank;
@ -146,14 +127,9 @@ interface Gear {
id: string;
rarity: number;
image: string;
kind: GearType;
kind: 'clothes' | 'shoes' | 'head';
thumbnail: string;
}
export enum GearType {
CLOTHES = 'clothes',
SHOES = 'shoes',
HEAD = 'head',
}
interface Brand {
image: string;
frequent_skill?: Skill;
@ -171,7 +147,7 @@ interface Skill {
}
interface Rank {
name: string | null;
name: null;
s_plus_number: null;
is_x: boolean;
number: number;
@ -215,10 +191,6 @@ export interface Timeline {
};
udemae: {
importance: number;
} | {
importance: number;
change: number;
stat: RankedMatchResults;
};
coop: {
importance: number;
@ -260,6 +232,38 @@ 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;
@ -296,19 +300,17 @@ interface ScheduleItem {
/** GET /records/hero */
export interface HeroRecords {
stage_infos: StageInfo[];
summary: HeroRecordsSummary;
summary: {
weapon_cleared_info: Record<string, boolean>;
honor: {
code: string;
name: string;
};
clear_rate: number;
};
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;
@ -336,27 +338,21 @@ export interface XPowerRankingSummary {
splat_zones: XPowerRankingRecords;
}
/** GET /x_power_ranking/{season}/{rule} */
export interface XPowerRankingRecords {
interface XPowerRankingRecords {
weapon_ranking: null;
season_id: string;
top_rankings_count: number;
top_rankings: XPowerRankingRecordsRanking[];
status: XPowerRankingStatus;
status: string;
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: WeaponSet;
weapon: Weapon;
rank: number;
unique_id: string;
x_power: number;
@ -371,35 +367,34 @@ export interface PastFestivals {
}
interface Festival {
colors: FestivalInkColours;
colors: {
middle: InkColour;
bravo: InkColour;
alpha: InkColour;
};
festival_id: number;
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;
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;
};
}
interface InkColour {
@ -455,20 +450,18 @@ interface FestivalResults1 {
/** GET /league_match_ranking/{league}/{region} */
export interface LeagueMatchRankings {
start_time: number;
league_type: LeagueType;
league_ranking_region: LeagueRankingRegion;
league_type: {
name: string;
key: string;
};
league_ranking_region: {
code: string;
id: number;
};
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;
@ -477,7 +470,7 @@ interface LeagueMatchRanking {
rank: number;
}
interface LeagueTagMember {
weapon: WeaponSet;
weapon: Weapon;
unique_id: string;
principal_id: string;
}
@ -486,18 +479,16 @@ interface LeagueTagMember {
export interface Results {
results: MatchResults[];
unique_id: string;
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;
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;
};
}
type MatchResults = RegularMatchResults | RankedMatchResults;
@ -534,10 +525,10 @@ interface RankedMatchResults extends BaseMatchResults {
is_x: boolean;
is_number_reached: boolean;
s_plus_number: null;
name: string | null;
name: null;
number: number;
};
estimate_gachi_power: number | null;
estimate_gachi_power: null;
x_power: null;
}
interface PlayerResult {
@ -552,7 +543,7 @@ interface PlayerResult {
interface RankedPlayerResult extends PlayerResult {
player: PlayerResult['player'] & {
udemae: {
name: string | null;
name: null;
s_plus_number: null;
is_x: boolean;
};
@ -561,7 +552,7 @@ interface RankedPlayerResult extends PlayerResult {
interface SelfRankedPlayerResult extends PlayerResult {
player: PlayerResult['player'] & {
udemae: {
name: string | null;
name: null;
s_plus_number: null;
number: number; // -1;
is_number_reached: boolean;
@ -678,18 +669,6 @@ 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;
@ -731,15 +710,6 @@ 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;
@ -751,15 +721,6 @@ 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;

View File

@ -1,243 +0,0 @@
//
// 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,16 +1,15 @@
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';
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';
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';
@ -24,45 +23,30 @@ export const updateIksmSessionLastUsed: {
} = {};
export default class SplatNet2Api {
protected _session_expired = false;
protected constructor(
constructor(
public iksm_session: string,
public unique_id: string,
public useragent: string,
public useragent: string
) {}
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();
async fetch<T = unknown>(url: string, method = 'GET', body?: string | FormData, headers?: object) {
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),
'Accept': '*/*',
'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',
'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,
'X-Requested-With': 'com.nintendo.znca',
}, headers),
body,
signal,
}).finally(cancel);
body: body,
});
debug('fetch %s %s, response %s', method, url, response.status);
if (response.status === 401) {
this._session_expired = true;
}
if (response.status !== 200) {
throw await SplatNet2ErrorResponse.fromResponse(response, '[splatnet2] Non-200 status code');
throw new ErrorResponse('[splatnet2] Unknown error', response, await response.text());
}
updateIksmSessionLastUsed.handler?.call(null, this.iksm_session);
@ -70,10 +54,10 @@ export default class SplatNet2Api {
const data = await response.json() as T | WebServiceError;
if ('code' in data) {
throw new SplatNet2ErrorResponse('[splatnet2] ' + data.message, response, data);
throw new ErrorResponse('[splatnet2] ' + data.message, response, data);
}
return defineResponse(data, response);
return data;
}
async getRecords() {
@ -105,11 +89,7 @@ export default class SplatNet2Api {
return this.fetch<HeroRecords>('/records/hero');
}
async getXPowerRankingSummary(season: string | Date | Season) {
if (typeof season === 'object' && 'start' in season) {
season = season.id;
}
async getXPowerRankingSummary(season: string | Date) {
if (season instanceof Date) {
season = toSeasonId(season.getUTCFullYear(), season.getUTCMonth() + 1);
}
@ -126,11 +106,7 @@ export default class SplatNet2Api {
return this.fetch<XPowerRankingSummary>('/x_power_ranking/' + season + '/summary');
}
async getXPowerRankingLeaderboard(season: string | Date | Season, rule: XPowerRankingRule, page: number = 1) {
if (typeof season === 'object' && 'start' in season) {
season = season.id;
}
async getXPowerRankingLeaderboard(season: string | Date, rule: XPowerRankingRule, page: number = 1) {
if (season instanceof Date) {
season = toSeasonId(season.getUTCFullYear(), season.getUTCMonth() + 1);
}
@ -144,27 +120,19 @@ export default class SplatNet2Api {
throw new Error('Invalid season ID');
}
return this.fetch<XPowerRankingRecords>('/x_power_ranking/' + season + '/' + rule + '?page=' + page);
return this.fetch<unknown>('/x_power_ranking/' + season + '/' + rule + '?page=' + page);
}
async getPastFestivals() {
return this.fetch<PastFestivals>('/festivals/pasts');
}
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);
}
async getLeagueMatchRanking(id: string, region: LeagueRegion) {
if (!id.match(LEAGUE_ID)) {
throw new Error('Invalid league ID');
}
return this.fetch<LeagueMatchRankings>('/league_match_ranking/' + id + '/' + region);
return this.fetch<PastFestivals>('/league_match_ranking/' + id + '/' + region);
}
async getResults() {
@ -192,7 +160,7 @@ export default class SplatNet2Api {
}
async shareProfile(stage: string, colour: ShareColour) {
const boundary = randomUUID();
const boundary = uuidgen();
const data = `--${boundary}
Content-Disposition: form-data; name="stage"
@ -239,44 +207,22 @@ ${colour}
});
}
static async createWithCoral(coral: CoralApiInterface, user: NintendoAccountUserCoral) {
const data = await this.loginWithCoral(coral, user);
return {splatnet: this.createWithSavedToken(data), data};
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 createWithSavedToken(data: SplatNet2AuthData) {
return new this(
data.iksm_session,
data.user_id,
data.useragent,
);
static async loginWithZnc(nso: ZncApi, user: NintendoAccountUser) {
const webserviceToken = await nso.getWebServiceToken(SPLATNET2_WEBSERVICE_ID);
return this.loginWithWebServiceToken(webserviceToken.result, user);
}
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> {
static async loginWithWebServiceToken(webserviceToken: WebServiceToken, user: NintendoAccountUser) {
const url = new URL(SPLATNET2_WEBSERVICE_URL);
url.search = new URLSearchParams({
lang: user.language,
@ -284,40 +230,41 @@ ${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();
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);
if (response.status !== 200) {
throw new ErrorResponse('[splatnet2] Unknown error', response, body);
}
const expires_at: number = (iksm_session.expires as Date)?.getTime() ?? Date.now() + 24 * 60 * 60 * 1000;
const cookies = response.headers.get('Set-Cookie');
const match = cookies?.match(/\biksm_session=([^;]*)(;(\s*((?!expires)[a-z]+=([^;]*));?)*(\s*(expires=([^;]*));?)?|$)/i);
debug('iksm_session %s, expires %s', iksm_session.value.replace(/^(.{6}).*/, '$1****'), iksm_session.expires);
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;
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);
@ -325,60 +272,45 @@ ${colour}
const mn = body.match(/<html(?:\s+[a-z0-9-]+(?:=(?:"[^"]*"|[^\s>]*))?)*\s+data-nsa-id=(?:"([^"]*)"|([^\s>]*))/i);
const [language, region, user_id, nsa_id] = [ml, mr, mu, mn].map(m => m?.[1] || m?.[2] || null);
if (!language) throw new 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****'),
});
debug('SplatNet 2 user', {language, region, user_id, nsa_id});
return {
webserviceToken,
url: url.toString(),
cookies,
cookies: cookies!,
body,
language,
region,
user_id,
nsa_id,
iksm_session: iksm_session.value,
iksm_session,
expires_at,
useragent: SPLATNET2_WEBSERVICE_USERAGENT,
};
}
}
export class SplatNet2ErrorResponse extends ErrorResponse<WebServiceError> {}
export function toSeasonId(year: number, month: number) {
const nextyear = month === 12 ? year + 1 : year;
const nextmonth = month === 12 ? 1 : month + 1;
export interface SplatNet2AuthData {
webserviceToken: WebServiceToken;
url: string;
cookies: string | Cookie[];
body: string;
if (year < 2000) throw new Error('Invalid season ID');
if (nextyear >= 2100) throw new Error('Invalid season ID');
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;
return ('' + (year - 2000)).padStart(2, '0') +
('' + month).padStart(2, '0') +
'01T00_' +
('' + (nextyear - 2000)).padStart(2, '0') +
('' + nextmonth).padStart(2, '0') +
'01T00';
}
export interface SplatNet2CliTokenData {
iksm_session: string;
language: string;
region: string;
user_id: string;
nsa_id: string;
export enum XPowerRankingRule {
SPLAT_ZONES = 'splat_zones',
TOWER_CONTROL = 'tower_control',
RAINMAKER = 'rainmaker',
CLAM_BLITZ = 'clam_blitz',
}
export function toLeagueId(date: Date, type: LeagueType) {

View File

@ -1,6 +0,0 @@
/** /bullet_tokens */
export interface BulletToken {
bulletToken: string;
lang: string;
is_noe_country: 'true' | 'false';
}

File diff suppressed because it is too large Load Diff

View File

@ -1,18 +1,4 @@
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>;
}
import { Response as NodeFetchResponse } from 'node-fetch';
export class ErrorResponse<T = unknown> extends Error {
readonly body: string | undefined;
@ -20,26 +6,11 @@ export class ErrorResponse<T = unknown> extends Error {
constructor(
message: string,
readonly response: Response | UndiciResponse,
body?: string | ArrayBuffer | T
readonly response: Response | NodeFetchResponse,
body?: string | 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 {
@ -48,32 +19,15 @@ 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 && ErrorResponseSymbol in instance;
return instance instanceof Error &&
'response' in instance &&
'body' in instance &&
'data' in instance;
},
});

View File

@ -1,349 +1,166 @@
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';
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';
const debug = createDebug('nxapi:api:znc-proxy');
export default class ZncProxyApi extends AbstractCoralApi implements CoralApiInterface {
export default class ZncProxyApi implements ZncApi {
static useragent: string | null = null;
constructor(
private url: URL | string,
private url: string,
// ZncApi uses the NSO token (valid for a few hours)
// ZncProxyApi uses the Nintendo Account session token (valid for two years)
public token: string,
public useragent = getAdditionalUserAgents()
) {
super();
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;
}
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 call<T = unknown>(url: string, parameter = {}): Promise<ZncSuccessResponse<T>> {
throw new Error('Not supported in ZncProxyApi');
}
async getAnnouncements() {
const result = await this.fetchProxyApi<{announcements: Announcements_4}>('announcements');
return createResult(result, result.announcements);
const response = await this.fetch<{announcements: Announcements}>('/announcements');
return {status: ZncStatus.OK as const, result: response.announcements, correlationId: ''};
}
async getFriendList() {
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),
}));
const response = await this.fetch<{friends: Friend[]}>('/friends');
return {status: ZncStatus.OK as const, result: response, correlationId: ''};
}
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({
async addFavouriteFriend(nsaid: string) {
await this.fetch('/friend/' + nsaid, 'POST', JSON.stringify({
isFavoriteFriend: true,
}));
return createResult(result, {});
return {status: ZncStatus.OK as const, result: {}, correlationId: ''};
}
async removeFavouriteFriend(nsa_id: string) {
const result = await this.fetchProxyApi('friend/' + nsa_id, 'PATCH', JSON.stringify({
async removeFavouriteFriend(nsaid: string) {
await this.fetch('/friend/' + nsaid, 'POST', JSON.stringify({
isFavoriteFriend: false,
}));
return createResult(result, {});
}
async deleteFriendIsNew(nsa_id: string) {
const result = await this.fetchProxyApi('friend/' + nsa_id, 'PATCH', JSON.stringify({
isNew: false,
}));
return createResult(result, {});
return {status: ZncStatus.OK as const, result: {}, correlationId: ''};
}
async getWebServices() {
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);
const response = await this.fetch<{webservices: WebService[]}>('/webservices');
return {status: ZncStatus.OK as const, result: response.webservices, correlationId: ''};
}
async getActiveEvent() {
const result = await this.fetchProxyApi<{activeevent: ActiveEvent | null}>('activeevent');
return createResult<GetActiveEventResult, typeof result>(result, result.activeevent ?? {});
const response = await this.fetch<{activeevent: ActiveEvent}>('/activeevent');
return {status: ZncStatus.OK as const, result: response.activeevent, correlationId: ''};
}
async getEvent(id: number) {
const result = await this.fetchProxyApi<{event: Event}>('event/' + id);
return createResult(result, result.event);
const response = await this.fetch<{event: Event}>('/event/' + id);
return {status: ZncStatus.OK as const, result: response.event, correlationId: ''};
}
async getUser(id: number) {
const result = await this.fetchProxyApi<{user: User}>('user/' + id);
return createResult(result, result.user);
const response = await this.fetch<{user: User}>('/user/' + id);
return {status: ZncStatus.OK as const, result: response.user, correlationId: ''};
}
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 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);
const response = await this.fetch<{user: CurrentUser}>('/user');
return {status: ZncStatus.OK as const, result: response.user, correlationId: ''};
}
async getCurrentUserPermissions() {
const user = await this.getCurrentUser();
return createResult(user, {
etag: user.etag,
permissions: user.permissions,
});
return {
status: ZncStatus.OK as const,
result: {
etag: user.result.etag,
permissions: user.result.permissions,
},
correlationId: '',
};
}
// 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> {
async updateCurrentUserPermissions(
to: PresencePermissions, from: PresencePermissions, etag: string
): Promise<ZncSuccessResponse<{}>> {
throw new Error('Not supported in ZncProxyApi');
}
getTokenWithNintendoAccountToken(
token: NintendoAccountToken, user: NintendoAccountUser,
): Promise<PartialCoralAuthData> {
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']> {
throw new Error('Not supported in ZncProxyApi');
}
async renewToken() {
const data = await this.fetchProxyApi<SavedToken>('auth');
data.proxy_url = this.url.toString();
const data = await this.fetch<SavedToken>('/auth');
data.proxy_url = this.url;
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.fetchProxyApi<SavedToken>('auth');
const data = await nso.fetch<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 =
PresenceOnline | PresenceOnline_4 | PresenceOffline |
{presence: PresenceOnline | PresenceOnline_4 | PresenceOffline} |
Presence | {presence: Presence} |
CurrentUser | {user: CurrentUser} |
Friend | {friend: Friend};
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);
export async function getPresenceFromUrl(presence_url: string) {
const response = await fetch(presence_url);
debug('fetch %s %s, response %s', 'GET', presence_url, response.status);
if (response.status !== 200) {
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);
throw new ErrorResponse('[zncproxy] Unknown error', response, await response.text());
}
const data = await response.json() as PresenceUrlResponse;
const user: CurrentUser<true> | CurrentUser<false> | Friend | Friend_4 | undefined =
const user: CurrentUser | Friend | undefined =
'user' in data ? data.user :
'friend' in data ? data.friend :
'nsaId' in data ? data :
undefined;
const presence: PresenceOnline | PresenceOnline_4 | PresenceOffline =
const presence: Presence =
'presence' in data ? data.presence :
'user' in data ? data.user.presence :
'friend' in data ? data.friend.presence :
@ -353,5 +170,5 @@ export async function getPresenceFromUrl(presence_url: string, useragent?: strin
throw new Error('Invalid presence data');
}
return defineResponse([presence, user, data as unknown] as const, response);
return [presence, user] as const;
}

206
src/api/znc-types.ts Normal file
View File

@ -0,0 +1,206 @@
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;
}

283
src/api/znc.ts Normal file
View File

@ -0,0 +1,283 @@
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` (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/app-main-bundle.cjs` (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 [app-entry.cts](app-entry.cts) (a CommonJS module) is used to import the actual app entrypoint after the `ready` event.
[electron.ts](electron.ts) exports all Electron APIs used in the main process. This is because the `electron` module doesn't actually exist - Electron patches the `require` function, but not the module importer. Additionally Electron does not support using a standard JavaScript module as the app entrypoint, so [main/app-entry.cts](main/app-entry.cts) 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.

View File

@ -1,16 +0,0 @@
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);
});

View File

@ -1,5 +0,0 @@
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

@ -1,151 +0,0 @@
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

@ -1,368 +0,0 @@
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,
},
});

70
src/app/browser/app.tsx Normal file
View File

@ -0,0 +1,70 @@
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

@ -1,190 +0,0 @@
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

@ -1,32 +0,0 @@
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

@ -1,14 +0,0 @@
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

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

View File

@ -1,14 +0,0 @@
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

@ -1,4 +0,0 @@
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

@ -1,40 +0,0 @@
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

@ -1,26 +0,0 @@
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

@ -1,288 +0,0 @@
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

@ -1,375 +0,0 @@
/// <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,37 +1,8 @@
import { AppRegistry } from 'react-native';
import { config } from './ipc.js';
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';
import App from './app.jsx';
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 { EventEmitter } from 'node:events';
import type { EventEmitter } from 'events';
import createDebug from 'debug';
import type { NxapiElectronIpc } from '../preload/index.js';
@ -10,21 +10,7 @@ declare global {
}
}
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);
});
const ipc = window.nxapiElectronIpc;
export default ipc;

View File

@ -1,113 +0,0 @@
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

@ -1,224 +0,0 @@
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

@ -1,93 +0,0 @@
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

@ -1,190 +0,0 @@
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

@ -1,96 +0,0 @@
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

@ -1,179 +0,0 @@
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

@ -1,83 +0,0 @@
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

@ -1,228 +0,0 @@
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