Skip to content

feat(plugins/community/splatoon): add plugin #1287

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 16 commits into from
Nov 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/actions/spelling/allow.txt
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
deno
gpgarmor
github
https
leetcode
pgn
scm
shas
splatoon
ssh
ubuntu
yargsparser
2 changes: 2 additions & 0 deletions .github/actions/spelling/excludes.txt
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,10 @@ ignore$
^\.github/actions/spelling/
^\Q.github/readme/partials/documentation/inspirations.md\E$
^\Q.github/workflows/spelling.yml\E$
^source/plugins/community/splatoon/
^\Qsource/plugins/sponsors/index.mjs\E$
^\Qsource/plugins/stargazers/worldmap/atlas/50m_countries.geojson\E$
^\Qsource/templates/classic/partials/splatoon.ejs\E$
^\Qsource/templates/terminal/fonts.css\E$
^\Qsource/templates/terminal/partials/screenshot.ejs\E$
^\Qtests/mocks/api/github/rest/emojis/get.mjs\E$
Expand Down
Binary file added .github/readme/imgs/plugin_splatoon_auth.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added .github/readme/imgs/plugin_splatoon_script.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ RUN chmod +x /metrics/source/app/action/index.mjs \
&& sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \
&& apt-get update \
&& apt-get install -y google-chrome-stable fonts-ipafont-gothic fonts-wqy-zenhei fonts-thai-tlwg fonts-kacst fonts-freefont-ttf libxss1 libx11-xcb1 libxtst6 lsb-release --no-install-recommends \
# Install deno for miscellaneous scripts
&& apt-get install -y curl unzip \
&& curl -fsSL https://deno.land/x/install/install.sh | DENO_INSTALL=/usr/local sh \
# Install ruby to support github licensed gem
&& apt-get install -y ruby-full git g++ cmake pkg-config libssl-dev \
&& gem install licensed \
Expand Down
3 changes: 3 additions & 0 deletions source/app/metrics/utils.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,9 @@ export const filters = {

/**Image to base64 */
export async function imgb64(image, {width, height, fallback = true} = {}) {
//Ignore already encoded-base 64
if ((typeof image === "string")&&(image.startsWith("data:image/png;base64")))
return image
//Undefined image
if (!image)
return fallback ? "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mOcOnfpfwAGfgLYttYINwAAAABJRU5ErkJggg==" : null
Expand Down
25 changes: 25 additions & 0 deletions source/plugins/community/splatoon/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<!--header-->
<!--/header-->

## ➡️ Available options

<!--options-->
<!--/options-->

## 🗝️ Obtaining a *Nintendo Switch Online* token

The helper script is intended to be run by [deno runtime](https://deno.land/). Either [install it locally](https://deno.land/manual/getting_started/installation) or use its [docker image](https://hub.docker.com/r/denoland/deno).

Run the following command in your terminal and follow instructions:
```bash
deno run --allow-run=deno --allow-read=profile.json --allow-write=profile.json --unstable https://raw.githubusercontent.com/lowlighter/metrics/master/source/plugins/community/splatoon/token.ts
```

![Script](/.github/readme/imgs/plugin_splatoon_script.png)

![Authentication](/.github/readme/imgs/plugin_splatoon_auth.png)

## ℹ️ Examples workflows

<!--examples-->
<!--/examples-->
164 changes: 164 additions & 0 deletions source/plugins/community/splatoon/assets.mjs

Large diffs are not rendered by default.

12 changes: 12 additions & 0 deletions source/plugins/community/splatoon/examples.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
- name: Example
uses: lowlighter/metrics@latest
with:
filename: metrics.plugin.splatoon.svg
token: ${{ secrets.METRICS_TOKEN }}
base: ""
plugin_splatoon: yes
plugin_splatoon_token: ${{ secrets.SPLATOON_TOKEN }}
test:
skip: true
prod:
skip: true
147 changes: 147 additions & 0 deletions source/plugins/community/splatoon/index.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
//Imports
import assets from "./assets.mjs"

//Setup
export default async function({login, q, imports, data, account}, {enabled = false, extras = false, token} = {}) {
//Plugin execution
try {
//Check if plugin is enabled and requirements are met
if ((!q.splatoon) || (!imports.metadata.plugins.splatoon.enabled(enabled, {extras})))
return null

//Load inputs
const {modes, "versus.limit":_versus_limit, "salmon.limit":_salmon_limit} = imports.metadata.plugins.splatoon.inputs({data, account, q})

//Save profile
{
const profile = `${imports.__module(import.meta.url)}/s3si/profile.json`
console.debug(`metrics/compute/${login}/plugins > splatoon > saving ${profile}`)
const parsed = JSON.parse(token)
if (!parsed?.loginState?.sessionToken)
throw new Error("Configuration is missing sessionToken")
await imports.fs.writeFile(profile, token)
}

//Fetch data
const allowed = {
files:["profile.json", "profile.json.swap", "export", "cache"],
net:["api.imink.app", "accounts.nintendo.com", "api.accounts.nintendo.com", "api-lp1.znc.srv.nintendo.net", "api.lp1.av5ja.srv.nintendo.net"]
}
await imports.run(`deno run --no-prompt --cached-only --no-remote --allow-read="${allowed.files}" --allow-write="${allowed.files}" --allow-net="${allowed.net}" index.ts --exporter file --no-progress`, {cwd: `${imports.__module(import.meta.url)}/s3si`}, {prefixed:false})

//Read fetched data
const fetched = (await Promise.all(
(await imports.fs.readdir(`${imports.__module(import.meta.url)}/s3si/export`))
.map(async file => JSON.parse(await imports.fs.readFile(`${imports.__module(import.meta.url)}/s3si/export/${file}`)))))
.sort((a, b) => new Date(b.data.detail.playedTime) - new Date(a.data.detail.playedTime))
console.debug(`metrics/compute/${login}/plugins > splatoon > fetched ${fetched.length} matches`)

//Versus mode
let vs = null
if (!((modes.length === 1)&&(modes[0] === "salmon-run"))) {
vs = {
matches:await Promise.all(fetched.filter(({type, data}) => (type === "VS")&&(modes.includes(data.detail.vsRule.name.toLocaleLowerCase().replace(/ /g, "-")))).slice(0, _versus_limit).map(async ({data}) => ({
mode:{
name:data.detail.vsRule.name,
icon:await imports.imgb64(assets.modes[data.detail.vsRule.name]),
},
result:data.detail.judgement,
knockout:data.detail.knockout ?? null,
teams:await Promise.all([data.detail.myTeam, ...data.detail.otherTeams].map(async team => ({
color:`#${Math.round(255*team.color.r).toString(16)}${Math.round(255*team.color.g).toString(16)}${Math.round(255*team.color.b).toString(16)}`,
score:((data.detail.vsRule.name === "Turf War") ? team.result?.paintRatio*100 : team.result?.score) ?? null,
players:await Promise.all(team.players.map(async ({name, byname, weapon, paint, result, isMyself:self}) => ({
name,
byname,
self,
weapon:{
name:weapon.name,
icon:await imports.imgb64(assets.weapons[weapon.name]),
},
special:{
name:weapon.specialWeapon.name,
icon:await imports.imgb64(assets.specials[weapon.specialWeapon.name]),
},
sub:{
name:weapon.subWeapon.name,
icon:await imports.imgb64(assets.subweapons[weapon.subWeapon.name]),
},
result:{
paint:paint ?? 0,
kill:result?.kill ?? 0,
death:result?.death ?? 0,
assist:result?.assist ?? 0,
special:result?.special ?? 0,
}
})))
}))),
awards:data.detail.awards,
date:data.detail.playedTime,
duration:data.detail.duration,
player:{
name:data.detail.player.name,
byname:data.detail.player.byname,
rank:data.listNode?.udemae ?? null,
},
stage:{
name:data.detail.vsStage.name,
icon:await imports.imgb64(assets.stages[data.detail.vsStage.name]),
}
})))
}
vs.player = vs.matches.at(-1)?.player ?? null
}

//Salmon run
let salmon = null
if (modes.includes("salmon-run")) {
salmon = {
matches:await Promise.all(fetched.filter(({type}) => type === "COOP").slice(0, _salmon_limit).map(async ({data}) => ({
weapons:await Promise.all(data.detail.myResult.weapons.map(async ({name}) => ({name, icon:await imports.imgb64(assets.weapons[name])}))),
special:{
name:data.detail.myResult.specialWeapon.name,
icon:await imports.imgb64(assets.specials[data.detail.myResult.specialWeapon.name])
},
eggs:{
golden:data.detail.myResult.goldenDeliverCount,
regular:data.detail.myResult.deliverCount,
},
defeated:await Promise.all(data.detail.enemyResults.map(async ({defeatCount:count, enemy:{name}}) => ({name, count, icon:await imports.imgb64(assets.salmon[name])}))),
rescues:data.detail.myResult.rescueCount,
rescued:data.detail.myResult.rescuedCount,
waves:data.detail.waveResults.map(({deliverNorm:quota, teamDeliverCount:delivered}) => ({quota, delivered})),
failed:data.detail.resultWave,
hazard:Math.round(data.detail.dangerRate*100),
boss:data.detail.bossResult ? {
defeated:data.detail.bossResult.hasDefeatBoss,
name:data.detail.bossResult.boss.name,
icon:await imports.imgb64(assets.salmon[data.detail.bossResult.boss.name])
} : null,
stage:{
name:data.detail.coopStage.name,
icon:await imports.imgb64(assets.stages[data.detail.coopStage.name])
},
date:data.detail.playedTime,
grade:data.detail.afterGrade.name,
player:data.detail.myResult.player.name,
}))),
}
salmon.player = {
name:salmon.matches.at(-1)?.player ?? null,
grade:salmon.matches.at(-1)?.grade ?? null,
}
}

//Results
return {
vs,
salmon,
icons:Object.fromEntries(await Promise.all(Object.entries(assets.icons).map(async ([k, v]) => [k, await imports.imgb64(v)])))
}
}
//Handle errors
catch (error) {
throw imports.format.error(error)
}
}

64 changes: 64 additions & 0 deletions source/plugins/community/splatoon/metadata.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
name: 🦑 Splatoon
category: community
description: |
This plugin displays your Splatoon 3 recent matches based on data fetched from Splatnet.
disclaimer: |
This plugin is not affiliated, associated, authorized, endorsed by, or in any way officially connected with [Nintendo](https://www.nintendo.com) or [Splatoon](https://splatoon.nintendo.com).
All product and company names are trademarks™ or registered® trademarks of their respective holders.

This specific plugin is licensed under GPL-3.0 rather than MIT to comply with [spacemeowx2/s3si.ts](https://github.com/spacemeowx2/s3si.ts) license.

Note that *Nintendo Switch Online* web tokens usage are not explicitly allowed by *Nintendo*, use at your own risk.
examples:
default: https://github.com/lowlighter/metrics/blob/examples/metrics.plugin.splatoon.svg
authors:
- lowlighter
supports:
- user
- organization
scopes: []
inputs:

plugin_splatoon:
description: |
Enable splatoon plugin
type: boolean
default: no

plugin_splatoon_token:
description: |
Splatnet token
type: token
default: ""
extras:
- metrics.api.nintendo.splatnet

plugin_splatoon_modes:
description: |
Displayed modes
type: array
format: comma-separated
default: turf-war, splat-zones, tower-control, rainmaker, clam-blitz, salmon-run
options:
- turf-war
- splat-zones
- tower-control
- rainmaker
- clam-blitz
- salmon-run

plugin_splatoon_versus_limit:
description: |
Display limit (Versus)
type: number
default: 1
min: 0
max: 6

plugin_splatoon_salmon_limit:
description: |
Display limit (Salmon run)
type: number
default: 1
min: 0
max: 6
3 changes: 3 additions & 0 deletions source/plugins/community/splatoon/s3si/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
cache
export
profile.json
Loading