Compare commits

..

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

286 changed files with 11258 additions and 32474 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

2
.gitignore vendored
View File

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

View File

@ -1,245 +1,130 @@
image: node:18
cache:
paths:
- node_modules/
paths:
- node_modules/
before_script:
- npm --color="always" install --force
- npm --color="always" install --force
build:
stage: build
script:
- npx tsc
# Uses CI_COMMIT_TAG, NXAPI_AUTH_CLI_CLIENT_ID, NXAPI_AUTH_APP_CLIENT_ID
- NODE_ENV=production npx rollup --config
stage: build
script:
- npx tsc
# Uses CI_COMMIT_TAG
- NODE_ENV=production npx rollup --config
- node bin/nxapi.js util validate-discord-titles
- node bin/nxapi.js util validate-discord-titles
- 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
- "node -e \"fs.writeFileSync('package.json', JSON.stringify((json => {json.__nxapi_release = process.env.CI_COMMIT_TAG; return json;})(JSON.parse(fs.readFileSync('package.json', 'utf-8'))), null, 4) + '\\n', 'utf-8')\""
- PACKAGE=`npm --color="always" pack`
- mv "$PACKAGE" nxapi.tgz
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
- npx electron-builder build --macos zip --linux --publish never
- mv dist/app/package app
artifacts:
paths:
- dist
- nxapi.tgz
- app
exclude:
- app/mac/**/*
- app/win-unpacked/**/*
- app/linux-unpacked/**/*
build-windows:
stage: build
image: electronuserland/builder:wine
script:
- node resources/build/ci-package-json.js
stage: build
image: electronuserland/builder:wine
script:
- npx tsc
# Uses CI_COMMIT_TAG
- NODE_ENV=production npx rollup --config
- 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
- node bin/nxapi.js util validate-discord-titles
- "node -e \"fs.writeFileSync('package.json', JSON.stringify((json => {json.__nxapi_release = process.env.CI_COMMIT_TAG; return json;})(JSON.parse(fs.readFileSync('package.json', 'utf-8'))), null, 4) + '\\n', 'utf-8')\""
- npx electron-builder build --win nsis --publish never
- mv dist/app/package app
artifacts:
paths:
- app
exclude:
- app/mac/**/*
- app/win-unpacked/**/*
- app/linux-unpacked/**/*
only:
variables:
- $BUILD_WINDOWS_APP == "true"
cache:
paths:
- node_modules/
policy: pull
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 == "true"
- $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,19 @@
#!/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
npx ts-json-schema-generator --path src/common/remote-config.ts --type NxapiRemoteConfig --no-type-check > .vscode/schema/remote-config.schema.json

24
.vscode/launch.json vendored
View File

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

11
.vscode/settings.json vendored
View File

@ -50,18 +50,9 @@
"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"
"url": "./.vscode/schema/remote-config.schema.json"
},
],
"typescript.tsdk": "node_modules/typescript/lib",

View File

@ -1,4 +1,4 @@
FROM node:20 as build
FROM node:18 as build
WORKDIR /app
@ -13,7 +13,11 @@ ADD tsconfig.json /app
RUN npx tsc
FROM node:20
FROM node:18
RUN apt update && \
apt install -y android-tools-adb && \
apt-get clean
WORKDIR /app
@ -21,16 +25,18 @@ ADD package.json /app
ADD package-lock.json /app
RUN npm ci --production
RUN npm install --no-save frida
COPY bin /app/bin
COPY resources /app/resources
COPY resources/cli/fonts /usr/local/share/fonts
COPY --from=build /app/dist /app/dist
RUN ln -s /app/bin/nxapi.js /usr/local/bin/nxapi
ENV NXAPI_DATA_PATH=/data
ENV NODE_ENV=production
RUN ln -s /data/android /root/.android
VOLUME [ "/data" ]
ENTRYPOINT [ "/app/resources/docker-entrypoint.sh" ]

661
LICENSE
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/>.

870
README.md

File diff suppressed because it is too large Load Diff

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,11 +1,7 @@
version: '3'
services:
#
# Coral/znc proxy
#
znc-proxy:
web:
build: .
command: nso http-server --listen \[::]:80
restart: unless-stopped
@ -16,59 +12,40 @@ services:
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
DEBUG: '*,-express:*'
ZNCA_API_URL: http://znca-api/api/znca
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
znca-api:
image: ${COMPOSE_PROJECT_NAME:-nxapi}_web
command:
- android-znca-api-server-frida
- $ZNCA_API_ANDROID_DEVICE
- --exec-command
- ${ZNCA_API_EXEC_COMMAND:-}
- --frida-server-path
- ${ZNCA_API_FRIDA_SERVER_PATH:-/data/local/tmp/frida-server}
- --listen
- '[::]:80'
restart: unless-stopped
profiles:
- presence-server
depends_on:
- web
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
traefik.http.routers.nxapi-znca.entrypoints: websecure
traefik.http.routers.nxapi-znca.rule: Host(`${TRAEFIK_HOST:-nxapi.ta.fancy.org.uk}`) && PathPrefix(`/api/znca/`)
traefik.http.routers.nxapi-znca.tls: true
traefik.http.services.nxapi-znca.loadbalancer.server.port: 80
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
DEBUG: '*,-express:*,-body-parser:*'
volumes:
- data:/data
healthcheck:
test: [ "ENTRYPOINT", "curl", "http://[::1]:80" ]
timeout: 45s
interval: 10s
retries: 10
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)).

12797
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,17 +1,14 @@
{
"name": "nxapi",
"version": "1.6.1",
"version": "1.3.0",
"description": "Nintendo Switch app APIs",
"license": "AGPL-3.0-or-later",
"author": "Ellie <ellie+nxapi@fancy.org.uk>",
"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",
@ -22,12 +19,10 @@
],
"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"
"./nooklink": "./dist/exports/nooklink.js"
},
"bin": {
"nxapi": "bin/nxapi.js"
@ -36,65 +31,64 @@
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"@samuelthomas2774/saltpack": "^0.4.0",
"body-parser": "^1.20.2",
"body-parser": "^1.20.0",
"cli-table": "^0.3.11",
"debug": "^4.3.4",
"discord-rpc": "^4.0.1",
"dotenv": "^16.4.5",
"dotenv-expand": "^11.0.6",
"dotenv": "^16.0.1",
"dotenv-expand": "^8.0.3",
"env-paths": "^3.0.0",
"express": "^4.19.2",
"murmurhash": "^2.0.1",
"express": "^4.18.1",
"mkdirp": "^1.0.4",
"node-fetch": "^3.2.9",
"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",
"tslib": "^2.4.0",
"uuid": "^8.3.2",
"yargs": "^17.5.1"
},
"optionalDependencies": {
"frida": "^15.2.2"
},
"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": "^22.0.1",
"@rollup/plugin-html": "^0.2.4",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^13.3.0",
"@rollup/plugin-replace": "^4.0.0",
"@rollup/plugin-typescript": "^8.3.3",
"@types/body-parser": "^1.19.2",
"@types/cli-table": "^0.3.0",
"@types/debug": "^4.1.7",
"@types/discord-rpc": "^4.0.3",
"@types/express": "^4.17.13",
"@types/mkdirp": "^1.0.2",
"@types/node": "^18.6.1",
"@types/node-notifier": "^8.0.2",
"@types/node-persist": "^3.1.2",
"@types/react": "^17.0.45",
"@types/react-native": "^0.67.7",
"@types/read": "^0.0.29",
"@types/uuid": "^8.3.4",
"@types/yargs": "^17.0.10",
"electron": "^19.0.9",
"electron-builder": "^23.1.0",
"frida": "^15.2.2",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-native-web": "^0.17.7",
"rollup": "^2.77.2",
"rollup-plugin-polyfill-node": "^0.10.2",
"ts-json-schema-generator": "^1.0.0",
"typescript": "^4.7.4"
},
"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",
@ -102,9 +96,7 @@
"!dist/app/package",
"!**/node_modules/**/*",
"resources/app",
"resources/common",
"!resources/common/remote-config.json",
"resources/cli"
"resources/common"
],
"asar": false,
"extraMetadata": {
@ -123,42 +115,10 @@
"schemes": [
"com.nintendo.znca"
]
},
{
"name": "Nintendo Account authentication for Nintendo Switch Online",
"schemes": [
"npf71b963c1b7b6d119"
]
},
{
"name": "Nintendo Account authentication for Nintendo Switch Parental Controls",
"schemes": [
"npf54789befb391a838"
]
}
],
"publish": [],
"mac": {
"extraFiles": [
{
"from": "resources/build/app/cli-macos.sh",
"to": "bin/nxapi"
}
],
"identity": null
},
"linux": {
"category": "Utility",
"extraFiles": [
{
"from": "resources/build/app/cli-linux.sh",
"to": "nxapi"
}
]
},
"deb": {
"afterInstall": "resources/build/app/deb/postinst",
"afterRemove": "resources/build/app/deb/postrm"
}
}
}

View File

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

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

