meow && add song of the day!
This commit is contained in:
+124
-3
@@ -1,4 +1,7 @@
|
||||
import crypto from 'node:crypto'
|
||||
import fs from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { defineConfig, loadEnv } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
@@ -35,6 +38,102 @@ function obfuscate() {
|
||||
|
||||
const MAX_TEAM_NAME_LENGTH = 80
|
||||
|
||||
function expandHome(filePath) {
|
||||
if (filePath === '~') return os.homedir()
|
||||
if (filePath.startsWith(`~${path.sep}`)) return path.join(os.homedir(), filePath.slice(2))
|
||||
if (filePath.startsWith('~/')) return path.join(os.homedir(), filePath.slice(2))
|
||||
return filePath
|
||||
}
|
||||
|
||||
function devSongHistoryPath(env) {
|
||||
const storageDir = path.resolve(expandHome(env.UPTIME_STORAGE_DIR || '~/tsswebstorage'))
|
||||
return path.join(storageDir, env.LASTFM_HISTORY_FILE || 'lastfm-song-of-day.json')
|
||||
}
|
||||
|
||||
function readDevSongHistory(env) {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(devSongHistoryPath(env), 'utf8'))
|
||||
} catch {
|
||||
return { picks: [] }
|
||||
}
|
||||
}
|
||||
|
||||
function writeDevSongHistory(env, history) {
|
||||
const filePath = devSongHistoryPath(env)
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true })
|
||||
fs.writeFileSync(filePath, JSON.stringify(history, null, 2))
|
||||
}
|
||||
|
||||
function normalizeLastfmTrack(track) {
|
||||
const artist = track?.artist?.['#text'] || track?.artist?.name || ''
|
||||
const name = track?.name || ''
|
||||
if (!artist || !name) return null
|
||||
|
||||
const images = Array.isArray(track.image) ? track.image : []
|
||||
const image = [...images].reverse().find((item) => item?.['#text'])
|
||||
|
||||
return {
|
||||
id: `${artist.toLowerCase()}::${name.toLowerCase()}`,
|
||||
artist,
|
||||
name,
|
||||
album: track?.album?.['#text'] || '',
|
||||
url: track?.url || '',
|
||||
image: image?.['#text'] || '',
|
||||
played_at: track?.date?.uts ? Number(track.date.uts) : null,
|
||||
}
|
||||
}
|
||||
|
||||
async function devSongOfTheDay(env) {
|
||||
const apiKey = env.LASTFM_API_KEY || ''
|
||||
const username = env.LASTFM_USERNAME || ''
|
||||
if (!apiKey || !username) {
|
||||
return { status: 503, body: { configured: false, error: 'Last.fm is not configured' } }
|
||||
}
|
||||
|
||||
const date = new Date().toISOString().slice(0, 10)
|
||||
const history = readDevSongHistory(env)
|
||||
const existing = (history.picks || []).find((pick) => pick.date === date)
|
||||
if (existing?.track) {
|
||||
return { status: 200, body: { configured: true, date, track: existing.track } }
|
||||
}
|
||||
|
||||
const to = Math.floor(Date.now() / 1000)
|
||||
const from = to - 7 * 24 * 60 * 60
|
||||
const url = new URL('https://ws.audioscrobbler.com/2.0/')
|
||||
url.searchParams.set('method', 'user.getrecenttracks')
|
||||
url.searchParams.set('user', username)
|
||||
url.searchParams.set('api_key', apiKey)
|
||||
url.searchParams.set('format', 'json')
|
||||
url.searchParams.set('from', String(from))
|
||||
url.searchParams.set('to', String(to))
|
||||
url.searchParams.set('limit', '200')
|
||||
|
||||
const response = await fetch(url)
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`)
|
||||
const data = await response.json()
|
||||
const tracks = (data?.recenttracks?.track || []).map(normalizeLastfmTrack).filter(Boolean)
|
||||
const uniqueTracks = Array.from(new Map(tracks.map((track) => [track.id, track])).values())
|
||||
if (!uniqueTracks.length) {
|
||||
return { status: 503, body: { configured: true, date, error: 'No Last.fm tracks found from the last week' } }
|
||||
}
|
||||
|
||||
const previousIds = new Set((history.picks || []).map((pick) => pick.track?.id).filter(Boolean))
|
||||
const available = uniqueTracks.filter((track) => !previousIds.has(track.id))
|
||||
const pool = available.length ? available : uniqueTracks
|
||||
const track = pool[crypto.randomInt(0, pool.length)]
|
||||
const nextHistory = {
|
||||
picks: [
|
||||
...(history.picks || []).filter((pick) => pick.date !== date),
|
||||
{ date, track },
|
||||
]
|
||||
.sort((a, b) => String(a.date).localeCompare(String(b.date)))
|
||||
.slice(-366),
|
||||
}
|
||||
writeDevSongHistory(env, nextHistory)
|
||||
|
||||
return { status: 200, body: { configured: true, date, track } }
|
||||
}
|
||||
|
||||
function sri() {
|
||||
return {
|
||||
name: 'sri',
|
||||
@@ -77,6 +176,7 @@ function isAllowedApiUrl(req) {
|
||||
|
||||
if (url.pathname === '/api/viewers' && (req.method === 'GET' || req.method === 'HEAD')) return true
|
||||
if (url.pathname === '/api/viewers/event' && req.method === 'POST') return true
|
||||
if (url.pathname === '/api/lastfm/song-of-day' && (req.method === 'GET' || req.method === 'HEAD')) return true
|
||||
|
||||
if (req.method !== 'GET' && req.method !== 'HEAD') return false
|
||||
|
||||
@@ -117,16 +217,37 @@ function isAllowedApiUrl(req) {
|
||||
}
|
||||
}
|
||||
|
||||
function apiGuard() {
|
||||
function apiGuard(env) {
|
||||
return {
|
||||
name: 'api-guard',
|
||||
configureServer(server) {
|
||||
server.middlewares.use((req, res, next) => {
|
||||
server.middlewares.use(async (req, res, next) => {
|
||||
if (!req.url?.startsWith('/api/')) {
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
const url = new URL(req.url, 'http://localhost')
|
||||
if (url.pathname === '/api/lastfm/song-of-day' && req.method === 'GET') {
|
||||
try {
|
||||
const result = await devSongOfTheDay(env)
|
||||
res.writeHead(result.status, {
|
||||
'content-type': 'application/json; charset=utf-8',
|
||||
'cache-control': 'no-store',
|
||||
'x-content-type-options': 'nosniff',
|
||||
})
|
||||
res.end(JSON.stringify(result.body))
|
||||
} catch (error) {
|
||||
res.writeHead(502, {
|
||||
'content-type': 'application/json; charset=utf-8',
|
||||
'cache-control': 'no-store',
|
||||
'x-content-type-options': 'nosniff',
|
||||
})
|
||||
res.end(JSON.stringify({ error: 'Last.fm request failed', detail: error.message }))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (isAllowedApiUrl(req)) {
|
||||
next()
|
||||
return
|
||||
@@ -198,7 +319,7 @@ export default defineConfig(({ mode }) => {
|
||||
const comingSoon = String(env.comingsoon || env.COMINGSOON || '').toLowerCase() === 'true'
|
||||
|
||||
return {
|
||||
plugins: [comingSoonDev(comingSoon), apiGuard(), react(), tailwindcss(), obfuscate(), sri()],
|
||||
plugins: [comingSoonDev(comingSoon), apiGuard(env), react(), tailwindcss(), obfuscate(), sri()],
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
port: 3001,
|
||||
|
||||
Reference in New Issue
Block a user