@ -2,8 +2,8 @@ import * as path from 'path';
import { fileURLToPath } from 'url';
import * as fs from 'fs';
import * as child_process from 'child_process';
import { Module } from 'module';
import typescript from '@rollup/plugin-typescript';
import commonjs from '@rollup/plugin-commonjs';
import alias from '@rollup/plugin-alias';
import replace from '@rollup/plugin-replace';
@ -18,14 +18,6 @@ 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) {
@ -42,7 +34,7 @@ const git = (() => {
branch: branch && branch !== 'HEAD' ? branch : null,
changed_files: changed_files.length ? changed_files.split('\n') : [],
};
})();
})();;
// If CI_COMMIT_TAG is set this is a tagged version for release
const release = process.env.NODE_ENV === 'production' ? process.env.CI_COMMIT_TAG || null : null;
@ -51,14 +43,12 @@ const release = process.env.NODE_ENV === 'production' ? process.env.CI_COMMIT_TA
* @type {import('@rollup/plugin-replace').RollupReplaceOptions}
*/
const replace_options = {
include: ['dist/util/product.js'],
include: ['src/util/product.ts'],
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,
@ -68,21 +58,20 @@ const replace_options = {
* @type {import('rollup').RollupOptions['watch']}
*/
const watch = {
include: 'dist/**',
include: 'src/**',
};
/**
* @type {import('rollup').RollupOptions}
*/
const main = {
input: ['dist/cli-entry.js', 'dist/app/app-init.js', 'dist/app/main/index.js'],
input: ['src/cli-entry.ts', 'src/app/main/index.ts'],
output: {
dir: 'dist/bundle',
format: 'es',
sourcemap: true,
entryFileNames: chunk => {
if (chunk.name === 'cli-entry') return 'cli-bundle.js';
if (chunk.name === 'app-init') return 'app-init-bundle.js';
if (chunk.name === 'index') return 'app-main-bundle.js';
return 'entry-' + chunk.name + '.js';
},
@ -90,18 +79,19 @@ const main = {
},
plugins: [
replace(replace_options),
typescript({
outDir: 'dist/bundle/ts',
noEmit: true,
declaration: false,
}),
commonjs({
// the ".ts" extension is required
extensions: ['.js', '.jsx', '.ts', '.tsx'],
esmExternals: true,
// events and stream modify module.exports
requireReturnsDefault: 'preferred',
}),
json(),
alias({
entries: [
{find: 'string_decoder/', replacement: 'node:string_decoder'},
...Module.builtinModules.map(m => ({find: m, replacement: 'node:' + m})),
],
}),
nodeResolve({
exportConditions: ['node'],
browser: false,
@ -109,10 +99,8 @@ const main = {
}),
],
external: [
'electron',
'node-notifier',
'register-scheme',
'bindings',
'frida',
],
watch,
};
@ -121,27 +109,29 @@ const main = {
* @type {import('rollup').RollupOptions}
*/
const app_entry = {
input: 'dist/app/app-entry.cjs',
input: 'src/app/main/app-entry.cts',
output: {
file: 'dist/bundle/app-entry.cjs',
format: 'iife',
inlineDynamicImports: true,
sourcemap: true,
globals: {
'electron': 'require("electron")',
},
},
plugins: [
replace(replace_options),
replace({
include: ['dist/app/app-entry.cjs'],
include: ['src/app/main/app-entry.cts'],
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',
@ -155,10 +145,7 @@ const app_entry = {
],
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'),
path.resolve(__dirname, 'src/app/main/app-main-bundle.js'),
],
watch,
};
@ -167,7 +154,7 @@ const app_entry = {
* @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',
@ -175,7 +162,13 @@ const app_preload = {
},
plugins: [
replace(replace_options),
typescript({
noEmit: true,
declaration: false,
}),
commonjs({
// the ".ts" extension is required
extensions: ['.js', '.jsx', '.ts', '.tsx'],
esmExternals: true,
}),
nodeResolve({
@ -193,14 +186,20 @@ const app_preload = {
* @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({
@ -218,40 +217,30 @@ const app_preload_webservice = {
* @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',
file: 'dist/app/bundle/browser.js',
format: 'iife',
sourcemap: true,
manualChunks(id) {
if (id.includes('node_modules')) {
return 'vendor';
}
if (id.startsWith('\0')) {
return 'internal';
}
},
chunkFileNames: 'chunk-[name].js',
},
plugins: [
html({
title: 'nxapi',
}),
replace(replace_options),
typescript({
noEmit: true,
declaration: false,
}),
commonjs({
// the ".ts" extension is required
extensions: ['.js', '.jsx', '.ts', '.tsx'],
esmExternals: true,
}),
nodePolyfill(),
alias({
entries: [
// 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({
@ -262,12 +251,10 @@ const app_browser = {
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);
main,
app_entry,
app_preload,
app_preload_webservice,
app_browser,
];

View File

@ -5,7 +5,7 @@ export interface CoralSuccessResponse<T = unknown> {
correlationId: string;
}
export interface CoralError {
export interface CoralErrorResponse {
status: CoralStatus | number;
errorMessage: string;
correlationId: string;
@ -53,21 +53,21 @@ export enum CoralStatus {
// UNKNOWN = -1,
}
export type CoralResponse<T = unknown> = CoralSuccessResponse<T> | CoralError;
export type CoralResponse<T = unknown> = CoralSuccessResponse<T> | CoralErrorResponse;
export interface AccountLoginParameter {
naIdToken: string;
naBirthday: string;
naCountry: string;
language: string;
timestamp: number;
timestamp: string;
requestId: string;
f: string;
}
/** /v3/Account/Login */
export interface AccountLogin {
user: CurrentUser<true>;
user: CurrentUser;
webApiServerCredential: {
accessToken: string;
expiresIn: number;
@ -78,25 +78,13 @@ export interface AccountLogin {
};
}
/** /v3/Account/GetToken, /v3/Extension/Account/GetToken */
/** /v3/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;
timestamp: string;
requestId: string;
f: string;
}
@ -115,112 +103,23 @@ export interface Announcement {
linkText?: string;
}
/** /v4/Announcement/List */
export type Announcements_4 = Announcement_4[];
export interface AnnouncementBase_4 {
id: string;
type: AnnouncementType;
title: string;
deliversAt: number;
imageUri: string;
image2Uri?: string;
hasRead: boolean;
}
export enum AnnouncementType {
OPERATION = 'OPERATION',
FRIEND_REQUEST = 'FRIEND_REQUEST',
}
export type Announcement_4 = AnnouncementOperation | AnnouncementFriendRequest;
export interface AnnouncementOperation extends AnnouncementBase_4 {
type: AnnouncementType.OPERATION;
operation: AnnouncementOperationContents;
}
export interface AnnouncementOperationContents {
contents: string;
}
export interface AnnouncementFriendRequest extends AnnouncementBase_4 {
type: AnnouncementType.FRIEND_REQUEST;
friendRequest: AnnouncementFriendRequestContents;
}
export interface AnnouncementFriendRequestContents {
nsaId: string;
friendRequestId: string;
}
/** /v3/Friend/List */
export interface Friends {
friends: Friend[];
}
/** /v4/Friend/List */
export interface Friends_4 {
friends: Friend_4[];
extractFriendsIds: string[];
}
export interface Friend {
id: number;
nsaId: string;
imageUri: string;
image2Uri: string;
name: string;
isFriend: boolean;
isFavoriteFriend: boolean;
isServiceUser: boolean;
isNew: boolean;
friendCreatedAt: number;
route: FriendRoute;
presence: PresenceOnline | PresenceOffline;
presence: Presence;
}
/** /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;
/**
@ -229,19 +128,7 @@ export interface Presence {
*/
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: {};
game: Game | {};
}
export enum PresenceState {
@ -251,17 +138,14 @@ export enum PresenceState {
INACTIVE = 'INACTIVE',
/** The user is selected in an application */
ONLINE = 'ONLINE',
/** The user is selected in an application and playing 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 enum PresencePlatform {
/** Nintendo Switch */
NX = 1,
/** Nintendo Switch 2 */
OUNCE = 2,
}
export interface Game {
name: string;
imageUri: string;
@ -269,9 +153,6 @@ export interface Game {
totalPlayTime: number;
/** 0 if never played before */
firstPlayedAt: number;
}
export interface PresenceGame extends Game {
sysDescription: string;
}
@ -285,19 +166,14 @@ export interface FriendCodeUrl {
export interface FriendCodeUser {
id: number;
nsaId: string;
imageUri: string;
image2Uri: string;
imageUrl: 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;
@ -307,31 +183,11 @@ export interface WebService {
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 | {};
@ -370,52 +226,38 @@ export interface User {
id: number;
nsaId: string;
imageUri: string;
image2Uri: string;
name: string;
}
/** /v4/User/ShowSelf */
export interface CurrentUser<WithNintendoAccount extends boolean = true> {
/** /v3/User/ShowSelf */
export interface CurrentUser {
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;
links: {
nintendoAccount: {
membership: {
active: {
active: boolean;
} | boolean;
};
};
friendCode: {
regenerable: boolean;
regenerableAt: number;
id: string;
};
};
permissions: {
playLog: PlayLogPermissions;
presence: PresencePermissions;
friendRequestReception: boolean;
};
presence: PresenceOnline_4 | PresenceOffline;
presence: Presence;
}
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',
@ -426,9 +268,7 @@ export enum PresencePermissions {
export interface CurrentUserPermissions {
etag: string;
permissions: {
playLog: PlayLogPermissions;
presence: PresencePermissions;
friendRequestReception: boolean;
};
}
@ -442,225 +282,8 @@ export interface UpdateCurrentUserPermissionsParameter {
etag: string;
}
/** /v4/User/PlayLog/Show */
export type UserPlayLog = Game[];
/** /v3/FriendRequest/Received/List, /v4/FriendRequest/Received/List */
export interface ReceivedFriendRequests {
friendRequests: ReceivedFriendRequest[];
/** /v2/Game/GetWebServiceToken */
export interface WebServiceToken {
accessToken: string;
expiresIn: number;
}
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

@ -1,8 +1,8 @@
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, NintendoAccountToken, NintendoAccountUser } 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');
@ -10,17 +10,12 @@ 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(
public token: string,
public naId: string,
@ -29,25 +24,7 @@ export default class MoonApi {
readonly znma_useragent = ZNMA_USER_AGENT,
) {}
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;
}
async fetch<T = unknown>(url: string, method = 'GET', body?: string, headers?: object) {
const [signal, cancel] = timeoutSignal();
const response = await fetch(MOON_URL + url, {
method,
@ -72,30 +49,13 @@ export default class MoonApi {
debug('fetch %s %s, response %s', method, url, response.status);
if (response.status === 401 && _autoRenewToken && !_attempt && this.onTokenExpired) {
this._token_expired = true;
const data = await response.json() as MoonError;
// _renewToken will be awaited when calling fetch
this._renewToken = this._renewToken ?? this.onTokenExpired.call(null, data, response).then(data => {
if (data) this.setTokenWithSavedToken(data);
}).finally(() => {
this._renewToken = null;
});
return this.fetch(url, method, body, headers, _autoRenewToken, _attempt + 1);
}
if (response.status !== 200) {
throw 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() {
@ -128,14 +88,11 @@ export default class MoonApi {
async renewToken(token: string) {
const data = await MoonApi.loginWithSessionToken(token);
this.setTokenWithSavedToken(data);
return data;
}
private setTokenWithSavedToken(data: MoonAuthData | PartialMoonAuthData) {
this.token = data.nintendoAccountToken.access_token!;
if ('user' in data) this.naId = data.user.id;
this._token_expired = false;
this.naId = data.user.id;
return data;
}
static async createWithSessionToken(token: string) {
@ -165,7 +122,7 @@ export default class MoonApi {
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,
@ -177,56 +134,10 @@ export default class MoonApi {
}
}
export class MoonErrorResponse extends ErrorResponse<MoonError> {}
const na_client_settings = {
client_id: ZNMA_CLIENT_ID,
scope: [
'openid',
'user',
'user.mii',
'moonUser:administration',
'moonDevice:create',
'moonOwnedDevice:administration',
'moonParentalControlSetting',
'moonParentalControlSetting:update',
'moonParentalControlSettingState',
'moonPairingState',
'moonSmartDevice:administration',
'moonDailySummary',
'moonMonthlySummary',
].join(' '),
};
export type NintendoAccountUserMoon = NintendoAccountUser;
export class NintendoAccountSessionAuthorisationMoon extends NintendoAccountSessionAuthorisation {
protected constructor(
authorise_url: string,
state: string,
verifier: string,
redirect_uri?: string,
) {
const { client_id, scope } = na_client_settings;
super(client_id, scope, authorise_url, state, verifier, redirect_uri);
}
static create(/** @internal */ redirect_uri?: string) {
const { client_id, scope } = na_client_settings;
const auth_data = generateAuthData(client_id, scope, redirect_uri);
return new this(auth_data.url, auth_data.state, auth_data.verifier, redirect_uri);
}
}
export interface MoonAuthData {
nintendoAccountToken: NintendoAccountToken;
user: NintendoAccountUserMoon;
user: NintendoAccountUser;
znma_version: string;
znma_build: string;
znma_useragent: string;
}
export interface PartialMoonAuthData {
nintendoAccountToken: NintendoAccountToken;
}

View File

@ -1,131 +1,11 @@
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');
@ -134,7 +14,8 @@ export async function getNintendoAccountSessionToken(code: string, verifier: str
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({
@ -145,22 +26,15 @@ export async function getNintendoAccountSessionToken(code: string, verifier: str
signal,
}).finally(cancel);
if (response.status !== 200) {
throw await NintendoAccountAuthErrorResponse.fromResponse(response, '[na] Non-200 status code');
}
const token = await response.json() as NintendoAccountSessionToken | 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) {
@ -182,26 +56,18 @@ export async function getNintendoAccountToken(token: string, client_id: string)
signal,
}).finally(cancel);
if (response.status !== 200) {
throw await NintendoAccountAuthErrorResponse.fromResponse(response, '[na] Non-200 status code');
}
const nintendoAccountToken = await response.json() as NintendoAccountToken | 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();
@ -216,19 +82,15 @@ export async function getNintendoAccountUser<S extends NintendoAccountScope>(tok
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 +98,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 +112,7 @@ export interface NintendoAccountSessionTokenJwtPayload extends JwtPayload {
}
export interface NintendoAccountToken {
scope: NintendoAccountScope[];
scope: string[];
token_type: 'Bearer';
id_token: string;
access_token?: string;
@ -265,7 +127,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 +139,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 +178,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 +206,76 @@ 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: Mii | null;
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;
analyticsOptedIn: boolean;
clientFriendsOptedInUpdatedAt: number;
}
export interface Mii {
favoriteColor: string;
id: string;
clientId: '1cfe3a55ed8924d9';
type: 'profile';
favoriteColor: MiiColour;
updatedAt: number;
coreData: {
'4': string;
};
clientId: '1cfe3a55ed8924d9';
imageUriTemplate: 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;
type: 'profile';
}
export interface NintendoAccountError {
@ -478,15 +286,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,51 +1,28 @@
import { fetch, FormData, Response } from 'undici';
import fetch from 'node-fetch';
import createDebug from 'debug';
import { WebServiceToken } from './coral-types.js';
import { defineResponse, ErrorResponse, HasResponse } from './util.js';
import { CoralApiInterface, NintendoAccountUserCoral } from './coral.js';
import { NintendoAccountUser } from './na.js';
import { ErrorResponse } from './util.js';
import CoralApi from './coral.js';
import { WebServiceError, Users, AuthToken, UserProfile, Newspapers, Newspaper, Emoticons, Reaction, IslandProfile } from './nooklink-types.js';
import createDebug from '../util/debug.js';
import { timeoutSignal } from '../util/misc.js';
const debug = createDebug('nxapi:api:nooklink');
export const NOOKLINK_WEBSERVICE_ID = 4953919198265344;
export const NOOKLINK_WEBSERVICE_ID = '4953919198265344';
export const NOOKLINK_WEBSERVICE_URL = 'https://web.sd.lp1.acbaa.srv.nintendo.net';
export const NOOKLINK_WEBSERVICE_USERAGENT = 'Mozilla/5.0 (Linux; Android 8.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/58.0.3029.125 Mobile Safari/537.36';
const NOOKLINK_URL = NOOKLINK_WEBSERVICE_URL + '/api';
const BLANCO_VERSION = '2.1.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;
}
async fetch<T = unknown>(url: string, method = 'GET', body?: string | FormData, headers?: object) {
const [signal, cancel] = timeoutSignal();
const response = await fetch(NOOKLINK_URL + url, {
method,
@ -54,11 +31,12 @@ export default class NooklinkApi {
'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,
@ -66,30 +44,17 @@ export default class NooklinkApi {
debug('fetch %s %s, response %s', method, url, response.status);
if (response.status === 401 && _autoRenewToken && !_attempt && this.onTokenExpired) {
this._token_expired = true;
const data = await response.json() as WebServiceError;
// _renewToken will be awaited when calling fetch
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 +68,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 createWithCoral(nso: CoralApi, user: NintendoAccountUser) {
const data = await this.loginWithCoral(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 loginWithCoral(nso: CoralApi, 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,
@ -159,7 +104,6 @@ export default class NooklinkApi {
headers: {
'Upgrade-Insecure-Requests': '1',
'User-Agent': NOOKLINK_WEBSERVICE_USERAGENT,
'x-appplatform': 'android',
'x-appcolorscheme': 'DARK',
'x-gamewebtoken': webserviceToken.accessToken,
'dnt': '1',
@ -172,17 +116,17 @@ export default class NooklinkApi {
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,45 +146,20 @@ 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;
}
async fetch<T = unknown>(url: string, method = 'GET', body?: string | FormData, headers?: object) {
const [signal, cancel] = timeoutSignal();
const response = await fetch(NOOKLINK_URL + url, {
method,
@ -249,12 +168,13 @@ export class NooklinkUserApi {
'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,
@ -262,30 +182,17 @@ export class NooklinkUserApi {
debug('fetch %s %s, response %s', method, url, response.status);
if (response.status === 401 && _autoRenewToken && !_attempt && this.onTokenExpired) {
this._token_expired = true;
const data = await response.json() as WebServiceError;
// _renewToken will be awaited when calling fetch
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 +220,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 +238,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

@ -9,14 +9,13 @@ export interface Season {
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();
let season = sort_ascending ? FIRST_SEASON : CURRENT_SEASON;
while (season) {
yield season;
@ -26,7 +25,7 @@ export function* getAllSeasons(sort_ascending = false) {
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(id: string): Season | null
export function getSeason(year: number | Date | string, month?: number): Season | null {
if (year instanceof Date) {
month = year.getUTCMonth() + 1;
@ -34,7 +33,7 @@ export function getSeason(year: number | Date | string, month?: number): Season
}
if (typeof year === 'string') {
// 180401T00_180601T00
const match = year.match(/^(\d{2,})(0\d|1[012])01T00_(\d{2,})(0\d|1[012])01T00$/);
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]);
@ -43,17 +42,10 @@ export function getSeason(year: number | Date | string, month?: number): Season
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');
if (nextyear !== parseInt(match[3]) || nextmonth !== parseInt(match[4])) 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);
}
const start = new Date(Date.UTC(year, month! - 1));
if (Date.now() < start.getTime()) return null;
if (start.getUTCFullYear() < 2018 || (start.getUTCFullYear() === 2018 && start.getUTCMonth() < 3)) return null;
@ -73,7 +65,6 @@ export function getSeason(year: number | Date | string, month?: number): Season
return {
id,
key,
index: getSeasonIndex(start.getUTCFullYear(), start.getUTCMonth() + 1),
start,
end,
complete: Date.now() > end.getTime(),
@ -84,18 +75,13 @@ export function getFirstSeason() {
return getSeason(2018, 5);
}
export function getCurrentSeason() {
return getSeason(new Date());
}
const FIRST_SEASON = getFirstSeason();
const CURRENT_SEASON = getSeason(new Date());
export function getNextSeason(season: Season | number): Season | null
export function getNextSeason(season: Season): 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());
const current_start = typeof season === 'number' ? new Date(Date.UTC(season, month!)) : season.start;
if (current_start.getUTCFullYear() === 2018 && current_start.getUTCMonth() === 3) {
current_start.setUTCMonth(4);
@ -110,8 +96,7 @@ export function getNextSeason(season: Season | number, month?: number): Season |
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,
start.getUTCMonth() === 11 ? 0 : start.getUTCMonth() + 1,
));
const id = toSeasonId(start.getUTCFullYear(), start.getUTCMonth() + 1);
@ -120,21 +105,16 @@ export function getNextSeason(season: Season | number, month?: number): Season |
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(season: Season): 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 current_start = typeof season === 'number' ? new Date(Date.UTC(season, month!)) : season.start;
const start = new Date(Date.UTC(
current_start.getUTCFullYear() - (current_start.getUTCMonth() === 0 ? 1 : 0),
@ -145,8 +125,7 @@ export function getPreviousSeason(season: Season | number, month?: number): Seas
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,
start.getUTCMonth() === 11 ? 0 : start.getUTCMonth() + 1,
));
const id = toSeasonId(start.getUTCFullYear(), start.getUTCMonth() + 1);
@ -159,67 +138,21 @@ export function getPreviousSeason(season: Season | number, month?: number): Seas
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');
if (year === 2018 && month < 5) throw new Error('Invalid season ID');
const now = new Date();
if (year > now.getUTCFullYear()) throw new Error('Invalid season ID');

View File

@ -1,16 +1,17 @@
import { randomUUID } from 'node:crypto';
import { Cookie, fetch, FormData, getSetCookies } from 'undici';
import fetch from 'node-fetch';
import createDebug from 'debug';
import { v4 as uuidgen } from 'uuid';
import { WebServiceToken } from './coral-types.js';
import { defineResponse, ErrorResponse } from './util.js';
import { CoralApiInterface, NintendoAccountUserCoral } from './coral.js';
import { NintendoAccountUser } from './na.js';
import { ErrorResponse } from './util.js';
import CoralApi from './coral.js';
import { ActiveFestivals, CoopResult, CoopResults, CoopSchedules, HeroRecords, LeagueMatchRankings, NicknameAndIcons, PastFestivals, Records, Result, Results, Schedules, ShareResponse, ShopMerchandises, Stages, Timeline, WebServiceError, XPowerRankingRecords, XPowerRankingSummary } from './splatnet2-types.js';
import createDebug from '../util/debug.js';
import { timeoutSignal } from '../util/misc.js';
import { toSeasonId, Rule as XPowerRankingRule, Season } from './splatnet2-xrank.js';
const debug = createDebug('nxapi:api:splatnet2');
export const SPLATNET2_WEBSERVICE_ID = 5741031244955648;
export const SPLATNET2_WEBSERVICE_ID = '5741031244955648';
export const SPLATNET2_WEBSERVICE_URL = 'https://app.splatoon2.nintendo.net/';
export const SPLATNET2_WEBSERVICE_USERAGENT = 'Mozilla/5.0 (Linux; Android 8.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/58.0.3029.125 Mobile Safari/537.36';
@ -24,19 +25,13 @@ export const updateIksmSessionLastUsed: {
} = {};
export default class SplatNet2Api {
protected _session_expired = false;
protected constructor(
public iksm_session: string,
public unique_id: string,
public useragent: string,
) {}
async fetch<T extends object>(url: string, method = 'GET', body?: string | FormData, headers?: object) {
if (this._session_expired) {
throw new Error('Session expired');
}
async fetch<T = unknown>(url: string, method = 'GET', body?: string | FormData, headers?: object) {
const [signal, cancel] = timeoutSignal();
const response = await fetch(SPLATNET2_URL + url, {
method,
@ -57,12 +52,8 @@ export default class SplatNet2Api {
debug('fetch %s %s, response %s', method, url, response.status);
if (response.status === 401) {
this._session_expired = true;
}
if (response.status !== 200) {
throw 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 +61,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() {
@ -192,7 +183,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,8 +230,8 @@ ${colour}
});
}
static async createWithCoral(coral: CoralApiInterface, user: NintendoAccountUserCoral) {
const data = await this.loginWithCoral(coral, user);
static async createWithCoral(nso: CoralApi, user: NintendoAccountUser) {
const data = await this.loginWithCoral(nso, user);
return {splatnet: this.createWithSavedToken(data), data};
}
@ -268,14 +259,14 @@ ${colour}
);
}
static async loginWithCoral(coral: CoralApiInterface, user: NintendoAccountUserCoral) {
const webserviceToken = await coral.getWebServiceToken(SPLATNET2_WEBSERVICE_ID);
static async loginWithCoral(nso: CoralApi, user: NintendoAccountUser) {
const webserviceToken = await nso.getWebServiceToken(SPLATNET2_WEBSERVICE_ID);
return this.loginWithWebServiceToken(webserviceToken, user);
return this.loginWithWebServiceToken(webserviceToken.result, user);
}
static async loginWithWebServiceToken(
webserviceToken: WebServiceToken, user: NintendoAccountUserCoral
webserviceToken: WebServiceToken, user: NintendoAccountUser
): Promise<SplatNet2AuthData> {
const url = new URL(SPLATNET2_WEBSERVICE_URL);
url.search = new URLSearchParams({
@ -289,7 +280,6 @@ ${colour}
headers: {
'Upgrade-Insecure-Requests': '1',
'User-Agent': SPLATNET2_WEBSERVICE_USERAGENT,
'x-appplatform': 'android',
'x-appcolorscheme': 'DARK',
'x-gamewebtoken': webserviceToken.accessToken,
'dnt': '1',
@ -302,22 +292,27 @@ ${colour}
debug('fetch %s %s, response %s', 'GET', url, response.status);
if (response.status !== 200) {
throw await SplatNet2ErrorResponse.fromResponse(response, '[splatnet2] Non-200 status code');
}
const body = await response.text();
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.replace(/^(.{6}).*/, '$1****'), 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,10 +320,10 @@ ${colour}
const mn = body.match(/<html(?:\s+[a-z0-9-]+(?:=(?:"[^"]*"|[^\s>]*))?)*\s+data-nsa-id=(?:"([^"]*)"|([^\s>]*))/i);
const [language, region, user_id, nsa_id] = [ml, mr, mu, mn].map(m => m?.[1] || m?.[2] || null);
if (!language) throw new 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);
if (!language) throw new Error('[splatnet2] Invalid language in response');
if (!region) throw new Error('[splatnet2] Invalid region in response');
if (!user_id) throw new Error('[splatnet2] Invalid unique player ID in response');
if (!nsa_id) throw new Error('[splatnet2] Invalid NSA ID in response');
debug('SplatNet 2 user', {
language,
@ -340,26 +335,24 @@ ${colour}
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 interface SplatNet2AuthData {
webserviceToken: WebServiceToken;
url: string;
cookies: string | Cookie[];
cookies: string;
body: string;
language: string;

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,5 @@
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 +7,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 {
@ -58,22 +30,18 @@ export class ErrorResponse<T = unknown> extends Error {
' from ' + response.url + ' (' + response.status + ' ' + response.statusText + ')\n' +
' ' + util.inspect(this.data ? this.data : this.body, {
compact: true,
maxStringLength: 100,
}).replace(/\n/g, '\n ') +
(lines.length ? '\n' + lines.join('\n') : ''),
});
}
static async fromResponse<T>(response: UndiciResponse, message: string) {
const body = await response.arrayBuffer();
return new this<T>(message, response, body);
}
}
Object.defineProperty(ErrorResponse, Symbol.hasInstance, {
configurable: true,
value: (instance: ErrorResponse) => {
return instance && ErrorResponseSymbol in instance;
return instance instanceof Error &&
'response' in instance &&
'body' in instance &&
'data' in instance;
},
});

View File

@ -1,300 +1,180 @@
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 fetch, { Response } from 'node-fetch';
import createDebug from 'debug';
import { ActiveEvent, Announcements, CurrentUser, Event, Friend, Presence, PresencePermissions, User, WebService, WebServiceToken, CoralErrorResponse, CoralStatus, CoralSuccessResponse, FriendCodeUser, FriendCodeUrl } from './coral-types.js';
import { ErrorResponse } from './util.js';
import CoralApi from './coral.js';
import { NintendoAccountUser } from './na.js';
import { SavedToken } from '../common/auth/coral.js';
import createDebug from '../util/debug.js';
import { timeoutSignal } from '../util/misc.js';
import { getAdditionalUserAgents, getUserAgent } from '../util/useragent.js';
const debug = createDebug('nxapi:api:znc-proxy');
export default class ZncProxyApi extends AbstractCoralApi implements CoralApiInterface {
export default class ZncProxyApi implements CoralApi {
// Not used by ZncProxyApi
onTokenExpired: ((data: CoralErrorResponse, res: Response) => Promise<void>) | null = null;
/** @internal */
_renewToken: Promise<void> | null = null;
readonly znca_version = '';
readonly znca_useragent = '';
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();
}
async fetchProxyApi<T = unknown>(
url: URL | string, method = 'GET', body?: string, _headers?: HeadersInit,
/** @internal */ _log?: string,
) {
if (typeof url === 'string' && url.startsWith('/')) url = url.substring(1);
const base_url = typeof this.url === 'string' ? new URL(this.url) : this.url;
if (typeof this.url === 'string' && !base_url.pathname.endsWith('/')) base_url.pathname += '/';
const headers = new Headers(_headers);
headers.append('Authorization', 'na ' + this.token);
headers.append('User-Agent', getUserAgent(this.useragent));
if (body && !headers.has('Content-Type')) {
headers.append('Content-Type', 'application/json');
}
) {}
async fetch<T = unknown>(url: string, method = 'GET', body?: string, headers?: object) {
const [signal, cancel] = timeoutSignal();
const response = await fetch(new URL(url, base_url), {
const response = await fetch(this.url + url, {
method,
headers,
headers: Object.assign({
'Authorization': 'na ' + this.token,
'User-Agent': getUserAgent(this.useragent),
}, 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);
debug('fetch %s %s, response %s', method, url, response.status);
if (!response.ok) {
throw await ZncProxyErrorResponse.fromResponse(response, '[zncproxy] Non-2xx status code');
if (response.status === 204) return null!;
if (response.status !== 200) {
throw new ErrorResponse('[zncproxy] Unknown error', response, await response.text());
}
const data = (response.status === 204 ? {} : await response.json()) as T;
const data = await response.json() as T;
return defineResponse(data, response);
return data;
}
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<CoralSuccessResponse<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: CoralStatus.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: CoralStatus.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: CoralStatus.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: CoralStatus.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: CoralStatus.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: CoralStatus.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: CoralStatus.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: CoralStatus.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);
const response = await this.fetch<{user: FriendCodeUser}>('/friendcode/' + friend_code);
return {status: CoralStatus.OK as const, result: response.user, correlationId: ''};
}
// async sendFriendRequest(nsa_id: string): Promise<Result<{}>> {
// throw new Error('Not supported in ZncProxyApi');
// }
async sendFriendRequest(nsa_id: string): Promise<CoralSuccessResponse<{}>> {
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});
const response = await this.fetch<{user: CurrentUser}>('/user');
return {status: CoralStatus.OK as const, result: response.user, correlationId: ''};
}
async getFriendCodeUrl() {
const result = await this.fetchProxyApi<{friendcode: FriendCodeUrl}>('friendcode');
return createResult(result, result.friendcode);
const response = await this.fetch<{friendcode: FriendCodeUrl}>('/friendcode');
return {status: CoralStatus.OK as const, result: response.friendcode, correlationId: ''};
}
async getCurrentUserPermissions() {
const user = await this.getCurrentUser();
return createResult(user, {
etag: user.etag,
permissions: user.permissions,
});
return {
status: CoralStatus.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<CoralSuccessResponse<{}>> {
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: CoralStatus.OK as const, result: response.token, correlationId: ''};
}
async getToken(token: string, user: NintendoAccountUser): ReturnType<CoralApi['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;
@ -311,13 +191,12 @@ export enum ZncPresenceEventStreamEvent {
}
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 [signal, cancel] = timeoutSignal();
const response = await fetch(presence_url, {
headers: {
'User-Agent': getUserAgent(useragent),
@ -328,22 +207,17 @@ export async function getPresenceFromUrl(presence_url: string, useragent?: strin
debug('fetch %s %s, response %s', 'GET', presence_url, response.status);
if (response.status !== 200) {
throw 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 +227,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;
}

View File

@ -3,7 +3,7 @@ Electron app
The Electron app is bundled into ~4 files in `dist/app/bundle` using Rollup. The main process code is not bundled for development, but is when packaging the app at `dist/bundle` (with the command line executable at `dist/bundle/cli-bundle.js`).
[electron.ts](electron.ts) exports all Electron APIs used in the main process. This is because the `electron` module doesn't actually exist - Electron patches the `require` function (but not the module importer). Additionally Electron does not support using a standard JavaScript module as the app entrypoint, so [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) (a CommonJS module) is used to import the actual app entrypoint after the `ready` event.
Electron APIs used in renderer processes should be imported directly from the `electron` module as they are always bundled into a CommonJS module.

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

View File

@ -56,7 +56,6 @@ function ButtonMac(props: {
const styles_mac = StyleSheet.create({
button: {
// @ts-expect-error react-native-web
cursor: 'default',
lineHeight: 19,
borderRadius: 3,
@ -77,12 +76,10 @@ const styles_mac = StyleSheet.create({
},
innerActive: {
backgroundColor: 'transparent',
// @ts-expect-error react-native-web
backgroundImage: 'linear-gradient(0deg, #00000050, #00000040)',
},
innerPressed: {
backgroundColor: 'transparent',
// @ts-expect-error react-native-web
backgroundImage: 'linear-gradient(0deg, #00000040, #00000020)',
},

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 +1,7 @@
import React from 'react';
export const svg_styles: React.CSSProperties = {
height: '1.2em',
height: '1em',
width: 'auto',
fill: 'currentColor',
alignSelf: 'center',
verticalAlign: -4,
};

View File

@ -2,13 +2,8 @@ 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>
const IconWeb = React.memo(() => <Text>
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512" style={svg_styles}><title>ionicons-v5-r</title><path d="M449.07,399.08,278.64,82.58c-12.08-22.44-44.26-22.44-56.35,0L51.87,399.08A32,32,0,0,0,80,446.25H420.89A32,32,0,0,0,449.07,399.08Zm-198.6-1.83a20,20,0,1,1,20-20A20,20,0,0,1,250.47,397.25ZM272.19,196.1l-5.74,122a16,16,0,0,1-32,0l-5.74-121.95v0a21.73,21.73,0,0,1,21.5-22.69h.21a21.74,21.74,0,0,1,21.73,22.7Z"/></svg>
</Text>);
export default Platform.OS === 'web' ? IconWeb : React.memo(() => null);

View File

@ -1,4 +1 @@
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,18 +1,14 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { StyleSheet, Text, TextInput, View } from 'react-native';
import { StyleSheet, Text, TextInput, useColorScheme, 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';
import { getAccounts, RequestState, Root, useAsync, useDiscordPresenceSource, useEventListener } from '../util.js';
export interface DiscordSetupProps {
users?: string[];
friend_nsa_id?: string;
/** @default true */
show_preferences_button?: boolean;
}
enum DiscordSourceType {
@ -21,68 +17,39 @@ enum DiscordSourceType {
NONE,
}
export default function DiscordSetupWindow(props: DiscordSetupProps) {
export default function DiscordSetup(props: DiscordSetupProps) {
const colour_scheme = useColorScheme();
const theme = colour_scheme === 'light' ? light : dark;
const [accent_colour, setAccentColour] = React.useState(() => ipc.getAccentColour());
useEventListener(events, 'systemPreferences:accent-colour', setAccentColour, []);
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 ?
const [selectedMode, setSelectedMode] = useState(props.users?.length && props.friend_nsa_id ?
DiscordSourceType.CORAL : DiscordSourceType.NONE);
const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
const [selectedFriendNsaId, setSelectedFriendNsaId] = useState<string | null>(props.friendNsaId ?? null);
const [selectedFriendNsaId, setSelectedFriendNsaId] = useState<string | null>(props.friend_nsa_id ?? null);
const [presenceUrl, setPresenceUrl] = useState('');
useEffect(() => {
if (!props.discordPresenceSource) {
setSelectedMode(props.friendNsaId ? DiscordSourceType.CORAL : DiscordSourceType.NONE);
} else if ('na_id' in props.discordPresenceSource) {
if (!discord_presence_source) {
setSelectedMode(props.friend_nsa_id ? DiscordSourceType.CORAL : DiscordSourceType.NONE);
} else if ('na_id' in discord_presence_source) {
setSelectedMode(DiscordSourceType.CORAL);
setSelectedUserId(props.discordPresenceSource.na_id);
setSelectedFriendNsaId(props.discordPresenceSource.friend_nsa_id ?? null);
} else if ('url' in props.discordPresenceSource) {
setSelectedUserId(discord_presence_source.na_id);
setSelectedFriendNsaId(discord_presence_source.friend_nsa_id ?? null);
} else if ('url' in discord_presence_source) {
setSelectedMode(DiscordSourceType.URL);
setPresenceUrl(props.discordPresenceSource.url);
setPresenceUrl(discord_presence_source.url);
}
}, [props.discordPresenceSource]);
}, [discord_presence_source]);
const user = useMemo(() => selectedUserId ? props.users?.find(u => u.user.id === selectedUserId) : undefined,
[selectedUserId, props.users]);
const user = useMemo(() => selectedUserId ? users?.find(u => u.user.id === selectedUserId) : undefined,
[selectedUserId, 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 ||
@ -90,11 +57,10 @@ function DiscordSetup(props: {
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]);
const filtered_users = useMemo(() => users?.filter(u => selectedUserId === u.user.id ||
(u.nso && (!props.users || props.users.includes(u.user.id)))), [users, props.users, selectedUserId]);
useEventListener(events, 'window:refresh', () => forceRefreshFriends(), []);
useEventListener(events, 'window:refresh', () => (forceRefreshAccounts(), forceRefreshFriends()), []);
useEffect(() => {
if (filtered_users?.length && !user) setSelectedUserId(filtered_users[0].user.id);
@ -119,89 +85,94 @@ function DiscordSetup(props: {
window.close();
}, [selectedMode, selectedUserId, selectedFriendNsaId, presenceUrl]);
return <View style={styles.main}>
<Text style={theme.text}>{t('title')}</Text>
useEffect(() => {
const handler = (event: KeyboardEvent) => event.key === 'Escape' && window.close();
window.addEventListener('keydown', handler);
return () => window.removeEventListener('keydown', handler);
}, []);
<Text style={[styles.header, theme.text]}>{t('mode_heading')}</Text>
if (!users || discord_presence_source_state !== RequestState.LOADED) {
return null;
}
<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>
return <Root title="Discord Rich Presence setup" scrollable autoresize>
<View style={styles.main}>
<Text style={theme.text}>Discord Rich Presence setup</Text>
{selectedMode === DiscordSourceType.CORAL ? <>
<Text style={[styles.header, theme.text]}>{t('coral_user_heading')}</Text>
<Text style={[styles.help, theme.text]}>{t('coral_user_help')}</Text>
<Text style={[styles.header, theme.text]}>1. Select mode</Text>
<Picker<string> selectedValue={selectedUserId ?? ''} onValueChange={setSelectedUserId}
<Picker<DiscordSourceType> selectedValue={selectedMode} onValueChange={v => setSelectedMode(parseInt(v))}
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.Item label="Select a user that is friends with the user you want to share"
value={DiscordSourceType.CORAL} />
<Picker.Item label="Enter a URL that returns the presence data you want to share"
value={DiscordSourceType.URL} />
<Picker.Item label="Disable" value={DiscordSourceType.NONE} />
</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>
{selectedMode === DiscordSourceType.CORAL ? <>
<Text style={[styles.header, theme.text]}>2. Select user</Text>
<Text style={[styles.help, theme.text]}>This user must be friends with the user you want to share.</Text>
<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}
<Picker<string> selectedValue={selectedUserId ?? ''} onValueChange={setSelectedUserId}
style={[styles.picker, theme.picker]}
>
{friends_with_presence.map(f => <Picker.Item key={f.nsaId} label={f.name} value={f.nsaId} />)}
{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.friend_nsa_id && (!selectedFriendNsaId || selectedFriendNsaId === props.friend_nsa_id) ? <>
<Text style={[styles.header, theme.text]}>3. Select friend</Text>
<Text style={[styles.help, theme.text]}>This is the user you want to share.</Text>
<Picker<string> selectedValue={selectedFriendNsaId ?? ''} onValueChange={setSelectedFriendNsaId}
style={[styles.picker, theme.picker]}
enabled={false}
>
<Picker.Item key={props.friend_nsa_id} label={friend?.name ?? props.friend_nsa_id}
value={props.friend_nsa_id} />
</Picker>
</> : user && friends_with_presence ? <>
<Text style={[styles.header, theme.text]}>3. Select friend</Text>
<Text style={[styles.help, theme.text]}>This is the user you want to share.</Text>
<Picker<string> selectedValue={selectedFriendNsaId ?? ''} onValueChange={setSelectedFriendNsaId}
style={[styles.picker, theme.picker]}
>
{friends_with_presence.map(f => <Picker.Item key={f.nsaId} label={f.name} value={f.nsaId} />)}
</Picker>
</> : null}
</> : null}
</> : null}
{selectedMode === DiscordSourceType.URL ? <>
<Text style={[styles.header, theme.text]}>{t('url_heading')}</Text>
<Text style={[styles.help, theme.text]}>{t('url_help')}</Text>
{selectedMode === DiscordSourceType.URL ? <>
<Text style={[styles.header, theme.text]}>2. Enter presence URL</Text>
<Text style={[styles.help, theme.text]}>This must be a HTTPS URL that returns a JSON object with either a user, friend or presence key. This is intended to be used with nxapi's znc API proxy.</Text>
<TextInput value={presenceUrl} onChangeText={setPresenceUrl}
placeholder="https://nxapi.example.com/api/znc/friend/..."
style={[styles.textInput, theme.textInput]} />
</> : null}
<TextInput value={presenceUrl} onChangeText={setPresenceUrl}
placeholder="https://nxapi.example.com/api/znc/friend/..."
style={[styles.textInput, theme.textInput]} />
</> : null}
{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 style={styles.buttons}>
<View style={styles.button}>
<Button title="Cancel"
onPress={() => window.close()}
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
</View>
<View style={styles.button}>
<Button title="Save"
onPress={save}
primary
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
</View>
</View>
</View>
</View>;
</Root>;
}
const styles = StyleSheet.create({
@ -251,12 +222,6 @@ const styles = StyleSheet.create({
button: {
marginLeft: 10,
},
buttonPreferences: {
marginTop: 10,
marginLeft: 0,
flexDirection: 'row',
justifyContent: 'flex-start',
},
});
const light = StyleSheet.create({

View File

@ -1,30 +1,32 @@
/// <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 { ActivityIndicator, Image, StyleSheet, Text, TouchableOpacity, useColorScheme, View } from 'react-native';
import { CheckBox } from 'react-native-web';
import { Friend, Presence, PresenceGame, PresencePermissions, PresencePlatform, PresenceState } from '../../../api/coral-types.js';
import { Game, Presence, PresencePermissions, 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';
import { RequestState, Root, useAccentColour, useAsync, useColourScheme, useDiscordPresenceSource, useEventListener } from '../util.js';
export interface FriendProps {
user: string;
friend: string;
}
export default function FriendWindow(props: FriendProps) {
export default function Friend(props: FriendProps) {
const colour_scheme = useColorScheme();
const theme = colour_scheme === 'light' ? light : dark;
const [accent_colour, setAccentColour] = React.useState(() => ipc.getAccentColour());
useEventListener(events, 'systemPreferences:accent-colour', setAccentColour, []);
const [discord_presence_source, discord_presence_source_state] = useDiscordPresenceSource();
const [token] = useAsync(useCallback(() => ipc.getNintendoAccountCoralToken(props.user), [ipc, props.user]));
const [token] = useAsync(useCallback(() => ipc.getNintendoAccountNsoToken(props.user), [ipc, props.user]));
const [user] = useAsync(useCallback(() => token ?
ipc.getSavedCoralToken(token) : Promise.resolve(null), [ipc, token]));
ipc.getSavedNsoToken(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);
@ -48,7 +50,6 @@ export default function FriendWindow(props: FriendProps) {
if (!user || !friend || discord_presence_source_state !== RequestState.LOADED) {
return <Root title={friend?.name} titleUser={user ?? undefined}
autoresize={!!user && discord_presence_source_state === RequestState.LOADED}
i18nNamespace={['friend_window', 'time_since']}
>
<View style={styles.loading}>
<ActivityIndicator size="large" color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
@ -62,127 +63,80 @@ export default function FriendWindow(props: FriendProps) {
const can_see_user_presence = user.nsoAccount.user.permissions.presence === PresencePermissions.FRIENDS ||
(user.nsoAccount.user.permissions.presence === PresencePermissions.FAVORITE_FRIENDS && friend.isFavoriteFriend);
return <Root title={friend.name} titleUser={user} autoresize 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>;
}
return <Root title={friend.name} titleUser={user} autoresize>
<View style={styles.main}>
<View style={styles.friend}>
<Image source={{uri: friend.imageUri, width: 130, height: 130}} style={styles.friendImage} />
<Text style={[styles.friendName, theme.text]}>{friend.name}</Text>
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>
{friend.presence.updatedAt ?
<FriendPresence presence={friend.presence} /> :
<Text style={[styles.noPresence, theme.text]}>You don't have access to this user's presence, or they have never been online.</Text>}
</View>
<View style={styles.buttons}>
{props.showDiscordPresenceSetup ? <View style={styles.discord}>
<CheckBox
value={props.discordPresenceActive ?? false}
onValueChange={v => props.setDiscordPresenceActive?.(!!v)}
<View style={styles.right}>
<View style={styles.detail}>
{(friend.presence.state === PresenceState.ONLINE || friend.presence.state === PresenceState.PLAYING) &&
'name' in friend.presence.game ? <FriendPresenceGame game={friend.presence.game} /> : null}
<Text style={[styles.friendNsaId, theme.text]}>NSA ID: <Text style={styles.friendNsaIdValue}>{friend.nsaId}</Text></Text>
<Text style={[styles.friendCoralId, theme.text]}>{friend.isServiceUser ? <>
Coral user ID: <Text style={styles.friendCoralIdValue}>{friend.id}</Text>
</> : 'Never used Nintendo Switch Online app'}</Text>
<Text style={[styles.friendCreatedAt, theme.text]}>Friends since {new Date(friend.friendCreatedAt * 1000).toLocaleString('en-GB')}</Text>
{friend.presence.updatedAt ? <Text style={[styles.presenceUpdatedAt, theme.text]}>Presence updated at {new Date(friend.presence.updatedAt * 1000).toLocaleString('en-GB')}</Text> : null}
<Text style={[styles.canSeeUserPresence, theme.text]}>This user {can_see_user_presence ? 'can' : 'can not'} see your presence.</Text>
</View>
<View style={styles.buttons}>
{discord_presence_active || friend.presence.updatedAt ? <View style={styles.discord}>
<CheckBox
value={discord_presence_active ?? false}
onValueChange={v => ipc.setDiscordPresenceSource(v ?
{na_id: user.user.id, friend_nsa_id: friend.nsaId} : null)}
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}
style={styles.discordCheckbox}
/>
<TouchableOpacity onPress={() => ipc.setDiscordPresenceSource(!discord_presence_active ?
{na_id: user.user.id, friend_nsa_id: friend.nsaId} : null)}>
<Text style={theme.text}>Share presence to Discord</Text>
</TouchableOpacity>
</View> : null}
<Button title="Close"
onPress={() => window.close()}
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 />
primary autoFocus />
</View>
</View>
</View>
</View>;
</Root>;
}
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>;
if (props.presence.state === PresenceState.ONLINE || props.presence.state === PresenceState.PLAYING) {
return <Text style={[styles.presenceText, theme.text, styles.presenceTextOnline]}>Playing {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}
<Text style={[styles.presenceText, styles.presenceTextOffline, theme.text]}>Offline</Text>
{logout ? <Text style={[styles.presenceText, styles.presenceTextOffline, theme.text]}>Last seen {logout.toLocaleString('en-GB')}</Text> : null}
</View>;
}
function FriendPresenceGame(props: {
game: PresenceGame;
game: Game;
}) {
const theme = useColourScheme() === 'light' ? light : dark;
const accent_colour = useAccentColour();
const { t, i18n } = useTranslation('friend_window');
const openShop = useCallback(() => {
ipc.openExternalUrl(props.game.shopUri);
@ -197,26 +151,12 @@ function FriendPresenceGame(props: {
<View style={styles.gameDetail}>
<Text style={[styles.gameName, theme.text]}>{props.game.name}</Text>
{props.game.sysDescription ? <Text style={[styles.gameActivity, theme.text]}>{props.game.sysDescription}</Text> : null}
<Text style={[styles.gameTotalPlayTime, theme.text]}>
{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}
<Text style={[styles.gameTotalPlayTime, theme.text]}>Played for {hrduration(props.game.totalPlayTime)}</Text>
<Text style={[styles.gameFirstPlayed, theme.text]}>First played {first_played?.toLocaleString('en-GB') ?? 'now'}</Text>
{titleid ? <Text style={[styles.gameTitleId, theme.text]}>Title ID: <Text style={styles.gameTitleIdValue}>{titleid}</Text></Text> : null}
<View style={styles.gameShopButton}>
<Button title={t('game_shop')} onPress={openShop} color={'#' + accent_colour} />
<Button title="Nintendo eShop" onPress={openShop} color={'#' + accent_colour} />
</View>
</View>
</View>;

View File

@ -3,16 +3,10 @@ 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';
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');

View File

@ -1,4 +1,4 @@
import { EventEmitter } from 'node:events';
import { EventEmitter } from 'events';
import createDebug from 'debug';
import type { NxapiElectronIpc } from '../preload/index.js';

View File

@ -1,12 +1,11 @@
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';
import { Button } from '../components/index.js';
export default function SetupDiscordPresence(props: {
user: User;
@ -14,7 +13,6 @@ export default function SetupDiscordPresence(props: {
}) {
const theme = useColourScheme() === 'light' ? light : dark;
const accent_colour = useAccentColour();
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'discord_section' });
const [source, discord_presence_source_state] = useDiscordPresenceSource();
@ -37,46 +35,51 @@ export default function SetupDiscordPresence(props: {
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>
Use one of these accounts to set up Discord Rich Presence for this user:{' '}
{added_friends.map((u, i) => <React.Fragment key={u.user.id}>
{i === 0 ? '' : ', '}
<Image source={{uri: u.nso!.nsoAccount.user.imageUri, width: 16, height: 16}} style={styles.discordNsoUserImage} />{' '}
{u.nso!.nsoAccount.user.name}
{u.nso!.nsoAccount.user.name !== u.user.nickname ? ' (' + u.user.nickname + ')' : ''}
</React.Fragment>)}.
</Text>
<View style={styles.button}>
<Button title={t('setup')} onPress={() => ipc.showDiscordModal({
<Button title="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>
<Text style={[styles.text, theme.text]}>Add a Nintendo Switch Online account with this user as a friend to set up Discord Rich Presence.</Text>
</> : 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>
<Text style={[styles.text, theme.text]}>
This user's presence is being shared to Discord.
</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>
<Image source={{uri: friend.imageUri, width: 16, height: 16}} style={styles.discordNsoUserImage} />{' '}
{friend.name}'s presence is being shared to Discord using this account.
</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>
<Text style={[styles.text, theme.text]}>
An unknown user's presence is being shared to Discord using this account.
</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>
This user's presence is being shared to Discord using{' '}
<Image source={{uri: auth_user.nsoAccount.user.imageUri, width: 16, height: 16}} style={styles.discordNsoUserImage} />{' '}
{auth_user.nsoAccount.user.name}
{auth_user.nsoAccount.user.name !== auth_user.user.nickname ? ' (' + auth_user.user.nickname + ')' : ''}.
</Text>
</> : null;
return content ? <Section title={t('title')}>
return content ? <Section title="Discord Rich Presence">
<View style={styles.content}>
{content}
{source ? <View style={styles.button}>
<Button title={t('disable')}
onPress={() => ipc.setDiscordPresenceSource(null)} color={'#' + accent_colour} />
<Button title="Disable" onPress={() => ipc.setDiscordPresenceSource(null)} color={'#' + accent_colour} />
</View> : null}
</View>
</Section> : null;
@ -93,6 +96,10 @@ const styles = StyleSheet.create({
fontSize: 13,
opacity: 0.7,
},
discordNsoUserImage: {
borderRadius: 8,
textAlignVertical: -3,
},
button: {
marginTop: 10,

View File

@ -1,41 +1,23 @@
import React, { useCallback, useEffect, useState } from 'react';
import React, { useCallback, useEffect } 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 { DiscordPresenceSource, DiscordPresenceSourceUrl, DiscordPresenceSourceCoral } from '../../common/types.js';
import { DiscordPresence } from '../../../discord/util.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}
{props.presence && props.user ? <DiscordPresence presence={props.presence} user={props.user} /> : null}
</View>
</TouchableOpacity>;
}
@ -53,10 +35,8 @@ function renderDiscordPresenceSource(source: DiscordPresenceSource | null) {
function DiscordPresenceSourceCoral(props: {
source: DiscordPresenceSourceCoral;
}) {
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'sidebar' });
const [token] = useAsync(useCallback(() =>
ipc.getNintendoAccountCoralToken(props.source.na_id), [ipc, props.source.na_id]));
ipc.getNintendoAccountNsoToken(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);
@ -71,11 +51,11 @@ function DiscordPresenceSourceCoral(props: {
return <View style={styles.discordSource}>
{friend ? <Text style={styles.discordSourceText}>
<Trans i18nKey="main_window:sidebar.discord_active_friend">
<NintendoSwitchUser friend={friend} />
</Trans>
Discord Rich Presence active:{' '}
<Image source={{uri: friend.imageUri, width: 16, height: 16}} style={styles.discordNsoUserImage} />{' '}
{friend.name}
</Text> : <Text style={styles.discordSourceText}>
{t('discord_active')}
Discord Rich Presence active
</Text>}
</View>;
}
@ -83,70 +63,41 @@ function DiscordPresenceSourceCoral(props: {
function DiscordPresenceSourceUrl(props: {
source: DiscordPresenceSourceUrl;
}) {
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'sidebar' });
return <View style={styles.discordSource}>
<Text style={styles.discordSourceText} numberOfLines={3} ellipsizeMode="tail">
{t('discord_active')}:{' '}
Discord Rich Presence 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>
<Text style={styles.discordSourceText}>Discord Rich Presence not active</Text>
</View>;
}
function DiscordPresence(props: {
presence: DiscordPresence | null;
user: User | null;
presence: DiscordPresence;
user: User;
}) {
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'sidebar' });
const large_image_url = props.presence ? props.presence.activity.largeImageKey?.match(/^\d{16}$/) ?
const large_image_url = 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;
props.presence.activity.largeImageKey;
const user_image_url = 'https://cdn.discordapp.com/avatars/' + props.user.id + '/' + props.user.avatar + '.png';
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}>
return <>
<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>
<Text style={styles.discordPresenceText} numberOfLines={1} ellipsizeMode="tail">Playing</Text>
</View>
</TouchableOpacity>;
<View style={styles.discordUser}>
<Image source={{uri: user_image_url, width: 18, height: 18}} style={styles.discordUserImage} />
<Text style={styles.discordUserText} numberOfLines={1} ellipsizeMode="tail">{props.user.username}#{props.user.discriminator}</Text>
</View>
</>;
}
const styles = StyleSheet.create({
@ -164,18 +115,18 @@ const styles = StyleSheet.create({
discordSourceText: {
color: TEXT_COLOUR_DARK,
},
discordNsoUserImage: {
borderRadius: 8,
textAlignVertical: -3,
},
discordSourceUrlValue: {
fontFamily: 'monospace',
fontSize: 12,
userSelect: 'all',
},
discordPresenceContainer: {
marginTop: 2,
},
discordPresence: {
marginTop: 10,
marginTop: 12,
flexDirection: 'row',
alignItems: 'center',
},
@ -199,26 +150,4 @@ const styles = StyleSheet.create({
discordUserText: {
color: TEXT_COLOUR_DARK,
},
discordUserDiscriminator: {
opacity: 0.7,
},
errorTouchable: {
marginVertical: -16,
marginHorizontal: -20,
marginTop: 6,
paddingVertical: 16,
paddingHorizontal: 20,
paddingTop: 10,
},
error: {
flexDirection: 'row',
},
icon: {
marginRight: 10,
color: TEXT_COLOUR_DARK,
},
errorText: {
color: TEXT_COLOUR_DARK,
},
});

View File

@ -1,6 +1,5 @@
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';
@ -9,38 +8,34 @@ import Section from './section.js';
import { Button } from '../components/index.js';
export default function Event(props: {
user: User<true>;
user: User;
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']}
>
return <Section title="Voice chat" loading={props.loading} error={props.error}>
<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})}
{event_members} in game, {voip_members} in voice chat
{props.event.members.length > 1 ? ' of ' + props.event.members.length + ' members' : ''}
</Text>
<Text style={[styles.eventInstruction, theme.text]}>
{t(voip_members ? 'app_join' : 'app_start')}
Use the Nintendo Switch Online app on iOS or Android to {voip_members ? 'join' : 'start'} voice chat.
</Text>
{props.event.shareUri ? <View style={styles.shareButton}>
<Button title={t('share')} onPress={() => ipc.share({urls: [props.event.shareUri]})}
<Button title="Share" onPress={() => ipc.share({urls: [props.event.shareUri]})}
color={'#' + accent_colour} />
</View> : null}
</View>

View File

@ -1,62 +1,48 @@
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 { useColourScheme, User } from '../util.js';
import { Friend, 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';
import Section from './section.js';
export default function Friends(props: {
user: User<true>;
friends: Friend_4[];
user: User;
friends: Friend[];
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 onFriendCodeContextMenu = useCallback(() => {
ipc.showFriendCodeMenu(props.user.nso!.nsoAccount.user.links.friendCode);
}, [ipc, props.user.nso?.nsoAccount.user.links.friendCode]);
const header_buttons = <TouchableOpacity onPress={showAddFriendModal} style={styles.iconTouchable}>
<Text style={[styles.icon, {color: '#' + accent_colour}]}><AddOutline title={t('add')!} /></Text>
</TouchableOpacity>;
const fc = <Text
style={styles.friendCodeValue}
// @ts-expect-error react-native-web
onContextMenu={onFriendCodeContextMenu}
>SW-{props.user.nso!.nsoAccount.user.links.friendCode.id}</Text>;
return <Section title={t('title')} loading={props.loading} error={props.error}
errorKey={[props.user.nsotoken, 'friends']}
headerButtons={header_buttons}
>
return <Section title="Friends" loading={props.loading} error={props.error}>
{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>
<Text style={[styles.noFriendsText, theme.text]}>Add friends using a Nintendo Switch console.</Text>
<Text style={[styles.noFriendsText, styles.noFriendsFriendCodeText, theme.text]}>Your friend code: {fc}</Text>
</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>
<Text style={[styles.friendCode, theme.text]}>Your friend code: {fc}</Text>
</View> : null}
</Section>;
}
function Friend(props: {
friend: Friend_4;
user?: User<true>;
friend: Friend;
user?: User;
}) {
const theme = useColourScheme() === 'light' ? light : dark;
@ -68,12 +54,12 @@ function Friend(props: {
}, [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]);
}, [ipc, props.user?.user, props.user?.nso?.nsoAccount.user]);
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} />
<Image source={{uri: props.friend.imageUri, 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>
@ -98,26 +84,15 @@ 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, theme.text, styles.presenceTextOnline]}>Playing</Text>;
}
return <Text style={[styles.presenceText, styles.presenceTextOffline, theme.text]}>{logout ? since_logout : t('presence_offline')}</Text>;
return <Text style={[styles.presenceText, styles.presenceTextOffline, theme.text]}>Offline</Text>;
}
const styles = StyleSheet.create({
iconTouchable: {
marginLeft: 10,
},
icon: {
fontSize: HEADER_SIZE,
},
footer: {
paddingBottom: 16,
paddingHorizontal: ipc.platform === 'win32' ? 24 : 20,
@ -126,6 +101,10 @@ const styles = StyleSheet.create({
fontSize: 12,
opacity: 0.7,
},
friendCodeValue: {
// @ts-expect-error
userSelect: 'all',
},
content: {
paddingBottom: 16,
paddingLeft: ipc.platform === 'win32' ? 24 : 20,

View File

@ -1,14 +1,12 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { ScrollView, StyleSheet, Text, useColorScheme, View } from 'react-native';
import { ScrollView, StyleSheet, Text, TouchableOpacity, useColorScheme, View } from 'react-native';
import { CheckBox } from 'react-native-web';
import ipc, { events } from '../ipc.js';
import { getAccounts, Root, useAsync, useEventListener } from '../util.js';
import { AccentColourContext, 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;
@ -27,8 +25,7 @@ export default function App(props: AppProps) {
const [selectedUserId, setSelectedUserId] = useState<string | undefined>(undefined);
const selectedUser = useMemo(() => users?.find(u => u.user.id === selectedUserId), [users, selectedUserId]);
const [focused, setFocused] = useState(ipc.getWindowFocused());
useEventListener(events, 'window:focused', setFocused, []);
const [auto_refresh, setAutoRefresh] = useState<number | undefined>(undefined);
useEffect(() => {
if (!selectedUser) setSelectedUserId(users?.[0]?.user.id);
@ -38,19 +35,31 @@ export default function App(props: AppProps) {
titleUser={selectedUser}
vibrancy={props.vibrancy}
style={[styles.app, !props.vibrancy ? theme.appNoVibrancy : null]}
i18nNamespace={['main_window', 'time_since']}
>
<Sidebar users={users} selectedUser={selectedUserId} onSelectUser={setSelectedUserId}
insetTitleBarControls={props.insetTitleBarControls}
/>
>
<View style={[styles.content, styles.checkboxContainer]}>
<AccentColourContext.Consumer children={accent_colour => (
<CheckBox
value={!!auto_refresh}
onValueChange={v => setAutoRefresh(v ? 30 * 1000 : undefined)}
color={'#' + accent_colour}
style={styles.checkbox}
/>
)} />
<TouchableOpacity onPress={() => setAutoRefresh(auto_refresh ? undefined : 30 * 1000)}>
<Text style={theme.text}>Enable auto refresh</Text>
</TouchableOpacity>
</View>
</Sidebar>
<View style={[styles.main, theme.main]}>
<ScrollView style={styles.scroller} contentContainerStyle={styles.scrollerContent}>
<StatusUpdates />
<Update />
{selectedUser ? <Main key={selectedUser.user.id} user={selectedUser}
autoRefresh={focused ? REFRESH_INTERVAL : undefined} /> : null}
autoRefresh={auto_refresh} /> : null}
</ScrollView>
</View>
</Root>;
@ -69,6 +78,19 @@ const styles = StyleSheet.create({
scrollerContent: {
flex: 1,
},
content: {
paddingVertical: 16,
paddingHorizontal: 20,
},
checkboxContainer: {
flex: 1,
marginRight: 20,
flexDirection: 'row',
alignItems: 'center',
},
checkbox: {
marginRight: 10,
},
});
const light = StyleSheet.create({

View File

@ -1,6 +1,5 @@
import React, { useCallback, useEffect, useState } from 'react';
import React, { useCallback, useEffect } 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';
@ -10,6 +9,7 @@ import Section from './section.js';
import { TEXT_COLOUR_DARK, TEXT_COLOUR_LIGHT } from '../constants.js';
import SetupDiscordPresence from './discord-setup.js';
import { Button } from '../components/index.js';
import { hrlist } from '../../../util/misc.js';
export default function Main(props: {
user: User;
@ -17,26 +17,21 @@ export default function Main(props: {
}) {
const theme = useColourScheme() === 'light' ? light : dark;
const accent_colour = useAccentColour();
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'main_section' });
const [announcements, announcements_error, announcements_state] = useAsync(useCallback(() => props.user.nsotoken ?
ipc.getCoralAnnouncements(props.user.nsotoken) : Promise.resolve(null), [ipc, props.user.nsotoken]));
ipc.getNsoAnnouncements(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]));
ipc.getNsoWebServices(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());
ipc.getNsoActiveEvent(props.user.nsotoken) : Promise.resolve(null), [ipc, props.user.nsotoken]));
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]);
@ -46,20 +41,15 @@ export default function Main(props: {
return () => clearTimeout(timeout);
}, [ipc, props.user.nsotoken, loading, props.autoRefresh]);
useEffect(() => {
if (loading || !props.autoRefresh) return;
// When enabling auto refresh, update now if we haven't updated within the interval
if (last_refresh_at + props.autoRefresh < Date.now()) refresh();
}, [ipc, props.autoRefresh]);
useEventListener(events, 'window:refresh', refresh, []);
const showErrorDetails = useCallback(() => {
ipc.showCoralErrors(props.user.nsotoken!, ['friends', 'webservices', 'activeevent']);
if (friends_error) alert(friends_error.stack ?? friends_error.message);
if (webservices_error) alert(webservices_error.stack ?? webservices_error.message);
if (active_event_error) alert(active_event_error.stack ?? active_event_error.message);
}, [friends_error, webservices_error, active_event_error]);
if (!friends || !webservices || !active_event) {
if (!announcements || !friends || !webservices || !active_event) {
if (loading) {
return <View style={styles.loading}>
<ActivityIndicator size="large" color={'#' + accent_colour} />
@ -68,17 +58,18 @@ export default function Main(props: {
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'));
if (friends_error) errors.push('friends');
if (webservices_error) errors.push('game-specific services');
if (active_event_error) errors.push('voice chat');
const errors_text = hrlist(errors);
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>
<Text style={[styles.errorHeader, theme.text]}>Error loading data</Text>
<Text style={[styles.errorMessage, theme.text]}>An error occured while loading {errors_text} data.</Text>
<View style={styles.errorActions}>
<Button title={t('error.retry')} onPress={refresh} color={'#' + accent_colour} primary />
<Button title="Retry" onPress={refresh} color={'#' + accent_colour} primary />
<TouchableOpacity onPress={showErrorDetails} style={styles.errorViewDetailsTouchable}>
<Text style={theme.text}>{t('error.view_details')}</Text>
<Text style={theme.text}>View details</Text>
</TouchableOpacity>
</View>
</View>;
@ -101,15 +92,14 @@ export default function Main(props: {
function MoonOnlyUser() {
const theme = useColourScheme() === 'light' ? light : dark;
const accent_colour = useAccentColour();
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'main_section.moon_only_user' });
return <Section title={t('title')}>
return <Section title="Nintendo Switch Online">
<View style={styles.moonOnlyUser}>
<Text style={[styles.moonOnlyUserText, theme.text]}>{t('desc_1')}</Text>
<Text style={[styles.moonOnlyUserText, theme.text]}>{t('desc_2')}</Text>
<Text style={[styles.moonOnlyUserText, theme.text]}>This user is signed in to the Nintendo Switch Parental Controls app, but not the Nintendo Switch Online app.</Text>
<Text style={[styles.moonOnlyUserText, theme.text]}>Login to the Nintendo Switch Online app to view details here, or use the nxapi command to access Parental Controls data.</Text>
<View style={styles.moonOnlyUserButton}>
<Button title={t('login')} onPress={() => ipc.addCoralAccount()} color={'#' + accent_colour} primary />
<Button title="Login" onPress={() => ipc.addNsoAccount()} color={'#' + accent_colour} primary />
</View>
</View>
</Section>;

View File

@ -1,9 +1,7 @@
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';
@ -11,15 +9,12 @@ 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);
alert(props.error);
}, [props.error]);
return <View style={[styles.container, theme.container]}>
@ -28,16 +23,15 @@ export default function Section(props: React.PropsWithChildren<{
{props.loading ? <ActivityIndicator style={styles.activityIndicator} size={HEADER_SIZE}
color={'#' + accent_colour} /> :
props.error ? <TouchableOpacity onPress={showErrorDetails} style={styles.iconTouchable}>
<Text style={[styles.icon, {color: '#' + accent_colour}]}><Warning title={t('section_error')!} /></Text>
<Text style={[styles.icon, {color: '#' + accent_colour}]}><Warning /></Text>
</TouchableOpacity> : null}
{props.headerButtons}
</View>
{props.children}
</View>;
}
export const HEADER_SIZE = ipc.platform === 'win32' ? 24 : 14;
const HEADER_SIZE = ipc.platform === 'win32' ? 24 : 14;
const styles = StyleSheet.create({
container: {

View File

@ -1,6 +1,5 @@
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';
@ -14,7 +13,6 @@ export default function Sidebar(props: {
children?: React.ReactNode;
}) {
const theme = useColourScheme() === 'light' ? light : dark;
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'sidebar' });
const [discord_presence_source, discord_presence_source_state] = useDiscordPresenceSource();
const presence = useActiveDiscordPresence();
@ -42,13 +40,13 @@ export default function Sidebar(props: {
</View> : null}
{props.users ? <TouchableOpacity onPress={() => ipc.showAddUserMenu()} style={styles.addUser}>
<Text style={theme.text}>{t('add_user')}</Text>
<Text style={theme.text}>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>
<Text style={theme.text}>Set up Discord Rich Presence</Text>
</TouchableOpacity> : null}
{props.children}
@ -68,24 +66,15 @@ function User(props: {
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/' +
const miiImageSource: ImageURISource = props.user.user.mii ? {
uri: '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(),
props.user.user.mii.etag + '.png' +
'?type=face&width=140&bgColor=DFDFDFFF',
width: 32,
height: 32,
} : {
uri: 'https://cdn.accounts.nintendo.com/account/images/common/defaults/mii.png',
width: 32,
height: 32,
};
@ -101,8 +90,7 @@ function User(props: {
{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}} />
<Image source={{uri: 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 File

@ -1,48 +0,0 @@
import React, { useEffect, useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import ipc from '../ipc.js';
import { useAccentColour, useEventListener } from '../util.js';
import type { StatusUpdate } from '../../../common/status.js';
import { BORDER_COLOUR_SECONDARY_DARK, TEXT_COLOUR_DARK, UPDATE_COLOUR } from '../constants.js';
import { Button } from '../components/index.js';
enum StatusUpdateFlag {
HIDDEN = 0,
}
export default function StatusUpdates() {
const accent_colour = useAccentColour();
const [status_updates, setStatusUpdateData] = useState<StatusUpdate[] | null>(null);
useEffect(() => (ipc.getStatusUpdateData().then(setStatusUpdateData), undefined), [ipc]);
useEventListener(ipc.events, 'status-updates', setStatusUpdateData, [ipc.events]);
return status_updates?.map(status_update => status_update.flags & (1 << StatusUpdateFlag.HIDDEN) ? null : <View style={[styles.container, status_update.colour ? {backgroundColor: status_update.colour} : null]}>
<Text style={styles.updateText}>{status_update.content}</Text>
{status_update.action ? <View style={styles.updateButton}>
<Button title={status_update.action.label}
onPress={() => ipc.openExternalUrl(status_update.action!.url)}
color={'#' + accent_colour} />
</View> : null}
</View>);
}
const styles = StyleSheet.create({
container: {
backgroundColor: UPDATE_COLOUR,
borderBottomWidth: 1,
borderBottomColor: BORDER_COLOUR_SECONDARY_DARK,
paddingVertical: 8,
paddingHorizontal: 20,
flexDirection: 'row',
alignItems: 'center',
},
updateText: {
marginVertical: 4,
flex: 1,
color: TEXT_COLOUR_DARK,
},
updateButton: {
marginLeft: 14,
},
});

View File

@ -1,44 +1,29 @@
import React, { useEffect, useMemo, useState } from 'react';
import React, { useEffect, useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { useTranslation } from 'react-i18next';
import ipc from '../ipc.js';
import { useAccentColour, useEventListener } from '../util.js';
import type { UpdateCacheData } from '../../../common/update.js';
import type { StatusUpdate } from '../../../common/status.js';
import { BORDER_COLOUR_SECONDARY_DARK, TEXT_COLOUR_DARK, UPDATE_COLOUR } from '../constants.js';
import { TEXT_COLOUR_DARK, UPDATE_COLOUR } from '../constants.js';
import { Button } from '../components/index.js';
enum StatusUpdateFlag {
SUPPRESS_UPDATE_BANNER = 1,
}
export default function Update() {
const accent_colour = useAccentColour();
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'update' });
const [update, setUpdateData] = useState<UpdateCacheData | null>(null);
useEffect(() => (ipc.getUpdateData().then(setUpdateData), undefined), [ipc]);
useEventListener(ipc.events, 'nxapi:update:latest', setUpdateData, [ipc.events]);
const [status_updates, setStatusUpdateData] = useState<StatusUpdate[] | null>(null);
useEffect(() => (ipc.getStatusUpdateData().then(setStatusUpdateData), undefined), [ipc]);
useEventListener(ipc.events, 'status-updates', setStatusUpdateData, [ipc.events]);
const status_update_suppress_update_banner = useMemo(() =>
status_updates?.find(s => s.flags & (1 << StatusUpdateFlag.SUPPRESS_UPDATE_BANNER)),
[status_updates]);
return update && 'update_available' in update && update.update_available && !status_update_suppress_update_banner ? <View style={styles.container}>
<Text style={styles.updateText}>{t('update_available', {name: update.latest.name})}</Text>
return update && 'update_available' in update && update.update_available ? <View style={styles.container}>
<Text style={styles.updateText}>Update available: {update.latest.name}</Text>
<View style={styles.updateButton}>
<Button title={t('download')}
<Button title="Download"
onPress={() => ipc.openExternalUrl(update.latest.html_url)}
color={'#' + accent_colour} />
</View>
</View> : update && 'error_message' in update ? <View style={styles.container}>
<Text style={styles.updateText}>{t('error', {message: update.error_message})}</Text>
<Text style={styles.updateText}>Error checking for updates: {update.error_message}</Text>
<View style={styles.updateButton}>
<Button title={t('retry')}
<Button title="Try again"
onPress={() => (setUpdateData(null), ipc.checkUpdates())}
color={'#' + accent_colour} />
</View>
@ -48,8 +33,6 @@ export default function Update() {
const styles = StyleSheet.create({
container: {
backgroundColor: UPDATE_COLOUR,
borderBottomWidth: 1,
borderBottomColor: BORDER_COLOUR_SECONDARY_DARK,
paddingVertical: 8,
paddingHorizontal: 20,
flexDirection: 'row',

View File

@ -1,6 +1,5 @@
import React from 'react';
import { Image, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { useTranslation } from 'react-i18next';
import ipc from '../ipc.js';
import { useColourScheme, User } from '../util.js';
import { WebService } from '../../../api/coral-types.js';
@ -8,18 +7,14 @@ import { TEXT_COLOUR_DARK, TEXT_COLOUR_LIGHT } from '../constants.js';
import Section from './section.js';
export default function WebServices(props: {
user: User<true>;
user: User;
webservices: WebService[];
loading?: boolean;
error?: Error;
}) {
const { t, i18n } = useTranslation('main_window', { keyPrefix: 'webservices_section' });
if (!props.webservices.length) return null;
return <Section title={t('title')} loading={props.loading} error={props.error}
errorKey={[props.user.nsotoken, 'webservices']}
>
return <Section title="Game-specific services" loading={props.loading} error={props.error}>
<ScrollView horizontal>
<View style={styles.content}>
{props.webservices.map(g => <WebService key={g.id} webservice={g} token={props.user.nsotoken} />)}

View File

@ -1,440 +0,0 @@
import React, { useCallback, useEffect, useReducer, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { CheckBox, Picker } from 'react-native-web';
import { DiscordPresencePlayTime } from '../../../discord/types.js';
import { Button } from '../components/index.js';
import { DEFAULT_ACCENT_COLOUR, HIGHLIGHT_COLOUR_DARK, HIGHLIGHT_COLOUR_LIGHT, TEXT_COLOUR_DARK, TEXT_COLOUR_LIGHT } from '../constants.js';
import ipc, { events } from '../ipc.js';
import { getAccounts, RequestState, Root, useAccentColour, useAsync, useColourScheme, useDiscordPresenceSource, useEventListener } from '../util.js';
export interface PreferencesProps {}
export default function PreferencesWindow(props: PreferencesProps) {
return <Root
title={i18n => i18n.t('preferences_window:title')} scrollable autoresize
i18nNamespace="preferences_window"
>
<Preferences />
</Root>;
}
function _Preferences(props: {
}) {
const theme = useColourScheme() === 'light' ? light : dark;
const accent_colour = useAccentColour();
const { t, i18n, ready } = useTranslation('preferences_window');
const [users, ,, forceRefreshAccounts] = useAsync(useCallback(() => getAccounts(), [ipc]));
useEventListener(events, 'update-nintendo-accounts', forceRefreshAccounts, []);
const [login_item, ,, forceRefreshLoginItem] = useAsync(useCallback(() => ipc.getLoginItemSettings(), [ipc]));
const [show_error_alerts, , show_error_alerts_state, forceRefreshErrorAlerts] = useAsync(useCallback(() => ipc.getShowErrorAlerts(), [ipc]));
const setOpenAtLogin = useCallback(async (open_at_login: boolean | 'mixed') => {
await ipc.setLoginItemSettings({...login_item!, startup_enabled: !!open_at_login});
forceRefreshLoginItem();
}, [ipc, login_item]);
const setOpenAsHidden = useCallback(async (open_as_hidden: boolean | 'mixed') => {
await ipc.setLoginItemSettings({...login_item!, startup_hidden: !!open_as_hidden});
forceRefreshLoginItem();
}, [ipc, login_item]);
const setShowErrorAlerts = useCallback(async (show_error_alerts: boolean | 'mixed') => {
await ipc.setShowErrorAlerts(!!show_error_alerts);
forceRefreshErrorAlerts();
}, [ipc]);
const [discord_users, discord_users_error, discord_users_state, forceRefreshDiscordUsers] =
useAsync(useCallback(() => ipc.getDiscordUsers(), [ipc]));
const [discord_options, , discord_options_state, forceRefreshDiscordOptions] =
useAsync(useCallback(() => ipc.getSavedDiscordPresenceOptions(), [ipc]));
const [has_ever_loaded_discord_options, setHasLoadedDiscordOptions] = useReducer(() => true, false);
useEffect(() => (discord_options_state === RequestState.LOADED && setHasLoadedDiscordOptions(), undefined));
const [discord_friend_code, setDiscordFriendCodeValue] = useState(discord_options?.friend_code ?? '');
const discord_friend_code_valid = !discord_friend_code || discord_friend_code.match(/^\d{4}-\d{4}-\d{4}$/);
useEffect(() => {
setDiscordFriendCodeValue(discord_options?.friend_code ?? '');
}, [discord_options]);
const setDiscordUser = useCallback(async (user: string | undefined) => {
if (user === '*') user = undefined;
await ipc.setDiscordPresenceOptions({...discord_options, user});
forceRefreshDiscordOptions();
}, [ipc, discord_options]);
const setDiscordFriendCode = useCallback(async (friend_code: string | undefined) => {
setDiscordFriendCodeValue(friend_code ?? '');
if (friend_code && !friend_code.match(/^\d{4}-\d{4}-\d{4}$/)) return;
if (!friend_code) friend_code = undefined;
await ipc.setDiscordPresenceOptions({...discord_options, friend_code});
forceRefreshDiscordOptions();
}, [ipc, discord_options]);
const setDiscordShowConsoleOnline = useCallback(async (show_console_online: boolean | 'mixed') => {
await ipc.setDiscordPresenceOptions({...discord_options, show_console_online: !!show_console_online});
forceRefreshDiscordOptions();
}, [ipc, discord_options]);
const setDiscordShowPlayTime = useCallback(async (show_play_time: DiscordPresencePlayTime) => {
await ipc.setDiscordPresenceOptions({...discord_options, show_play_time});
forceRefreshDiscordOptions();
}, [ipc, discord_options]);
const setDiscordEnableSplatNet3Monitor = useCallback(async (enable_splatnet3_monitoring: boolean | 'mixed') => {
await ipc.setDiscordPresenceOptions({...discord_options, monitors: {...discord_options?.monitors,
enable_splatnet3_monitoring: !!enable_splatnet3_monitoring}});
forceRefreshDiscordOptions();
}, [ipc, discord_options]);
const [discord_presence_source, discord_presence_source_state] = useDiscordPresenceSource();
const discord_presence_source_user = discord_presence_source && 'na_id' in discord_presence_source ?
discord_presence_source.friend_nsa_id ?
users?.find(u => u.nso?.nsoAccount.user.nsaId === discord_presence_source.friend_nsa_id)?.nso :
users?.find(u => u.nso?.user.id === discord_presence_source.na_id)?.nso :
null;
const discord_friend_code_self = discord_presence_source_user?.nsoAccount.user.links.friendCode.id;
const [is_discord_friend_code_self, setIsDiscordFriendCodeSelf] = useState(false);
useEffect(() => {
setIsDiscordFriendCodeSelf(!!discord_friend_code_self &&
(!discord_friend_code || discord_friend_code === discord_friend_code_self));
}, [discord_presence_source, discord_friend_code_self]);
useEventListener(events, 'window:refresh', () => (
forceRefreshAccounts(), forceRefreshLoginItem(),
forceRefreshDiscordUsers(), forceRefreshDiscordOptions(),
forceRefreshErrorAlerts()
), []);
if (!users ||
!login_item ||
!has_ever_loaded_discord_options ||
discord_presence_source_state !== RequestState.LOADED ||
!ready
) {
return null;
}
const discord_user_picker = [<Picker.Item key="*" label={t('discord.user_any')!} value="*" />];
if (discord_options?.user && !discord_users?.find(u => u.id === discord_options.user)) {
discord_user_picker.push(<Picker.Item key={discord_options?.user} label={discord_options.user}
value={discord_options.user} />);
}
for (const user of discord_users ?? []) {
discord_user_picker.push(<Picker.Item key={user.id}
label={user.username + (user.discriminator && user.discriminator !== '0' ? '#' + user.discriminator : '')}
value={user.id} />);
}
return <View style={styles.main}>
{/* <Text style={theme.text}>Preferences</Text> */}
{login_item.supported || login_item.startup_enabled ? <View style={styles.section}>
<View style={styles.sectionLeft}>
<Text style={[styles.label, theme.text]}>{t('startup.heading')}</Text>
</View>
<View style={styles.sectionRight}>
<View style={styles.checkboxContainer}>
<CheckBox
value={login_item.startup_enabled}
onValueChange={setOpenAtLogin}
disabled={!login_item.supported}
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}
style={styles.checkbox}
/>
<TouchableOpacity disabled={!login_item.supported} style={styles.checkboxLabel} onPress={() => setOpenAtLogin(!login_item.startup_enabled)}>
<Text style={[styles.checkboxLabelText, theme.text]}>{t('startup.login')}</Text>
</TouchableOpacity>
</View>
<View
style={[styles.checkboxContainer, !login_item.startup_enabled ? styles.disabled : null]}
>
<CheckBox
value={login_item.startup_hidden}
onValueChange={setOpenAsHidden}
disabled={!login_item.startup_enabled}
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}
style={styles.checkbox}
/>
<TouchableOpacity disabled={!login_item.startup_enabled} style={styles.checkboxLabel}
onPress={() => setOpenAsHidden(!login_item.startup_hidden)}
>
<Text style={[styles.checkboxLabelText, theme.text]}>{t('startup.background')}</Text>
</TouchableOpacity>
</View>
</View>
</View> : null}
{/* <View style={styles.section}>
<View style={styles.sectionLeft}>
<Text style={[styles.label, theme.text]}>Sleep</Text>
</View>
<View style={styles.sectionRight}>
<Text style={theme.text}>Prevent sleep menu here</Text>
</View>
</View> */}
<View style={styles.section}>
<View style={styles.sectionLeft}>
<Text style={[styles.label, theme.text]}>{t('discord.heading')}</Text>
</View>
<View style={styles.sectionRight}>
<Text style={theme.text}>{t(discord_presence_source ? 'discord.enabled' : 'discord.disabled')}</Text>
<View style={styles.button}>
<Button title={t('discord.setup')}
onPress={() => ipc.showDiscordModal({show_preferences_button: false})}
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)} />
</View>
<Text style={[styles.header, theme.text]}>{t('discord.user')}</Text>
<Picker<string> selectedValue={discord_options?.user ?? '*'} onValueChange={setDiscordUser}
style={[styles.picker, theme.picker]}
enabled={discord_options_state !== RequestState.LOADING &&
discord_users_state !== RequestState.LOADING}
>{...discord_user_picker}</Picker>
<Text style={[styles.header, theme.text]}>{t('discord.friend_code')}</Text>
<Text style={[styles.help, theme.text]}>{t('discord.friend_code_help')}</Text>
{is_discord_friend_code_self ? <View style={styles.friendCodeCheckbox}>
<View style={styles.checkboxContainer}>
<CheckBox
value={!!discord_options?.friend_code}
onValueChange={v => setDiscordFriendCode(v ? discord_friend_code_self : undefined)}
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}
style={styles.checkbox}
/>
<TouchableOpacity style={styles.checkboxLabel} onPress={() => setDiscordFriendCode(discord_options?.friend_code ? undefined : discord_friend_code_self)}>
<Text style={theme.text}>{t('discord.friend_code_self')}</Text>
</TouchableOpacity>
</View>
<TouchableOpacity style={styles.textLinkTouchable} onPress={() => setIsDiscordFriendCodeSelf(false)}>
<Text style={[styles.textLink, theme.text, {color: '#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}]}>
{t('discord.friend_code_custom')}
</Text>
</TouchableOpacity>
</View> : <View style={styles.friendCodeInput}>
<TextInput value={discord_friend_code} onChangeText={setDiscordFriendCode}
placeholder="0000-0000-0000"
style={[styles.textInput, theme.textInput]} />
</View>}
<View style={[styles.checkboxContainer, styles.checkboxContainerMargin]}>
<CheckBox
value={discord_options?.show_console_online ?? false}
onValueChange={setDiscordShowConsoleOnline}
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}
style={styles.checkbox}
/>
<TouchableOpacity style={styles.checkboxLabel} onPress={() => setDiscordShowConsoleOnline(!discord_options?.show_console_online)}>
<Text style={[styles.checkboxLabelText, theme.text]}>{t('discord.inactive_presence')}</Text>
</TouchableOpacity>
</View>
<Text style={[styles.help, theme.text]}>{t('discord.inactive_presence_help')}</Text>
<Text style={[styles.header, theme.text]}>{t('discord.play_time')}</Text>
<Picker<string>
selectedValue={'' + (discord_options?.show_play_time ??
DiscordPresencePlayTime.DETAILED_PLAY_TIME_SINCE)}
onValueChange={v => setDiscordShowPlayTime(parseInt(v))}
style={[styles.picker, theme.picker]}
enabled={discord_options_state !== RequestState.LOADING}
>
<Picker.Item key={DiscordPresencePlayTime.HIDDEN} value={DiscordPresencePlayTime.HIDDEN}
label={t('discord.play_time_hidden')!} />
<Picker.Item key={DiscordPresencePlayTime.NINTENDO} value={DiscordPresencePlayTime.NINTENDO}
label={t('discord.play_time_nintendo')!} />
<Picker.Item key={DiscordPresencePlayTime.APPROXIMATE_PLAY_TIME} value={DiscordPresencePlayTime.APPROXIMATE_PLAY_TIME}
label={t('discord.play_time_approximate_play_time')!} />
<Picker.Item key={DiscordPresencePlayTime.APPROXIMATE_PLAY_TIME_SINCE} value={DiscordPresencePlayTime.APPROXIMATE_PLAY_TIME_SINCE}
label={t('discord.play_time_approximate_play_time_since')!} />
<Picker.Item key={DiscordPresencePlayTime.HOUR_PLAY_TIME} value={DiscordPresencePlayTime.HOUR_PLAY_TIME}
label={t('discord.play_time_hour_play_time')!} />
<Picker.Item key={DiscordPresencePlayTime.HOUR_PLAY_TIME_SINCE} value={DiscordPresencePlayTime.HOUR_PLAY_TIME_SINCE}
label={t('discord.play_time_hour_play_time_since')!} />
<Picker.Item key={DiscordPresencePlayTime.DETAILED_PLAY_TIME} value={DiscordPresencePlayTime.DETAILED_PLAY_TIME}
label={t('discord.play_time_detailed_play_time')!} />
<Picker.Item key={DiscordPresencePlayTime.DETAILED_PLAY_TIME_SINCE} value={DiscordPresencePlayTime.DETAILED_PLAY_TIME_SINCE}
label={t('discord.play_time_detailed_play_time_since')!} />
</Picker>
</View>
</View>
<View style={styles.section}>
<View style={styles.sectionLeft}>
<Text style={[styles.label, theme.text]}>{t('splatnet3.heading')}</Text>
</View>
<View style={styles.sectionRight}>
<View style={[styles.checkboxContainer]}>
<CheckBox
value={discord_options?.monitors?.enable_splatnet3_monitoring ?? false}
onValueChange={setDiscordEnableSplatNet3Monitor}
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}
style={styles.checkbox}
/>
<TouchableOpacity style={styles.checkboxLabel} onPress={() => setDiscordEnableSplatNet3Monitor(!discord_options?.monitors?.enable_splatnet3_monitoring)}>
<Text style={[styles.checkboxLabelText, theme.text]}>{t('splatnet3.discord')}</Text>
</TouchableOpacity>
</View>
<Text style={[styles.help, theme.text]}>{t('splatnet3.discord_help_1')}</Text>
<Text style={[styles.help, theme.text]}>{t('splatnet3.discord_help_2')}</Text>
</View>
</View>
<View style={styles.section}>
<View style={styles.sectionLeft}>
<Text style={[styles.label, theme.text]}>{t('miscellaneous.heading')}</Text>
</View>
<View style={styles.sectionRight}>
<View style={[styles.checkboxContainer]}>
<CheckBox
value={show_error_alerts ?? true}
onValueChange={setShowErrorAlerts}
color={'#' + (accent_colour ?? DEFAULT_ACCENT_COLOUR)}
style={styles.checkbox}
/>
<TouchableOpacity style={styles.checkboxLabel} onPress={() => setShowErrorAlerts(!(show_error_alerts ?? true))}>
<Text style={[styles.checkboxLabelText, theme.text]}>{t('miscellaneous.show_error_alerts')}</Text>
</TouchableOpacity>
</View>
<Text style={[styles.help, theme.text]}>{t('miscellaneous.show_error_alerts_help')}</Text>
</View>
</View>
</View>;
}
const Preferences = React.memo(_Preferences);
const styles = StyleSheet.create({
loading: {
flex: 1,
paddingVertical: 50,
paddingHorizontal: 20,
justifyContent: 'center',
},
main: {
flex: 1,
paddingVertical: 20,
paddingHorizontal: 35,
},
section: {
marginBottom: 15,
flexDirection: 'row',
},
sectionLeft: {
width: '30%',
marginRight: 30,
},
label: {
textAlign: 'right',
},
sectionRight: {
flex: 1,
},
header: {
marginTop: 12,
},
help: {
marginTop: 8,
fontSize: 13,
opacity: 0.7,
},
textLinkTouchable: {
marginBottom: 8,
},
textLink: {
fontSize: 13,
opacity: 0.85,
},
picker: {
marginTop: 8,
paddingVertical: 4,
paddingHorizontal: 8,
borderWidth: 0,
borderRadius: 3,
fontSize: 13,
},
textInput: {
marginTop: 8,
paddingVertical: 5,
paddingHorizontal: 10,
borderRadius: 3,
fontSize: 13,
},
checkboxContainer: {
marginBottom: 8,
flex: 1,
flexBasis: 'auto',
flexDirection: 'row',
alignItems: 'center',
},
checkboxContainerMargin: {
marginTop: 8,
marginBottom: 0,
},
checkbox: {
marginRight: 10,
},
checkboxLabel: {
flex: 1,
},
checkboxLabelText: {
},
disabled: {
opacity: 0.8,
},
friendCodeCheckbox: {
marginTop: 8,
},
friendCodeInput: {
marginBottom: 4,
},
button: {
marginTop: 10,
marginRight: 10,
flexDirection: 'row',
},
});
const light = StyleSheet.create({
text: {
color: TEXT_COLOUR_LIGHT,
},
picker: {
backgroundColor: HIGHLIGHT_COLOUR_LIGHT,
color: TEXT_COLOUR_LIGHT,
},
textInput: {
backgroundColor: HIGHLIGHT_COLOUR_LIGHT,
color: TEXT_COLOUR_LIGHT,
},
});
const dark = StyleSheet.create({
text: {
color: TEXT_COLOUR_DARK,
},
picker: {
backgroundColor: HIGHLIGHT_COLOUR_DARK,
color: TEXT_COLOUR_DARK,
},
textInput: {
backgroundColor: HIGHLIGHT_COLOUR_DARK,
color: TEXT_COLOUR_DARK,
},
});

View File

@ -87,7 +87,3 @@ declare module 'react-native-web' {
type Item<T = number | string> = PickerItem<T>;
}
}
declare module 'node:timers' {
function setTimeout(callback: (_: void) => void, delay?: number): NodeJS.Timeout;
}

View File

@ -1,29 +1,24 @@
import { EventEmitter } from 'node:events';
import React, { useCallback, useEffect, useLayoutEffect, useMemo, useState } from 'react';
import React, { useCallback, useEffect, useLayoutEffect, useState } from 'react';
import { ColorSchemeName, LayoutChangeEvent, Platform, StyleProp, StyleSheet, useColorScheme, View, ViewStyle } from 'react-native';
import { i18n, TFunction } from 'i18next';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import type { User as DiscordUser } from 'discord-rpc';
import { NintendoAccountUserCoral } from '../../api/coral.js';
import { NintendoAccountUserMoon } from '../../api/moon.js';
import { ErrorResponse } from '../../api/util.js';
import { DiscordPresence } from '../../discord/util.js';
import ipc, { events } from './ipc.js';
import { NintendoAccountUser } from '../../api/na.js';
import { SavedToken } from '../../common/auth/coral.js';
import { SavedMoonToken } from '../../common/auth/moon.js';
import { DiscordPresence } from '../../discord/types.js';
import ipc, { events } from './ipc.js';
import { BACKGROUND_COLOUR_MAIN_DARK, BACKGROUND_COLOUR_MAIN_LIGHT, DEFAULT_ACCENT_COLOUR } from './constants.js';
import createI18n from '../i18n/index.js';
export const WindowFocusedContext = React.createContext(false);
export function Root(props: React.PropsWithChildren<{
title?: string | ((i18n: i18n) => string);
title?: string;
titleUser?: User | SavedToken;
style?: StyleProp<ViewStyle>;
scrollable?: boolean;
autoresize?: boolean;
vibrancy?: boolean;
i18nNamespace?: string | string[];
}>) {
const colour_scheme = useColorScheme();
const theme = colour_scheme === 'light' ? light : dark;
@ -31,49 +26,34 @@ export function Root(props: React.PropsWithChildren<{
const [accent_colour, setAccentColour] = React.useState(() => ipc.getAccentColour());
useEventListener(events, 'systemPreferences:accent-colour', setAccentColour, []);
const [window_focused, setWindowFocused] = useState(ipc.getWindowFocused());
useEventListener(events, 'window:focused', setWindowFocused, []);
const [window_focused, setWindowFocus] = useState(true);
const [i18n, i18n_error] = useAsync(useCallback(async () => {
const i18n = createI18n();
// @ts-expect-error
window.i18n = i18n;
i18n.use(initReactI18next);
await i18n.init({
lng: ipc.getLanguage(),
});
await i18n.loadNamespaces('app');
if (props.i18nNamespace) await i18n.loadNamespaces(props.i18nNamespace);
return i18n;
}, []));
if (i18n_error) throw i18n_error;
useEventListener(events, 'update-language', language => i18n?.changeLanguage(language), [i18n]);
// Force rerender when language changes so the window title is updated
const [language, setCurrentLanguage] = useState();
useEffect(() => {
i18n?.on('languageChanged', setCurrentLanguage);
return () => i18n?.off('languageChanged', setCurrentLanguage);
}, [i18n]);
const handler = (event: FocusEvent) => setWindowFocus(event.type === 'focus');
window.addEventListener('focus', handler);
window.addEventListener('blur', handler);
return () => {
window.removeEventListener('focus', handler);
window.removeEventListener('blur', handler);
};
}, []);
useAsync(useCallback(async () => i18n?.loadNamespaces('app'), [i18n, language]));
useAsync(useCallback(async () => props.i18nNamespace && i18n?.loadNamespaces(props.i18nNamespace),
[i18n, props.i18nNamespace, language]));
useEffect(() => {
const user_na = props.titleUser?.user;
const user_nso = (props.titleUser && 'nso' in props.titleUser ? props.titleUser.nso : props.titleUser)?.nsoAccount.user;
const user_prefix =
user_na ? '[' + user_na.nickname +
(user_nso && user_nso.name !== user_na.nickname ? '/' + user_nso.name : '') +
'] ' : '';
document.title = user_prefix + (props.title ?? 'Nintendo Switch Online');
}, [props.title, props.titleUser]);
const [preventingFocus, setPreventFocus] = useState(true);
const unlockFocus = useCallback(() => setPreventFocus(false), []);
useLayoutEffect(() => setPreventFocus(props.autoresize ?? true), [props.autoresize]);
const onLayout = useCallback(async (event: LayoutChangeEvent) => {
if (!event.nativeEvent.layout.height) return;
await ipc.setWindowHeight(event.nativeEvent.layout.height);
setPreventFocus(false);
}, []);
@ -82,17 +62,6 @@ export function Root(props: React.PropsWithChildren<{
document.documentElement.style.overflowY = props.scrollable ? 'auto' : 'hidden';
}, [props.scrollable]);
const title_user_prefix = useMemo(() => {
const user_na = props.titleUser?.user;
const user_nso = (props.titleUser && 'nso' in props.titleUser ? props.titleUser.nso : props.titleUser)?.nsoAccount.user;
return user_na ? '[' + user_na.nickname +
(user_nso && user_nso.name !== user_na.nickname ? '/' + user_nso.name : '') +
'] ' : '';
}, [props.titleUser]);
if (!i18n) return null;
const content = <View style={[
props.scrollable ? styles.appScrollable : styles.app,
!props.vibrancy ? theme.appNoVibrancy : null,
@ -114,35 +83,17 @@ export function Root(props: React.PropsWithChildren<{
return <ColourSchemeContext.Provider value={colour_scheme}>
<AccentColourContext.Provider value={accent_colour ?? DEFAULT_ACCENT_COLOUR}>
<WindowFocusedContext.Provider value={window_focused}>
<I18nextProvider i18n={i18n}>
<WindowTitle title={title_user_prefix + (
typeof props.title === 'function' ? props.title.call(null, i18n) :
props.title ?? i18n.t('app:default_title'))} />
{content}
</I18nextProvider>
{content}
</WindowFocusedContext.Provider>
</AccentColourContext.Provider>
</ColourSchemeContext.Provider>;
}
function WindowTitle(props: {
title: string;
}) {
useEffect(() => {
document.title = props.title;
}, [props.title]);
return null;
}
const styles = StyleSheet.create({
app: {
// @ts-expect-error vh unit only supported on web
height: Platform.OS === 'web' ? '100vh' : '100%',
},
appScrollable: {
// @ts-expect-error vh unit only supported on web
minHeight: Platform.OS === 'web' ? '100vh' : '100%',
},
});
@ -243,19 +194,10 @@ export function useColourScheme() {
return React.useContext(ColourSchemeContext);
}
export interface User<IsCoral extends boolean = boolean> {
user:
IsCoral extends true ? NintendoAccountUserCoral :
IsCoral extends false ? NintendoAccountUserMoon :
NintendoAccountUserCoral | NintendoAccountUserMoon;
nso:
IsCoral extends true ? SavedToken :
IsCoral extends false ? null :
SavedToken | null;
nsotoken:
IsCoral extends true ? string :
IsCoral extends false ? null :
string | null;
export interface User {
user: NintendoAccountUser;
nso: SavedToken | null;
nsotoken: string | undefined;
moon: SavedMoonToken | null;
moontoken: string | undefined;
}
@ -266,10 +208,10 @@ export async function getAccounts() {
const accounts: User[] = [];
for (const id of ids ?? []) {
const nsotoken = await ipc.getNintendoAccountCoralToken(id) ?? null;
const nsotoken = await ipc.getNintendoAccountNsoToken(id);
const moontoken = await ipc.getNintendoAccountMoonToken(id);
const nso = nsotoken ? await ipc.getSavedCoralToken(nsotoken) ?? null : null;
const nso = nsotoken ? await ipc.getSavedNsoToken(nsotoken) ?? null : null;
const moon = moontoken ? await ipc.getSavedMoonToken(moontoken) ?? null : null;
if (!nso && !moon) continue;
@ -307,61 +249,3 @@ export function useActiveDiscordUser() {
return user;
}
export function useTimeSince(time: Date, short = false, t?: TFunction) {
const [now, setNow] = useState(Date.now());
const [since, update_in] = getTimeSince(time, now, short ? short_time_since_intervals : time_since_intervals, t);
const update_at = Date.now() + update_in;
useEffect(() => {
const timeout = setTimeout(() => setNow(Date.now()), Math.max(1000, update_at - Date.now()));
return () => clearTimeout(timeout);
}, [time, short, update_at]);
return since;
}
interface TimeSinceInterval {
interval: number;
max: number;
string: (count: number) => string;
key?: string;
}
const time_since_intervals: TimeSinceInterval[] = [
{interval: 1000, max: 10, string: () => 'just now', key: 'default.now'},
{interval: 1000, max: 60, string: c => c + ' second' + (c === 1 ? '' : 's') + ' ago', key: 'default.seconds'},
{interval: 60 * 1000, max: 60, string: c => c + ' minute' + (c === 1 ? '' : 's') + ' ago', key: 'default.minutes'},
{interval: 60 * 60 * 1000, max: 24, string: c => c + ' hour' + (c === 1 ? '' : 's') + ' ago', key: 'default.hours'},
{interval: 24 * 60 * 60 * 1000, max: Infinity, string: c => c + ' day' + (c === 1 ? '' : 's') + ' ago', key: 'default.days'},
];
const short_time_since_intervals: TimeSinceInterval[] = [
{interval: 1000, max: 10, string: () => 'Just now', key: 'default.now'},
{interval: 1000, max: 60, string: c => c + ' sec' + (c === 1 ? '' : 's'), key: 'short.seconds'},
{interval: 60 * 1000, max: 60, string: c => c + ' min' + (c === 1 ? '' : 's'), key: 'short.minutes'},
{interval: 60 * 60 * 1000, max: 24, string: c => c + ' hr' + (c === 1 ? '' : 's'), key: 'short.hours'},
{interval: 24 * 60 * 60 * 1000, max: Infinity, string: c => c + ' day' + (c === 1 ? '' : 's'), key: 'short.days'},
];
function getTimeSince(
time: Date | number, now = Date.now(),
intervals = time_since_intervals, t?: TFunction,
): [string, number] {
if (time instanceof Date) time = time.getTime();
const elapsed = Math.max(0, now - time);
const last = intervals[time_since_intervals.length - 1];
for (const i of intervals) {
if (elapsed < i.max * i.interval || last === i) {
const count = Math.floor(elapsed / i.interval);
return [
(t && i.key ? t(i.key, {count, defaultValue: ''}) : '') || i.string.call(null, count),
i.interval - (elapsed - (count * i.interval)),
];
}
}
throw new Error('Invalid intervals');
}

View File

@ -1,21 +1,15 @@
import { DiscordPresencePlayTime } from '../../discord/types.js';
import { DiscordPresencePlayTime } from '../../discord/util.js';
export enum WindowType {
MAIN_WINDOW = 'App',
FRIEND = 'Friend',
DISCORD_PRESENCE = 'DiscordPresence',
ADD_FRIEND = 'AddFriend',
PREFERENCES = 'Preferences',
ADD_ACCOUNT_MANUAL_PROMPT = 'AddAccountManualPrompt',
}
interface WindowProps {
[WindowType.MAIN_WINDOW]: import('../browser/main/index.js').AppProps;
[WindowType.FRIEND]: import('../browser/friend/index.js').FriendProps;
[WindowType.DISCORD_PRESENCE]: import('../browser/discord/index.js').DiscordSetupProps;
[WindowType.ADD_FRIEND]: import('../browser/add-friend/index.js').AddFriendProps;
[WindowType.PREFERENCES]: import('../browser/preferences/index.js').PreferencesProps;
[WindowType.ADD_ACCOUNT_MANUAL_PROMPT]: import('../browser/add-account-manual/index.js').AddAccountManualPromptProps;
}
export interface WindowConfiguration<T extends WindowType = WindowType> {
@ -32,7 +26,6 @@ export interface DiscordPresenceConfiguration {
show_console_online?: boolean;
show_active_event?: boolean;
show_play_time?: DiscordPresencePlayTime;
monitors?: DiscordPresenceExternalMonitorsConfiguration;
}
export type DiscordPresenceSource = DiscordPresenceSourceCoral | DiscordPresenceSourceUrl;
@ -43,18 +36,3 @@ export interface DiscordPresenceSourceCoral {
export interface DiscordPresenceSourceUrl {
url: string;
}
export interface DiscordPresenceExternalMonitorsConfiguration {
enable_splatnet3_monitoring?: boolean;
}
export interface DiscordStatus {
error_message: string | null;
}
export interface LoginItem {
supported: boolean;
startup_enabled: boolean;
startup_hidden: boolean;
}
export type LoginItemOptions = Omit<LoginItem, 'supported'>;

View File

@ -1,104 +0,0 @@
import createDebug from 'debug';
import { BackendModule, CallbackError, createInstance, ReadCallback } from 'i18next';
const debug = createDebug('app:i18n');
import './locale/en-gb.js';
export const languages = {
'en-GB': {
name: 'English',
app: () => import('./locale/en-gb.js'),
authors: [
['Ellie', 'https://gitlab.fancy.org.uk/ellie'],
],
},
'de-DE': {
name: 'Deutsch',
app: () => import('./locale/de-de.js'),
authors: [
['Inkception', 'https://github.com/Inkception'],
],
},
'es-ES': {
name: 'Español',
app: () => import('./locale/es-es.js'),
authors: [
['sarayalth', 'https://github.com/sarayalth'],
],
},
'ja-JP': {
name: 'Japanese',
app: () => import('./locale/ja-jp.js'),
authors: [
['hilot06', 'https://github.com/hilot06'],
],
},
};
const namespaces = {
app: 'app',
app_menu: 'app',
menu_app: 'app',
menus: 'app',
notifications: 'app',
handle_uri: 'app',
main_window: 'app',
preferences_window: 'app',
friend_window: 'app',
addfriend_window: 'app',
discordsetup_window: 'app',
addaccountmanual_window: 'app',
} as const;
type Namespace = keyof typeof namespaces;
export default function createI18n() {
const i18n = createInstance({
fallbackLng: 'en-GB',
debug: true,
supportedLngs: Object.keys(languages),
load: 'currentOnly',
returnNull: false,
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
},
react: {
useSuspense: false,
},
});
i18n.use(LanguageBackend);
return i18n;
}
const LanguageBackend: BackendModule = {
type: 'backend',
read: (
language: keyof typeof languages,
namespace: Namespace,
callback: ReadCallback,
) => {
debug('Loading %s translations for %s', namespace, language);
importLocale(language, namespaces[namespace]).then(resources => {
callback(null, resources[namespace as keyof typeof resources]);
}, (error: CallbackError) => {
callback(error, null);
});
},
init: null as any,
};
async function importLocale(
language: keyof typeof languages,
chunk: typeof namespaces[keyof typeof namespaces] = 'app',
) {
if (!(language in languages)) throw new Error('Unknown language ' + language);
return languages[language][chunk]();
}

View File

@ -1,386 +0,0 @@
import { CREDITS_NOTICE, LICENCE_NOTICE } from '../../../common/constants.js';
export const app = {
default_title: 'Nintendo Switch Online',
licence: LICENCE_NOTICE,
credits: CREDITS_NOTICE,
translation_credits: '{{language}} Übersetzungen von {{authors, list}}.',
};
export const app_menu = {
preferences: 'Einstellungen',
view: 'Anschauen',
learn_more: 'Mehr erfahren',
learn_more_github: 'Mehr erfahren (GitHub)',
search_issues: 'Probleme untersuchen',
refresh: 'Aktualisieren',
};
export const menu_app = {
coral_heading: 'Nintendo Switch Online',
na_id: 'Nintendo Account ID: {{id}}',
coral_id: 'Coral ID: {{id}}',
nsa_id: 'NSA ID: {{id}}',
discord_presence_enable: 'Discord Rich Presence aktivieren',
user_notifications_enable: 'Aktiviere Benachrichtigungen für diesen User',
friend_notifications_enable: 'Aktiviere Benachrichtigungen für Freunde von diesen User',
refresh: 'Jetzt aktualisieren',
add_friend: 'Freund hinzufügen',
web_services: 'Web-Services',
moon_heading: 'Nintendo Switch-Altersbeschränkungen',
add_account: 'Account hinzufügen',
show_main_window: 'Zeige Hauptfenster',
preferences: 'Einstellungen',
quit: 'Beenden',
};
export const menus = {
add_account: {
add_account_coral: 'Nintendo Switch Online Account hinzufügen',
add_account_moon: 'Altersbeschränkter Nintendo Switch Account hinzufügen',
},
friend_code: {
share: 'Teilen',
copy: 'Kopieren',
friend_code_regenerable: 'Regeneriere durch Nintendo Switch Konsole',
friend_code_regenerable_at: 'Kann {{date, datetime}} neu generiert werden',
},
user: {
na_id: 'Nintendo Account ID: {{id}}',
coral_id: 'Coral ID: {{id}}',
nsa_id: 'NSA ID: {{id}}',
discord_disable: 'Deaktiviere Discord Rich Presence',
discord_enabled_for: 'Discord Rich Presence für {{name}} aktiviert',
discord_enabled_via: 'Discord Rich Presence durch {{name}} aktiviert',
discord_enable: 'Aktiviere Discord Rich Presence für diesen User...',
friend_notifications_enable: 'Aktiviere Freund-Benachrichtigungen',
refresh: 'Jetzt aktualisieren',
add_friend: 'Freund hinzufügen',
remove_help: 'Benutze den nxapi Befehl, um diesen User zu entfernen',
},
friend: {
presence_online: 'Online',
presence_online_nx: 'Online (Nintendo Switch)',
presence_online_ounce: 'Online (Nintendo Switch 2)',
game_first_played: 'Zuerst gespielt: {{date, datetime}}',
game_play_time_h: 'Spielzeit: $t(friend.hours, {"count": {{hours}}})',
game_play_time_hm: 'Spielzeit: $t(friend.hours, {"count": {{hours}}}), $t(friend.minutes, {"count": {{minutes}}})',
game_play_time_m: 'Spielzeit: $t(friend.minutes, {"count": {{minutes}}})',
hours_one: '{{count}} Stunde',
hours_other: '{{count}} Stunden',
minutes_one: '{{count}} Minute',
minutes_other: '{{count}} Minuten',
presence_inactive: 'Offline (Konsole online)',
presence_offline: 'Offline',
presence_updated: 'Aktualisiert: {{date, datetime}}',
presence_logout_time: 'Ausgeloggt: {{date, datetime}}',
discord_presence_enable: 'Aktiviere Discord Rich Presence',
},
};
export const notifications = {
playing: 'Spielt {{name}}',
offline: 'Offline',
};
export const handle_uri = {
friend_code_select: 'Wähle einen User aus, um Freunde hinzuzufügen',
web_service_select: 'Wähle einen User aus, um diesen Service zu öffnen',
web_service_invalid_title: 'Unbekannter Titel',
web_service_invalid_detail: 'Die angegebene URL verwies nicht auf einen existierenden Web-Service.',
cancel: 'Abbrechen',
};
export const na_auth = {
window: {
title: 'Nintendo Account',
},
znca_api_use: {
title: 'Verwendung einer Drittanbieter-API',
ok: 'OK',
cancel: 'Abbrechen',
more_information: 'Weitere Informationen',
},
notification_coral: {
title: 'Nintendo Switch Online',
body_existing: 'Bereits als {{name}} (Nintendo Account {{na_name}} / {{na_username}}) eingeloggt',
body_authenticated: 'Authentifiziert als {{name}} (Nintendo Account {{na_name}} / {{na_username}})',
body_reauthenticated: 'Erneut als {{name}} (Nintendo Account {{na_name}} / {{na_username}}) authentifiziert',
},
notification_moon: {
title: 'Nintendo Switch-Altersbeschränkungen',
body_existing: 'Bereits als {{na_name}} ({{na_username}}) eingeloggt',
body_authenticated: 'Authentifiziert als {{na_name}} ({{na_username}})',
body_reauthenticated: 'Erneut als {{na_name}} ({{na_username}}) authentifiziert',
},
error: {
title: 'Fehler beim Hinzufügen des Accounts',
},
};
export const time_since = {
default: {
now: 'jetzt',
seconds_one: 'Vor {{count}} Sekunde',
seconds_other: 'Vor {{count}} Sekunden',
minutes_one: 'Vor {{count}} Minute',
minutes_other: 'Vor {{count}} Minuten',
hours_one: 'Vor {{count}} Stunde',
hours_other: 'Vor {{count}} Stunden',
days_one: 'Vor {{count}} Tag',
days_other: 'Vor {{count}} Tagen',
},
short: {
now: 'jetzt',
seconds_one: '{{count}} Sek',
seconds_other: '{{count}} Sek',
minutes_one: '{{count}} Min',
minutes_other: '{{count}} Min',
hours_one: '{{count}} Std',
hours_other: '{{count}} Std',
days_one: '{{count}} Tg',
days_other: '{{count}} Tg',
},
};
export const main_window = {
sidebar: {
discord_active: 'Discord Rich Presence aktiv',
discord_active_friend: 'Discord Rich Presence aktiv: <0></0>',
discord_not_active: 'Discord Rich Presence nicht aktiv',
discord_playing: 'Spielt',
discord_not_connected: 'Nicht mit Discord verbunden',
add_user: 'User hinzufügen',
discord_setup: 'Discord Rich Presence einrichten',
},
update: {
update_available: 'Update verfügbar: {{name}}',
download: 'Download',
error: 'Fehler beim Überprüfen von Updates aufgetreten: {{message}}',
retry: 'Erneut versuchen',
},
main_section: {
error: {
title: 'Fehler beim Laden der Daten',
message: 'Ein Fehler ist beim Laden der {{errors, list}} Daten aufgetreten.',
message_friends: 'freunde',
message_webservices: 'spielspezifische services',
message_event: 'sprachchat',
retry: 'Erneut versuchen',
view_details: 'Details anschauen',
},
moon_only_user: {
title: 'Nintendo Switch Online',
desc_1: 'Dieser User ist mit der Nintendo Switch-Altersbeschränkungen App angemeldet, aber nicht mit der Nintendo Switch Online App.',
desc_2: 'Logge dich mit der Nintendo Switch Online App ein, um Details einzusehen oder benutze den nxapi Befehl, um auf Altersbeschränkungen zuzugreifen.',
login: 'Login',
},
section_error: 'Fehler beim Aktualisieren der Daten',
},
discord_section: {
title: 'Discord Rich Presence',
setup_with_existing_user: 'Benutze einer dieser Account, um die Discord Rich Presence einzurichten: <0></0>.',
add_user: 'Füge einen Nintendo Switch Online Account mit diesem User als Freund hinzu, um die Discord Rich Presence einzurichten.',
active_self: 'Die Aktivität wird mit diesem User auf Discord geteilt.',
active_friend: '<0></0>\'s Aktivität wird mit diesem Account auf Discord geteilt.',
active_unknown: 'Die Aktivität eines unbekannten Users wird mit Discord geteilt.',
active_via: 'Die Aktivität wird mit diesem User auf Discord über <0></0> geteilt.',
setup: 'Einrichten',
disable: 'Deaktivieren',
},
friends_section: {
title: 'Freunde',
no_friends: 'Füge Freunde mit deiner Nintendo Switch Konsole hinzu.',
friend_code: 'Dein Freundescode: <0></0>',
presence_playing: 'Spielt',
presence_offline: 'Offline',
},
webservices_section: {
title: 'Spielspezifische Services',
},
event_section: {
title: 'Sprachchat',
members: '{{event}} im Spiel, {{voip}} im Sprachchat',
members_with_total: '{{event}} im Spiel, {{voip}} von {{total}} im Sprachkanal',
app_start: 'Benutze die Nintendo Switch Online App auf iOS oder Android, um einen Sprachchat zu starten.',
app_join: 'Benutze die Nintendo Switch Online App auf iOS oder Android, um einem Sprachchat beizutreten.',
share: 'Teilen',
},
};
export const preferences_window = {
title: 'Einstellungen',
startup: {
heading: 'Start',
login: 'Öffne beim Start',
background: 'Öffne im Hintergrund',
},
sleep: {
heading: 'Sleep',
},
discord: {
heading: 'Discord Rich Presence',
enabled: 'Discord Rich Presence ist aktiviert.',
disabled: 'Discord Rich Presence ist deaktiviert.',
setup: 'Discord Rich Presence Setup',
user: 'Discord User',
user_any: 'Zuerst gesehen',
friend_code: 'Freundescode',
friend_code_help: 'Wenn du deinen Freundescode hinzufügst, wird ebenfalls dein User Icon in Discord angezeigt.',
friend_code_self: 'Teile meinen Freundescode',
friend_code_custom: 'Eigenen Freundescode festlegen',
inactive_presence: 'Zeige inaktive Aktivität',
inactive_presence_help: 'Zeigt "Spielt nicht", wenn eine verbundene Konsole online ist, du aber nicht spielst.',
play_time: 'Spielzeit',
play_time_hidden: 'Spielzeit niemals anzeigen',
play_time_nintendo: 'Zeige Spielzeit wie sie auf der Nintendo Switch Konsole angezeigt wird',
play_time_approximate_play_time: 'Zeige ungefähre Spielzeit (nächste 5 Stunden) an',
play_time_approximate_play_time_since: 'Zeige ungefähre Spielzeit (nächste 5 Stunden) mit erstem Startdatum an',
play_time_hour_play_time: 'Zeige ungefähre Spielzeit (nächste Stunde) an',
play_time_hour_play_time_since: 'Zeige ungefähre Spielzeit (nächste Stunde) mit erstem Startdatum an',
play_time_detailed_play_time: 'Zeige exakte Spielzeit an',
play_time_detailed_play_time_since: 'Zeige exakte Spielzeit mit erstem Startdatum an',
},
splatnet3: {
heading: 'SplatNet 3',
discord: 'Aktiviere die erweiterte Discord Rich Presence für Splatoon 3',
discord_help_1: 'Benutzt SplatNet 3, um zusätzliche Informationen anzuzeigen, während du Splatoon 3 spielst. Du musst einen zweiten Nintendo Switch Account hinzufügen, welcher mit deinem Hauptaccount befreundet ist und Zugriff auf SplatNet 3 hat.',
discord_help_2: 'Wenn du eine Presence URL benutzt, werden die zusätzlichen Informationen angezeigt, ohne diese Einstellung zu berücksichtigen.',
},
};
export const friend_window = {
no_presence: 'Du hast keinen Zugriff auf die Aktivität von diesem User oder er war nie online.',
nsa_id: 'NSA ID',
coral_id: 'Coral user ID',
no_coral_user: 'Hat nie die Nintendo Switch Online App genutzt',
friends_since: 'Freunde seit: {{date, datetime}}',
presence_updated_at: 'Aktivität aktualisiert: {{date, datetime}}',
presence_logout_at: 'Zuletzt online: {{date, datetime}}',
presence_sharing: 'Dieser User kann deine Aktivität sehen.',
presence_not_sharing: 'Dieser User kann deine Aktivität nicht sehen.',
discord_presence: 'Aktivität auf Discord teilen',
close: 'Schließen',
presence_playing: 'Spielt {{game}}',
presence_playing_nx: 'Spielt {{game}} (Nintendo Switch)',
presence_playing_ounce: 'Spielt {{game}} (Nintendo Switch 2)',
presence_offline: 'Offline',
presence_last_seen: 'Zuletzt gesehen: {{since_logout}}',
game_played_for_h: 'Gespielt für $t(hours, {"count": {{hours}}})',
game_played_for_hm: 'Gespielt für $t(hours, {"count": {{hours}}}), $t(minutes, {"count": {{minutes}}})',
game_played_for_m: 'Gespielt für $t(minutes, {"count": {{minutes}}})',
hours_one: '{{count}} Stunde',
hours_other: '{{count}} Stunden',
minutes_one: '{{count}} Minute',
minutes_other: '{{count}} Minuten',
game_first_played: 'Zuerst gespielt am {{date, datetime}}',
game_first_played_now: 'Zuerst gespielt jetzt',
game_title_id: 'Titel ID',
game_shop: 'Nintendo eShop',
};
export const addfriend_window = {
title: 'Freund hinzufügen',
help: 'Gebe oder füge einen Freundescode oder eine Freundescode-URL ein, um eine Freundschaftsanfrage zu senden.',
lookup_error: 'Fehler beim Aufrufen des Freundescodes aufgetreten: {{message}}',
nsa_id: 'NSA ID',
coral_id: 'Coral user ID',
no_coral_user: 'Hat nie die Nintendo Switch Online App genutzt',
send_added: 'Du bist nun mit diesem User befreundet.',
send_sent: 'Freundschaftsanfrage gesendet. {{user}} kann deine Freundschaftsanfrage über die Nintendo Switch Konsole annehmen oder dir eine Freundschaftsanfrage über die Nintendo Switch Online App oder nxapi senden.',
send_sending: 'Sende Freundschaftsanfrage...',
send_error: 'Fehler beim Senden der Freundschaftsanfrage aufgetreten: {{message}}',
already_friends: 'Du bist bereits mit diesem User befreundet',
close: 'Schließen',
send: 'Anfrage senden',
};
export const discordsetup_window = {
title: 'Discord Rich Presence Setup',
mode_heading: '1. Wähle den Modus aus',
mode_coral_friend: 'Wähle einen User, der mit dir befreundet ist, aus.',
mode_url: 'Gebe eine URL ein, die deine Aktivität zurückgibt.',
mode_none: 'Deaktivieren',
coral_user_heading: '2. Wähle den User aus',
coral_user_help: 'Der User muss mit dir befreundet sein, um die Aktivität zu teilen.',
coral_friend_heading: '3. Wähle einen Freund aus',
coral_friend_help: 'Das ist der User, den du teilen möchtest.',
url_heading: '2. Gebe eine Presence-URL ein',
url_help: 'Der Link muss eine HTTPS-URL sein, die ein JSON-Objekt mit einem User, Freund oder Aktivitätsschlüssel zurückgibt. Diese Funktion ist für nxapi\'s znc API Proxy vorgesehen.',
preferences_heading: 'Konfiguriere zusätzliche Optionen für die Discord Rich Presence',
preferences: 'Einstellungen',
cancel: 'Abbrechen',
save: 'Speichern',
};
export const addaccountmanual_window = {
title: 'Account hinzufügen',
authorise_heading: '1. Logge dich in deinen Nintendo Account ein.',
authorise_help: 'Wähle noch keinen Account aus.',
authorise_open: 'Öffne die Nintendo Account Authorisierung',
response_heading: '2. Gebe den Weiterleitungslink ein',
response_help_1: 'Rechtsklick auf der "Externen Account verlinken" Seite, Rechtsklick auf "Diese Person auswählen" und den Link kopieren. Der Link sollte mit "{{url}}". beginnen',
response_help_2: 'Wenn du einen Kinder-Account, welcher mit deinem Account verlinkt ist, hinzufügen möchtest, klicke auf \"Diese Person auswählen\". Wenn dann nur der Kinder-Account angezeigt wird, Rechtsklick auf \"Diese Person auswählen\" und den Link kopieren.',
cancel: 'Abbrechen',
save: 'Account hinzufügen',
};

View File

@ -1,397 +0,0 @@
import { CREDITS_NOTICE, LICENCE_NOTICE, ZNCA_API_USE_TEXT } from '../../../common/constants.js';
export const app = {
default_title: 'Nintendo Switch Online',
licence: LICENCE_NOTICE,
credits: CREDITS_NOTICE,
translation_credits: '{{language}} translation by {{authors, list}}.',
};
export const app_menu = {
preferences: 'Preferences',
view: 'View',
learn_more: 'Learn More',
learn_more_github: 'Learn More (GitHub)',
search_issues: 'Search Issues',
export_logs: 'Export Logs',
refresh: 'Refresh',
};
export const menu_app = {
coral_heading: 'Nintendo Switch Online',
na_id: 'Nintendo Account ID: {{id}}',
coral_id: 'Coral ID: {{id}}',
nsa_id: 'NSA ID: {{id}}',
discord_presence_enable: 'Enable Discord Presence',
user_notifications_enable: 'Enable notifications for this user\'s presence',
friend_notifications_enable: 'Enable notifications for friends of this user\'s presence',
refresh: 'Update now',
add_friend: 'Add friend',
web_services: 'Web services',
moon_heading: 'Nintendo Switch Parental Controls',
add_account: 'Add account',
show_main_window: 'Show main window',
preferences: 'Preferences',
quit: 'Quit',
};
export const menus = {
add_account: {
add_account_coral: 'Add Nintendo Switch Online account',
add_account_moon: 'Add Nintendo Switch Parental Controls account',
},
friend_code: {
share: 'Share',
copy: 'Copy',
friend_code_regenerable: 'Regenerate using a Nintendo Switch console',
friend_code_regenerable_at: 'Can be regenerated at {{date, datetime}}',
},
user: {
na_id: 'Nintendo Account ID: {{id}}',
coral_id: 'Coral ID: {{id}}',
nsa_id: 'NSA ID: {{id}}',
discord_disable: 'Disable Discord presence',
discord_enabled_for: 'Discord presence enabled for {{name}}',
discord_enabled_via: 'Discord presence enabled using {{name}}',
discord_enable: 'Enable Discord presence for this user...',
friend_notifications_enable: 'Enable friend notifications',
refresh: 'Update now',
add_friend: 'Add friend',
remove_help: 'Use the nxapi command to remove this user',
},
friend: {
presence_online: 'Online',
presence_online_nx: 'Online (Nintendo Switch)',
presence_online_ounce: 'Online (Nintendo Switch 2)',
game_first_played: 'First played: {{date, datetime}}',
game_play_time_h: 'Play time: $t(friend.hours, {"count": {{hours}}})',
game_play_time_hm: 'Play time: $t(friend.hours, {"count": {{hours}}}), $t(friend.minutes, {"count": {{minutes}}})',
game_play_time_m: 'Play time: $t(friend.minutes, {"count": {{minutes}}})',
hours_one: '{{count}} hour',
hours_other: '{{count}} hours',
minutes_one: '{{count}} minute',
minutes_other: '{{count}} minutes',
presence_inactive: 'Offline (console online)',
presence_offline: 'Offline',
presence_updated: 'Updated: {{date, datetime}}',
presence_logout_time: 'Logout time: {{date, datetime}}',
discord_presence_enable: 'Enable Discord Presence',
},
};
export const notifications = {
playing: 'Playing {{name}}',
offline: 'Offline',
};
export const handle_uri = {
friend_code_select: 'Select a user to add friends',
web_service_select: 'Select a user to open this web service',
web_service_invalid_title: 'Invalid web service',
web_service_invalid_detail: 'The URL did not reference an existing web service.',
cancel: 'Cancel',
};
export const na_auth = {
window: {
title: 'Nintendo Account',
},
znca_api_use: {
title: 'Third-party API usage',
// This should be translated in other languages
text: ZNCA_API_USE_TEXT,
ok: 'OK',
cancel: 'Cancel',
more_information: 'More information',
},
notification_coral: {
title: 'Nintendo Switch Online',
body_existing: 'Already signed in as {{name}} (Nintendo Account {{na_name}} / {{na_username}})',
body_authenticated: 'Authenticated as {{name}} (Nintendo Account {{na_name}} / {{na_username}})',
body_reauthenticated: 'Reauthenticated to {{name}} (Nintendo Account {{na_name}} / {{na_username}})',
},
notification_moon: {
title: 'Nintendo Switch Parental Controls',
body_existing: 'Already signed in as {{na_name}} ({{na_username}})',
body_authenticated: 'Authenticated as {{na_name}} ({{na_username}})',
body_reauthenticated: 'Reauthenticated to {{na_name}} ({{na_username}})',
},
error: {
title: 'Error adding account',
},
};
export const time_since = {
default: {
now: 'just now',
seconds_one: '{{count}} second ago',
seconds_other: '{{count}} seconds ago',
minutes_one: '{{count}} minute ago',
minutes_other: '{{count}} minutes ago',
hours_one: '{{count}} hour ago',
hours_other: '{{count}} hours ago',
days_one: '{{count}} day ago',
days_other: '{{count}} days ago',
},
short: {
now: 'Just now',
seconds_one: '{{count}} sec',
seconds_other: '{{count}} secs',
minutes_one: '{{count}} min',
minutes_other: '{{count}} mins',
hours_one: '{{count}} hr',
hours_other: '{{count}} hrs',
days_one: '{{count}} day',
days_other: '{{count}} days',
},
};
export const main_window = {
sidebar: {
discord_active: 'Discord Rich Presence active',
discord_active_friend: 'Discord Rich Presence active: <0></0>',
discord_not_active: 'Discord Rich Presence not active',
discord_playing: 'Playing',
discord_not_connected: 'Not connected to Discord',
add_user: 'Add user',
discord_setup: 'Set up Discord Rich Presence',
},
update: {
update_available: 'Update available: {{name}}',
download: 'Download',
error: 'Error checking for updates: {{message}}',
retry: 'Try again',
},
main_section: {
error: {
title: 'Error loading data',
message: 'An error occured while loading {{errors, list}} data.',
message_friends: 'friends',
message_webservices: 'game-specific services',
message_event: 'voice chat',
retry: 'Retry',
view_details: 'View details',
},
moon_only_user: {
title: 'Nintendo Switch Online',
desc_1: 'This user is signed in to the Nintendo Switch Parental Controls app, but not the Nintendo Switch Online app.',
desc_2: 'Login to the Nintendo Switch Online app to view details here, or use the nxapi command to access Parental Controls data.',
login: 'Login',
},
section_error: 'Error updating data',
},
discord_section: {
title: 'Discord Rich Presence',
setup_with_existing_user: 'Use one of these accounts to set up Discord Rich Presence for this user: <0></0>.',
add_user: 'Add a Nintendo Switch Online account with this user as a friend to set up Discord Rich Presence.',
active_self: 'This user\'s presence is being shared to Discord.',
active_friend: '<0></0>\'s presence is being shared to Discord using this account.',
active_unknown: 'An unknown user\'s presence is being shared to Discord using this account.',
active_via: 'This user\'s presence is being shared to Discord using <0></0>.',
setup: 'Setup',
disable: 'Disable',
},
friends_section: {
title: 'Friends',
add: 'Add',
no_friends: 'Add friends using a Nintendo Switch console.',
friend_code: 'Your friend code: <0></0>',
presence_playing: 'Playing',
presence_offline: 'Offline',
},
webservices_section: {
title: 'Game-specific services',
},
event_section: {
title: 'Voice chat',
members: '{{event}} in game, {{voip}} in voice chat',
members_with_total: '{{event}} in game, {{voip}} in voice chat of {{total}} members',
app_start: 'Use the Nintendo Switch Online app on iOS or Android to start voice chat.',
app_join: 'Use the Nintendo Switch Online app on iOS or Android to join voice chat.',
share: 'Share',
},
};
export const preferences_window = {
title: 'Preferences',
startup: {
heading: 'Startup',
login: 'Open at login',
background: 'Open in background',
},
sleep: {
heading: 'Sleep',
},
discord: {
heading: 'Discord Rich Presence',
enabled: 'Discord Rich Presence is enabled.',
disabled: 'Discord Rich Presence is disabled.',
setup: 'Discord Rich Presence setup',
user: 'Discord user',
user_any: 'First discovered',
friend_code: 'Friend code',
friend_code_help: 'Adding your friend code will also show your Nintendo Switch user icon in Discord.',
friend_code_self: 'Share my friend code',
friend_code_custom: 'Set custom friend code',
inactive_presence: 'Show inactive presence',
inactive_presence_help: 'Shows "Not playing" when a console linked to your account is online, but you are not selected in a game.',
play_time: 'Play time',
play_time_hidden: 'Never show play time',
play_time_nintendo: 'Show play time as it appears on a Nintendo Switch console',
play_time_approximate_play_time: 'Show approximate play time (nearest 5 hours)',
play_time_approximate_play_time_since: 'Show approximate play time (nearest 5 hours) with first played date',
play_time_hour_play_time: 'Show approximate play time (nearest hour)',
play_time_hour_play_time_since: 'Show approximate play time (nearest hour) with first played date',
play_time_detailed_play_time: 'Show exact play time',
play_time_detailed_play_time_since: 'Show exact play time with first played date',
},
splatnet3: {
heading: 'SplatNet 3',
discord: 'Enable enhanced Discord Rich Presence for Splatoon 3',
discord_help_1: 'Uses SplatNet 3 to retrieve additional presence information while playing Splatoon 3. You must be using a secondary Nintendo Account that is friends with your main account to fetch your presence, and the secondary account must be able to access SplatNet 3.',
discord_help_2: 'When using a presence URL that returns Splatoon 3 data additional presence information will be shown regardless of this setting.',
},
miscellaneous: {
heading: 'Miscellaneous',
show_error_alerts: 'Show error alerts',
show_error_alerts_help: 'Shows an alert when an error occurs while updating presence. If this is disabled, nxapi will delay updates after errors.',
},
};
export const friend_window = {
no_presence: 'You don\'t have access to this user\'s presence, or they have never been online.',
nsa_id: 'NSA ID',
coral_id: 'Coral user ID',
no_coral_user: 'Never used the Nintendo Switch Online app',
friends_since: 'Friends since {{date, datetime}}',
presence_updated_at: 'Presence updated at {{date, datetime}}',
presence_logout_at: 'Last online at {{date, datetime}}',
presence_sharing: 'This user can see your presence.',
presence_not_sharing: 'This user can not see your presence.',
discord_presence: 'Share presence to Discord',
close: 'Close',
presence_playing: 'Playing {{game}}',
presence_playing_nx: 'Playing {{game}} (Nintendo Switch)',
presence_playing_ounce: 'Playing {{game}} (Nintendo Switch 2)',
presence_offline: 'Offline',
presence_last_seen: 'Last seen {{since_logout}}',
game_played_for_h: 'Played for $t(hours, {"count": {{hours}}})',
game_played_for_hm: 'Played for $t(hours, {"count": {{hours}}}), $t(minutes, {"count": {{minutes}}})',
game_played_for_m: 'Played for $t(minutes, {"count": {{minutes}}})',
hours_one: '{{count}} hour',
hours_other: '{{count}} hours',
minutes_one: '{{count}} minute',
minutes_other: '{{count}} minutes',
game_first_played: 'First played {{date, datetime}}',
game_first_played_now: 'First played now',
game_title_id: 'Title ID',
game_shop: 'Nintendo eShop',
};
export const addfriend_window = {
title: 'Add friend',
help: 'Type or paste a friend code or friend code URL to send a friend request.',
lookup_error: 'Error looking up friend code: {{message}}',
nsa_id: 'NSA ID',
coral_id: 'Coral user ID',
no_coral_user: 'Never used the Nintendo Switch Online app',
send_added: 'You are now friends with this user.',
send_sent: 'Friend request sent. {{user}} can accept your friend request using a Nintendo Switch console, or by sending you a friend request using the Nintendo Switch Online app or nxapi.',
send_sending: 'Sending friend request...',
send_error: 'Error sending friend request: {{message}}',
already_friends: 'You are already friends with this user.',
close: 'Close',
send: 'Send friend request',
};
export const discordsetup_window = {
title: 'Discord Rich Presence setup',
mode_heading: '1. Select mode',
mode_coral_friend: 'Select a user that is friends with the user you want to share',
mode_url: 'Enter a URL that returns the presence data you want to share',
mode_none: 'Disable',
coral_user_heading: '2. Select user',
coral_user_help: 'This user must be friends with the user you want to share.',
coral_friend_heading: '3. Select friend',
coral_friend_help: 'This is the user you want to share.',
url_heading: '2. Enter presence URL',
url_help: 'This must be a HTTPS URL that returns a JSON object with either a user, friend or presence key. This is intended to be used with nxapi\'s znc API proxy.',
preferences_heading: 'Configure additional options for Discord Rich Presence',
preferences: 'Preferences',
cancel: 'Cancel',
save: 'Save',
};
export const addaccountmanual_window = {
title: 'Add account',
authorise_heading: '1. Login to your Nintendo Account',
authorise_help: 'Do not select an account yet.',
authorise_open: 'Open Nintendo Account authorisation',
response_heading: '2. Enter the callback link',
response_help_1: 'On the "Linking an External Account" page, right click "Select this person" and copy the link. It should start with "{{url}}".',
response_help_2: 'If you are adding a child account linked to your account, click "Select this person" next to their account to sign in as the child account, then with only the child account showing right click "Select this person" and copy the link.',
cancel: 'Cancel',
save: 'Add account',
};

View File

@ -1,387 +0,0 @@
import { CREDITS_NOTICE, LICENCE_NOTICE } from '../../../common/constants.js';
export const app = {
default_title: 'Nintendo Switch Online',
licence: LICENCE_NOTICE,
credits: CREDITS_NOTICE,
translation_credits: 'Traducido al {{language}} por {{authors, list}}.',
};
export const app_menu = {
preferences: 'Preferencias',
view: 'Ver',
learn_more: 'Más Información',
learn_more_github: 'Más Información (GitHub)',
search_issues: 'Buscar Incidencias',
refresh: 'Actualizar',
};
export const menu_app = {
coral_heading: 'Nintendo Switch Online',
na_id: 'Nintendo Account ID: {{id}}',
coral_id: 'Coral ID: {{id}}',
nsa_id: 'NSA ID: {{id}}',
discord_presence_enable: 'Activar Discord Rich Presence',
user_notifications_enable: 'Activar notificaciones para este usuario',
friend_notifications_enable: 'Activar notificaciones para amigos de este usuario',
refresh: 'Actualizar ahora',
add_friend: 'Añadir amigo',
web_services: 'Servicios web',
moon_heading: 'Control parental de Nintendo Switch',
add_account: 'Añadir cuenta',
show_main_window: 'Mostrar la ventana principal',
preferences: 'Preferencias',
quit: 'Cerrar',
};
export const menus = {
add_account: {
add_account_coral: 'Añadir cuenta de Nintendo Switch Online',
add_account_moon: 'Añadir cuenta de Control parental de Nintendo Switch',
},
friend_code: {
share: 'Compartir',
copy: 'Copiar',
friend_code_regenerable: 'Regenerar utilizando una consola Nintendo Switch',
friend_code_regenerable_at: 'Se puede regenerar el {{date, datetime}}',
},
user: {
na_id: 'Nintendo Account ID: {{id}}',
coral_id: 'Coral ID: {{id}}',
nsa_id: 'NSA ID: {{id}}',
discord_disable: 'Desactivar Discord Rich Presence',
discord_enabled_for: 'Discord Rich Presence activado para {{name}}',
discord_enabled_via: 'Discord Rich Presence activado utilizando {{name}}',
discord_enable: 'Activar Discord Rich Presence para este usuario...',
friend_notifications_enable: 'Activar notificaciones para amigos',
refresh: 'Actualizar ahora',
add_friend: 'Añadir amigo',
remove_help: 'Utiliza el comando nxapi para eliminar a este usuario',
},
friend: {
presence_online: 'Online',
presence_online_nx: 'Online (Nintendo Switch)',
presence_online_ounce: 'Online (Nintendo Switch 2)',
game_first_played: 'Jugado por primera vez: {{date, datetime}}',
game_play_time_h: 'Tiempo de juego: $t(friend.hours, {"count": {{hours}}})',
game_play_time_hm: 'Tiempo de juego: $t(friend.hours, {"count": {{hours}}}), $t(friend.minutes, {"count": {{minutes}}})',
game_play_time_m: 'Tiempo de juego: $t(friend.minutes, {"count": {{minutes}}})',
hours_one: '{{count}} hora',
hours_other: '{{count}} horas',
minutes_one: '{{count}} minuto',
minutes_other: '{{count}} minutos',
presence_inactive: 'Desconectado (consola conectada)',
presence_offline: 'Desconectado',
presence_updated: 'Actualizado: {{date, datetime}}',
presence_logout_time: 'Hora de desconexión: {{date, datetime}}',
discord_presence_enable: 'Activar Discord Rich Presence',
},
};
export const notifications = {
playing: 'Jugando {{name}}',
offline: 'Desconectado',
};
export const handle_uri = {
friend_code_select: 'Selecciona un usuario para añadir amigos',
web_service_select: 'Selecciona un usuario para abrir este servicio web',
web_service_invalid_title: 'Servicio web inválido',
web_service_invalid_detail: 'La URL no hace referencia a un servicio web existente.',
cancel: 'Cancelar',
};
export const na_auth = {
window: {
title: 'Cuenta Nintendo',
},
znca_api_use: {
title: 'Uso de API de terceros',
ok: 'OK',
cancel: 'Cancelar',
more_information: 'Más Información',
},
notification_coral: {
title: 'Nintendo Switch Online',
body_existing: 'Ya has iniciado sesión como {{name}} (Nintendo Account {{na_name}} / {{na_username}})',
body_authenticated: 'Autenticado como {{name}} (Nintendo Account {{na_name}} / {{na_username}})',
body_reauthenticated: 'Reautenticado como {{name}} (Nintendo Account {{na_name}} / {{na_username}})',
},
notification_moon: {
title: 'Control parental de Nintendo Switch',
body_existing: 'Ya has iniciado sesión como {{na_name}} ({{na_username}})',
body_authenticated: 'Autenticado como {{na_name}} ({{na_username}})',
body_reauthenticated: 'Reautenticado como {{na_name}} ({{na_username}})',
},
error: {
title: 'Error añadiendo cuenta',
},
};
export const time_since = {
default: {
now: 'ahora',
seconds_one: 'Hace {{count}} segundo',
seconds_other: 'Hace {{count}} segundos',
minutes_one: 'Hace {{count}} minuto',
minutes_other: 'Hace {{count}} minutos',
hours_one: 'Hace {{count}} hora',
hours_other: 'Hace {{count}} horas',
days_one: 'Hace {{count}} día',
days_other: 'Hace {{count}} días',
},
short: {
now: 'Ahora',
seconds_one: '{{count}} seg',
seconds_other: '{{count}} seg',
minutes_one: '{{count}} min',
minutes_other: '{{count}} min',
hours_one: '{{count}} h',
hours_other: '{{count}} h',
days_one: '{{count}} día',
days_other: '{{count}} días',
},
};
export const main_window = {
sidebar: {
discord_active: 'Discord Rich Presence activo',
discord_active_friend: 'Discord Rich Presence activo: <0></0>',
discord_not_active: 'Discord Rich Presence no está activo',
discord_playing: 'Jugando',
discord_not_connected: 'No conectado a Discord',
add_user: 'Añadir usuario',
discord_setup: 'Configurar Discord Rich Presence',
},
update: {
update_available: 'Actualización disponible: {{name}}',
download: 'Descargar',
error: 'Error buscando actualizaciones: {{message}}',
retry: 'Intentar de nuevo',
},
main_section: {
error: {
title: 'Error cargando datos',
message: 'Se produjo un error cargando los datos {{errors, list}}.',
message_friends: 'amigos',
message_webservices: 'servicios específicos de juegos',
message_event: 'chat de voz',
retry: 'Reintentar',
view_details: 'Ver detalles',
},
moon_only_user: {
title: 'Nintendo Switch Online',
desc_1: 'Este usuario ha iniciado sesión a la aplicación de Control parental de Nintendo Switch, pero no en la aplicación de Nintendo Switch Online.',
desc_2: 'Inicia sesión en la aplicación de Nintendo Switch Online para ver los detalles aquí, o utiliza el comando nxapi para acceder a los datos de Control Parental.',
login: 'Iniciar Sesión',
},
section_error: 'Error actualizando datos',
},
discord_section: {
title: 'Discord Rich Presence',
setup_with_existing_user: 'Utiliza una de estas cuentas para configurar Discord Rich Presence para este usuario: <0></0>.',
add_user: 'Añade una cuenta de Nintendo Switch Online con este usuario como amigo para configurar Discord Rich Presence.',
active_self: 'Compartiendo el estado de este usuario.',
active_friend: 'El estado de <0></0> se está compartiendo a Discord utilizando esta cuenta.',
active_unknown: 'El estado de un usuario desconocido se está compartiendo a Discord utilizando esta cuenta.',
active_via: 'El estado de este usuario se está compartiendo a Discord utilizando <0></0>.',
setup: 'Configurar',
disable: 'Desactivar',
},
friends_section: {
title: 'Amigos',
add: 'Añadir',
no_friends: 'Añade amigos utilizando una consola Nintendo Switch.',
friend_code: 'Tu código de amigo: <0></0>',
presence_playing: 'Jugando',
presence_offline: 'Desconectado',
},
webservices_section: {
title: 'Servicios específicos de juegos',
},
event_section: {
title: 'Chat de voz',
members: '{{event}} jugando, {{voip}} en chat de voz',
members_with_total: '{{event}} jugando, {{voip}} en chat de voz de {{total}} miembros',
app_start: 'Utiliza la aplicación de Nintendo Switch Online en iOS o Android para empezar un chat de voz.',
app_join: 'Utiliza la aplicación de Nintendo Switch Online en iOS o Android para unirte un chat de voz.',
share: 'Compartir',
},
};
export const preferences_window = {
title: 'Preferencias',
startup: {
heading: 'Inicio',
login: 'Abrir al iniciar sesión',
background: 'Abrir en segundo plano',
},
sleep: {
heading: 'Sleep',
},
discord: {
heading: 'Discord Rich Presence',
enabled: 'Discord Rich Presence está activado.',
disabled: 'Discord Rich Presence está desactivado.',
setup: 'Configuración de Discord Rich Presence',
user: 'Usuario de Discord',
user_any: 'El primero que encuentre',
friend_code: 'Código de amigo',
friend_code_help: 'Añadir tu código de amigo también enseñará tu icono de usuario de Nintendo Switch en Discord.',
friend_code_self: 'Compartir mi código de amigo',
friend_code_custom: 'Personalizar código de amigo',
inactive_presence: 'Mostrar inactividad',
inactive_presence_help: 'Muestra "No está jugando" cuando una consola vinculada con tu cuenta está en línea, pero tú no estás jugando.',
play_time: 'Tiempo de juego',
play_time_hidden: 'Nunca mostrar el tiempo de juego',
play_time_nintendo: 'Mostrar el tiempo de juego como aparece en la consola Nintendo Switch',
play_time_approximate_play_time: 'Mostrar tiempo de juego aproximado (5 horas más cercanas)',
play_time_approximate_play_time_since: 'Mostrar tiempo de juego aproximado (5 horas más cercanas) con fecha de la primera partida',
play_time_hour_play_time: 'Mostrar tiempo de juego aproximado (hora más cercana)',
play_time_hour_play_time_since: 'Mostrar tiempo de juego aproximado (hora más cercana) con fecha de la primera partida',
play_time_detailed_play_time: 'Mostrar tiempo de juego exacto',
play_time_detailed_play_time_since: 'Mostrar tiempo de juego exacto con fecha de la primera partida',
},
splatnet3: {
heading: 'SplatNet 3',
discord: 'Activar Discord Rich Presence ampliado para Splatoon 3',
discord_help_1: 'Utiliza SplatNet 3 para mostrar información adicional mientras juegas Splatoon 3. Deberás utilizar una cuenta Nintendo secundaria que esté añadida como amigo en tu cuenta principal y tenga acceso a SplatNet 3.',
discord_help_2: 'Si utilizas una URL que devuelva datos de Splatoon 3 se mostrará la información adicional sin tener en cuenta esta opción.',
},
};
export const friend_window = {
no_presence: 'No tienes acceso al estado de este usuario, o nunca se ha conectado.',
nsa_id: 'NSA ID',
coral_id: 'Coral user ID',
no_coral_user: 'Nunca ha utilizado la aplicación de Nintendo Switch Online',
friends_since: 'Amigos desde: {{date, datetime}}',
presence_updated_at: 'Estado actualizado: {{date, datetime}}',
presence_logout_at: 'Última vez online: {{date, datetime}}',
presence_sharing: 'Este usuario puede ver tu estado.',
presence_not_sharing: 'Este usuario no puede ver tu estado.',
discord_presence: 'Compartir estado\nen Discord',
close: 'Cerrar',
presence_playing: 'Jugando {{game}}',
presence_playing_nx: 'Jugando {{game}} (Nintendo Switch)',
presence_playing_ounce: 'Jugando {{game}} (Nintendo Switch 2)',
presence_offline: 'Desconectado',
presence_last_seen: 'Visto por última vez: {{since_logout}}',
game_played_for_h: 'Jugado durante: $t(hours, {"count": {{hours}}})',
game_played_for_hm: 'Jugado durante: $t(hours, {"count": {{hours}}}), $t(minutes, {"count": {{minutes}}})',
game_played_for_m: 'Jugado durante: $t(minutes, {"count": {{minutes}}})',
hours_one: '{{count}} hora',
hours_other: '{{count}} horas',
minutes_one: '{{count}} minuto',
minutes_other: '{{count}} minutos',
game_first_played: 'Jugado por primera vez: {{date, datetime}}',
game_first_played_now: 'Jugado por primera vez: ahora',
game_title_id: 'Title ID',
game_shop: 'Nintendo eShop',
};
export const addfriend_window = {
title: 'Añadir amigo',
help: 'Escribe o pega un código de amigo o una URL de código de amigo para enviar una solicitud de amistad.',
lookup_error: 'Se produjo un error al buscar el código de amigo: {{message}}',
nsa_id: 'NSA ID',
coral_id: 'Coral user ID',
no_coral_user: 'Nunca ha utilizado la aplicación de Nintendo Switch Online',
send_added: 'Ahora eres amigo de este usuario.',
send_sent: 'Solicitud de amistad enviada. {{user}} puede aceptar tu solicitud de amistad utilizando una consola Nintendo Switch, o enviándote una solicitud de amistad utilizando la aplicación de Nintendo Switch Online o nxapi.',
send_sending: 'Enviando solicitud de amistad...',
send_error: 'Se produjo un error al enviar la solicitud de amistad: {{message}}',
already_friends: 'Ya eres amigo de este usuario.',
close: 'Cerrar',
send: 'Enviar solicitud de amistad',
};
export const discordsetup_window = {
title: 'Configuración de Discord Rich Presence',
mode_heading: '1. Selecciona un modo',
mode_coral_friend: 'Selecciona un usuario que sea amigo del usuario que quieres compartir',
mode_url: 'Introduce una URL que devuelva el estado que quieres compartir',
mode_none: 'Desactivar',
coral_user_heading: '2. Selecciona un usuario',
coral_user_help: 'Este usuario tiene que ser amigo del usuario que quieres compartir.',
coral_friend_heading: '3. Selecciona un amigo',
coral_friend_help: 'Este es el usuario que quieres compartir.',
url_heading: '2. Ingresa una URL de estado',
url_help: 'Esta URL tiene que utilizar HTTPS y devolver un objeto JSON con una clave de usuario, amigo o estado. Esta función está diseñada para ser utilizada con el proxy de la API znc de nxapi.',
preferences_heading: 'Configura opciones adicionales para Discord Rich Presence',
preferences: 'Preferencias',
cancel: 'Cancelar',
save: 'Guardar',
};
export const addaccountmanual_window = {
title: 'Añadir cuenta',
authorise_heading: '1. Inicia sesión en tu cuenta Nintendo',
authorise_help: 'Aún no elijas una cuenta.',
authorise_open: 'Abrir la autorización de la cuenta Nintendo',
response_heading: '2. Introduce el enlace de callback',
response_help_1: 'En la pagina de "Vincular una cuenta externa", dale click derecho a "Elegir a esta persona" y copia el link. El link debería de empezar con "{{url}}".',
response_help_2: 'Si deseas agregar una cuenta infantil vinculada a tu cuenta, haz clic en "Elegir a esta persona". Si solo se muestra la cuenta infantil, haz clic derecho en "Elegir esta persona" y copia el enlace.',
cancel: 'Cancelar',
save: 'Añadir cuenta',
};

View File

@ -1,354 +0,0 @@
import { CREDITS_NOTICE, LICENCE_NOTICE } from '../../../common/constants.js';
export const app = {
default_title: 'Nintendo Switch Online',
licence: LICENCE_NOTICE,
credits: CREDITS_NOTICE,
translation_credits: 'Japanese translation by hilot06.',
};
export const app_menu = {
preferences: '設定',
view: '表示',
learn_more: 'もっと知る',
learn_more_github: 'GitHubでもっと知る',
search_issues: 'Issuesの検索',
refresh: '更新',
};
export const menu_app = {
coral_heading: 'Nintendo Switch Online',
na_id: 'ニンテンドーアカウントのID: {{id}}',
coral_id: 'Coral ID: {{id}}',
nsa_id: 'NSA ID: {{id}}',
discord_presence_enable: 'Discord Presenceを有効にする',
user_notifications_enable: 'このユーザーの通知を有効にする',
friend_notifications_enable: 'フレンド通知を有効にする',
refresh: '今すぐアップデート',
add_friend: 'フレンドを追加',
web_services: 'Webサービス',
moon_heading: 'NintendoみまもりSwitch',
add_account: 'アカウントを追加',
show_main_window: 'メイン画面を表示',
preferences: '設定',
quit: '終了',
};
export const menus = {
add_account: {
add_account_coral: 'Nintendo Switch Online アカウントを追加',
add_account_moon: 'NintendoみまもりSwitch アカウントを追加',
},
friend_code: {
share: '共有',
copy: 'コピー',
friend_code_regenerable: 'Nintendo Switch本体を使ってフレンドコードを再発行',
friend_code_regenerable_at: '{{date, datetime}}から再発行できます',
},
user: {
na_id: 'ニンテンドーアカウントのID: {{id}}',
coral_id: 'Coral ID: {{id}}',
nsa_id: 'NSA ID: {{id}}',
discord_disable: 'Discord Rich Presenceが無効',
discord_enabled_for: '{{name}}のDiscord Rich Presenceが有効',
discord_enabled_via: '{{name}}を経由したDiscord Rich Presenceが有効',
discord_enable: 'このユーザーに対してDiscord Rich Presenceを有効化する...',
friend_notifications_enable: 'フレンド通知を有効化',
refresh: '今すぐアップデート',
add_friend: 'フレンドを追加',
remove_help: 'このユーザーを削除するには、nxapiコマンドを使用してください。',
},
friend: {
presence_online: 'オンライン',
presence_online_nx: 'オンライン (Nintendo Switch)',
presence_online_ounce: 'オンライン (Nintendo Switch 2)',
game_first_played: '初めてあそんだ日: {{date, datetime}}',
game_play_time_h: 'プレイ時間: $t(friend.hours, {"count": {{hours}}})',
game_play_time_hm: 'プレイ時間: $t(friend.hours, {"count": {{hours}}}), $t(friend.minutes, {"count": {{minutes}}})',
game_play_time_m: 'プレイ時間: $t(friend.minutes, {"count": {{minutes}}})',
hours_one: '{{count}}時間',
hours_other: '{{count}}時間',
minutes_one: '{{count}}分',
minutes_other: '{{count}}分',
presence_inactive: 'オンライン (ゲーム未起動)',
presence_offline: 'オフライン',
presence_updated: '更新日時: {{date, datetime}}',
presence_logout_time: 'オフラインになった日時: {{date, datetime}}',
discord_presence_enable: 'Discord Rich Presenceを有効化',
},
};
export const notifications = {
playing: '{{name}} をプレイ中',
offline: 'オフライン',
};
export const handle_uri = {
friend_code_select: 'フレンドを追加するユーザーを選択',
web_service_select: 'このWebサービスを開くユーザーを選択',
web_service_invalid_title: '無効なWebサービス',
web_service_invalid_detail: 'そのURLは既存のWebサービスを参照していません。',
cancel: 'キャンセル',
};
export const time_since = {
default: {
now: 'たった今',
seconds_one: '{{count}}秒前',
seconds_other: '{{count}}秒前',
minutes_one: '{{count}}分前',
minutes_other: '{{count}}分前',
hours_one: '{{count}}時間前',
hours_other: '{{count}}時間前',
days_one: '{{count}}日前',
days_other: '{{count}}日前',
},
short: {
now: '今',
seconds_one: '{{count}}秒',
seconds_other: '{{count}}秒',
minutes_one: '{{count}}分',
minutes_other: '{{count}}分',
hours_one: '{{count}}時間',
hours_other: '{{count}}時間',
days_one: '{{count}}日',
days_other: '{{count}}日',
},
};
export const main_window = {
sidebar: {
discord_active: 'Discord Rich Presenceが動作中',
discord_active_friend: 'Discord Rich Presenceが動作中: <0></0>',
discord_not_active: 'Discord Rich Presenceは動作していません',
discord_playing: 'プレイ中',
add_user: 'ユーザーを追加',
discord_setup: 'Discord Rich Presenceを設定',
},
update: {
update_available: 'アップデートが利用可能: {{name}}',
download: 'ダウンロード',
error: 'アップデートの確認に失敗しました: {{message}}',
retry: 'やり直す',
},
main_section: {
error: {
title: 'データ読み込みエラー',
message: '{{errors, list}} データの読み込み中にエラーが発生しました。.',
message_friends: 'フレンド',
message_webservices: 'ゲーム固有サービス',
message_event: 'ボイスチャット',
retry: 'やり直す',
view_details: '詳細を表示',
},
moon_only_user: {
title: 'Nintendo Switch Online',
desc_1: 'このユーザーはNintendo Switch Onlineのアプリではなく、NintendoみまもりSwitchのアプリにサインインしています。',
desc_2: '詳細を確認するには、こちらからNintendo Switch Onlineのアプリにログインするか、nxapiのコマンドを使ってNintendoみまもりSwitchのデータを閲覧してください。',
login: 'ログイン',
},
section_error: 'データ更新エラー',
},
discord_section: {
title: 'Discord Rich Presence',
setup_with_existing_user: 'この中からDiscord Rich Presenceの表示に使うアカウントを選択: <0></0>.',
add_user: 'このユーザーのNintendo Switch Onlineアカウントをフレンドとして追加し、Discord Rich Presenceを設定します。',
active_self: 'このユーザーの情報をDiscordで表示',
active_friend: '<0></0>の情報をこのアカウントを使ってDiscordで表示',
active_unknown: '不明なユーザーの情報が、このアカウントを使ってDiscordで表示されます。',
active_via: 'このユーザーの情報は<0></0>を使ってDiscordで表示されます。',
setup: 'セットアップ',
disable: '無効化',
},
friends_section: {
title: 'フレンド',
add: '追加する',
no_friends: 'Nintendo Switch本体を使ってフレンドを追加してください。',
friend_code: 'あなたのフレンドコード: <0></0>',
presence_playing: 'プレイ中',
presence_offline: 'オフライン',
},
webservices_section: {
title: 'ゲーム固有サービス',
},
event_section: {
title: 'ボイスチャット',
members: 'ゲーム: {{event}} 人 / ボイスチャット: {{voip}} 人',
members_with_total: 'ゲーム: {{event}} 人 / ボイスチャット: {{voip}} 人 / 計 {{total}} 人',
app_start: 'スマホのNintendo Switch Onlineアプリを使ってボイスチャットを開始してください。',
app_join: 'スマホのNintendo Switch Onlineアプリを使ってボイスチャットに参加してください。',
share: '共有する',
},
};
export const preferences_window = {
title: '設定',
startup: {
heading: 'スタートアップ',
login: 'Windowsにログインした時に開く',
background: 'バックグラウンドで開く',
},
sleep: {
heading: 'スリープ',
},
discord: {
heading: 'Discord Rich Presence',
enabled: 'Discord Rich Presenceは有効です。',
disabled: 'Discord Rich Presenceは無効です。',
setup: 'Discord Rich Presenceのセットアップ',
user: 'Discordユーザー',
user_any: '最初に見つかったユーザーを使う',
friend_code: 'フレンドコード',
friend_code_help: 'フレンドコードを追加すると、DiscordにNintendo Switch上のユーザーアイコンも表示されます。',
friend_code_self: 'フレンドコードを共有',
friend_code_custom: 'カスタムフレンドコードを設定',
inactive_presence: '本体を起動している時にプレゼンスを表示',
inactive_presence_help: 'ゲームはしていないがNintendo Switch本体を起動している時、「Not playing」を表示します。',
play_time: 'プレイ時間',
play_time_hidden: 'プレイ時間を表示しない',
play_time_nintendo: 'Nintendo Switch本体と同じようにプレイ時間を表示する',
play_time_approximate_play_time: '5時間刻みのプレイ時間を表示',
play_time_approximate_play_time_since: '5時間刻みのプレイ時間を初プレイの日時と一緒に表示',
play_time_hour_play_time: '1時間刻みのプレイ時間を表示',
play_time_hour_play_time_since: '1時間刻みのプレイ時間を初プレイの日時と一緒に表示',
play_time_detailed_play_time: '正確なプレイ時間を表示',
play_time_detailed_play_time_since: '正確なプレイ時間を初プレイの日時と一緒に表示',
},
splatnet3: {
heading: 'イカリング3',
discord: 'スプラトゥーン3向けのDiscord Rich Presenceを有効にする',
discord_help_1: 'スプラトゥーン3をプレイ中に、イカリング3を使って追加の情報を取得・表示します。メインアカウントとフレンドであるサブアカウントを用意し、サブアカウントがイカリング3にアクセスできる必要があります。',
discord_help_2: 'Discord Presenceに設定したURLからイカリング3のデータが返ってくる場合は、この設定に関係なく追加の情報が取得・表示されます。',
},
};
export const friend_window = {
no_presence: 'このユーザーのプレイ情報を表示する権限がないか、このユーザーがオンラインになったことがありません。',
nsa_id: 'NSA ID',
coral_id: 'CoralユーザーID',
no_coral_user: 'Nintendo Switch Onlineアプリ未使用',
friends_since: 'フレンドになった日: {{date, datetime}}',
presence_updated_at: '状態の最終更新: {{date, datetime}}',
presence_logout_at: '最終オンライン: {{date, datetime}}',
presence_sharing: 'このユーザーはあなたのプレイ情報を見られます。',
presence_not_sharing: 'このユーザーはあなたのプレイ情報を見られません。',
discord_presence: 'Discordでプレイ情報をシェア',
close: '閉じる',
presence_playing: '{{game}}をプレイ中',
presence_playing_nx: '{{game}}をプレイ中 (Nintendo Switch)',
presence_playing_ounce: '{{game}}をプレイ中 (Nintendo Switch 2)',
presence_offline: 'オフライン',
presence_last_seen: '最終ログイン: {{since_logout}}',
game_played_for_h: '$t(hours, {"count": {{hours}}}) 経過',
game_played_for_hm: '$t(hours, {"count": {{hours}}}), $t(minutes, {"count": {{minutes}}}) 経過',
game_played_for_m: '$t(minutes, {"count": {{minutes}}}) 経過',
hours_one: '{{count}}時間',
hours_other: '{{count}}時間',
minutes_one: '{{count}}分',
minutes_other: '{{count}}分',
game_first_played: '{{date, datetime}}にはじめてプレイ',
game_first_played_now: '初プレイ中',
game_title_id: 'ゲームID',
game_shop: 'ニンテンドー eショップ',
};
export const addfriend_window = {
title: 'フレンドを追加',
help: 'フレンド申請を送るには、フレンドコードかフレンドコードURLを入力してください。',
lookup_error: 'フレンドコードを見つけられません: {{message}}',
nsa_id: 'NSA ID',
coral_id: 'Coral user ID',
no_coral_user: 'Nintendo Switch Onlineアプリ未使用',
send_added: 'このユーザーはフレンドです。',
send_sent: 'フレンド申請を送信しました。 {{user}}はNintendo Switchを使ってフレンド申請を許可するか、Nintendo Switch Onlineやnxapiを使ってフレンド申請を送れます。',
send_sending: 'フレンド申請を送信中...',
send_error: 'フレンド申請の送信に失敗しました: {{message}}',
already_friends: 'すでにこのユーザーはフレンドです。',
close: '閉じる',
send: 'フレンド申請を送信',
};
export const discordsetup_window = {
title: 'Discord Rich Presence 設定',
mode_heading: '1. モードを選択',
mode_coral_friend: 'フレンドのプレイ情報を共有する',
mode_url: 'URLを入力して返ってくるデータを共有する',
mode_none: '無効',
coral_user_heading: '2. ユーザーを選択',
coral_user_help: 'このユーザーは、プレイ情報を共有するユーザーとフレンド同士である必要があります。',
coral_friend_heading: '3. フレンドを選択',
coral_friend_help: 'このユーザーのプレイ情報を共有します。',
url_heading: '2. プレイ情報URLを入力',
url_help: 'このURLは、ユーザー・フレンド・プレゼンスキーのいずれかを含んだJSONファイルを返すHTTPSのURLでなければなりません。このオプションは、nxapiのznc APIプロキシを使うことを想定しています。',
preferences_heading: 'Discord Rich Presenceの追加設定を表示',
preferences: '設定',
cancel: 'キャンセル',
save: '保存する',
};
export const addaccountmanual_window = {
title: 'アカウントを追加',
authorise_heading: '1. ニンテンドーアカウントにログイン',
authorise_help: 'まだアカウントを選択しないでください',
authorise_open: 'ニンテンドーアカウントのログインページを開く',
response_heading: '2. コールバックリンクを入力',
response_help_1: '「アカウントを連携」ページに表示される「この人にする」を右クリックし、リンクをコピーしてください。コピーされたリンクは「{{url}}」から始まります。',
response_help_2: 'おとなアカウントに紐づいているこどもアカウントを追加する場合は、こどもアカウントの「この人にする」を押してこどもアカウントにサインインしてから、こどもアカウントのみが表示された状態の「この人にする」ボタンのリンクをコピーしてください。',
cancel: 'キャンセル',
save: 'アカウントを追加',
};

View File

@ -0,0 +1,8 @@
const electron = require('electron');
// Do anything that must be run before the app is ready...
electron.app.whenReady()
// @ts-expect-error
.then(() => typeof __NXAPI_BUNDLE_APP_MAIN__ !== 'undefined' ? import(__NXAPI_BUNDLE_APP_MAIN__) : import('./index.js'))
.then(m => m.init.call(null));

View File

@ -1,122 +1,68 @@
import { i18n } from 'i18next';
import { GITHUB_MIRROR_URL, GITLAB_URL, ISSUES_URL } from '../../common/constants.js';
import { app, BrowserWindow, Menu, MenuItem, shell } from 'electron';
import { App } from './index.js';
import { createLogArchive } from './support.js';
import { BrowserWindow, Menu, MenuItem, shell } from './electron.js';
let appinstance: App | null;
const menu_app = new MenuItem({role: 'appMenu'});
const menu_file = new MenuItem({role: 'fileMenu'});
const menu_edit = new MenuItem({role: 'editMenu'});
export function setAppInstance(app: App) {
appinstance = app;
}
const menu_view = new MenuItem({
label: 'View',
submenu: [
{ role: 'reload' },
{ role: 'forceReload' },
{ role: 'toggleDevTools' },
{ type: 'separator' },
{ role: 'resetZoom' },
{ role: 'zoomIn' },
{ role: 'zoomOut' },
{ type: 'separator' },
{ role: 'togglefullscreen' },
],
});
function createAppMenuItems(i18n?: i18n) {
const menu_app = new MenuItem({
role: 'appMenu',
submenu: [
{ role: 'about' },
{ type: 'separator' },
{
label: i18n?.t('app_menu:preferences') ?? 'Preferences',
accelerator: 'CommandOrControl+,',
click: () => {
appinstance?.showPreferencesWindow();
},
const menu_window = new MenuItem({role: 'windowMenu'});
const menu_help = new MenuItem({
role: 'help',
submenu: [
{
label: 'Learn More',
click: async () => {
await shell.openExternal(GITLAB_URL);
},
{ type: 'separator' },
{ role: 'services' },
{ type: 'separator' },
{ role: 'hide' },
{ role: 'hideOthers' },
{ role: 'unhide' },
{ type: 'separator' },
{ role: 'quit' },
],
});
const menu_file = new MenuItem({role: 'fileMenu'});
const menu_edit = new MenuItem({role: 'editMenu'});
const menu_window = new MenuItem({role: 'windowMenu'});
const menu_help = new MenuItem({
role: 'help',
submenu: [
{
label: i18n?.t('app_menu:learn_more') ?? 'Learn More',
click: async () => {
await shell.openExternal(GITLAB_URL);
},
},
{
label: 'Learn More (GitHub)',
click: async () => {
await shell.openExternal(GITHUB_MIRROR_URL);
},
{
label: i18n?.t('app_menu:learn_more_github') ?? 'Learn More (GitHub)',
click: async () => {
await shell.openExternal(GITHUB_MIRROR_URL);
},
},
{
label: 'Search Issues',
click: async () => {
await shell.openExternal(ISSUES_URL);
},
{
label: i18n?.t('app_menu:search_issues') ?? 'Search Issues',
click: async () => {
await shell.openExternal(ISSUES_URL);
},
},
{
label: i18n?.t('app_menu:export_logs') ?? 'Export Logs',
click: () => {
createLogArchive();
},
},
],
});
},
],
});
return {menu_app, menu_file, menu_edit, menu_window, menu_help};
}
function createAppMenu(i18n?: i18n) {
const {menu_app, menu_file, menu_edit, menu_window, menu_help} = createAppMenuItems(i18n);
export const app_menu = Menu.buildFromTemplate([
...(process.platform === 'darwin' ? [menu_app] : []),
menu_file,
menu_edit,
menu_view,
menu_window,
menu_help,
]);
export function createWindowMenu(window: BrowserWindow) {
const menu_view = new MenuItem({
label: i18n?.t('app_menu:view') ?? 'View',
submenu: [
{ role: 'reload' },
{ role: 'forceReload' },
{ role: 'toggleDevTools' },
{ type: 'separator' },
{ role: 'resetZoom' },
{ role: 'zoomIn' },
{ role: 'zoomOut' },
{ type: 'separator' },
{ role: 'togglefullscreen' },
],
});
return Menu.buildFromTemplate([
...(process.platform === 'darwin' ? [menu_app] : []),
menu_file,
menu_edit,
menu_view,
menu_window,
menu_help,
]);
}
let app_menu = createAppMenu();
const menu_window_supports_refresh = new WeakSet<BrowserWindow>();
export function createWindowMenu(window: BrowserWindow, i18n = appinstance?.i18n) {
menu_window_supports_refresh.add(window);
const {menu_app, menu_file, menu_edit, menu_window, menu_help} = createAppMenuItems(i18n);
const menu_view = new MenuItem({
label: i18n?.t('app_menu:view') ?? 'View',
label: 'View',
submenu: [
{
id: 'window_refresh',
label: i18n?.t('app_menu:refresh') ?? 'Refresh',
label: 'Refresh',
click: (menuItem, browserWindow, event) => {
if (browserWindow && menu_window_supports_refresh.has(browserWindow)) {
if (browserWindow === window) {
browserWindow.webContents.send('nxapi:window:refresh');
} else {
browserWindow?.webContents.reload();
@ -144,30 +90,3 @@ export function createWindowMenu(window: BrowserWindow, i18n = appinstance?.i18n
menu_help,
]);
}
const menus = new WeakMap<BrowserWindow, Menu>();
app.on('browser-window-focus', (event, window) => {
Menu.setApplicationMenu(menus.get(window) ?? app_menu);
});
app.on('browser-window-blur', (event, window) => {
if (!BrowserWindow.getFocusedWindow()) {
Menu.setApplicationMenu(app_menu);
}
});
export function setWindowMenu(window: BrowserWindow, menu: Menu) {
menus.set(window, menu);
if (window.isFocused()) Menu.setApplicationMenu(app_menu);
}
export function updateMenuLanguage(i18n: i18n) {
app_menu = createAppMenu(i18n);
for (const window of BrowserWindow.getAllWindows()) {
if (!menus.has(window)) continue;
menus.set(window, createWindowMenu(window, i18n));
}
Menu.setApplicationMenu(menus.get(BrowserWindow.getFocusedWindow()!) ?? app_menu);
}

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