Sega-Channel/server/index.mjs
orca 065647af6d Server version, lineups and pixel-art screens; deployed on the OptiPlex
Commits the in-progress work that was sitting in the tree: the Node server
(server/), Dockerfile, lineups page, new pixel-art components and themes,
with the old library/ROM loaders and render.yaml removed. The README now
points at cyberdeck/optiplex/segachannel/deploy.py (the home server moved
from the Mac mini to an OptiPlex).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 20:02:16 -05:00

313 lines
11 KiB
JavaScript

// Sega Channel server: serves the built menu (dist/), EmulatorJS, the ROMs (read-only) and a small JSON API.
// No dependencies; Node 22.
//
// ROM_DIR folder of Genesis ROMs, never written to (default ./roms)
// DATA_DIR room/title edits, play counts, saves and states (default ./.data)
// EJS_DIR EmulatorJS's data/ folder (default ./emulatorjs)
// PORT (default 8080)
import { createReadStream } from 'node:fs'
import { mkdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises'
import { createServer } from 'node:http'
import { dirname, extname, join, normalize, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { ROOMS, createLibrary } from './library.mjs'
import { describeWindow, pickLineup, windowIndex } from './rotation.mjs'
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const ROM_DIR = resolve(process.env.ROM_DIR ?? join(ROOT, 'roms'))
const DATA_DIR = resolve(process.env.DATA_DIR ?? join(ROOT, '.data'))
const EJS_DIR = resolve(process.env.EJS_DIR ?? join(ROOT, 'emulatorjs'))
const DIST = join(ROOT, 'dist')
const PORT = Number(process.env.PORT ?? 8080)
const MAX_BODY = 16 * 2 ** 20
const LINEUP_SIZE = Number(process.env.LINEUP_SIZE ?? 50)
const library = createLibrary({ romDir: ROM_DIR, lineupPath: join(ROOT, 'data', 'sega-channel-lineup.json') })
// --- state.json: per-game edits and stats, keyed by game id -------------------------------------------------
const STATE_FILE = join(DATA_DIR, 'state.json')
let state = { games: {} }
let writing = Promise.resolve()
async function loadState() {
await mkdir(join(DATA_DIR, 'states'), { recursive: true })
await mkdir(join(DATA_DIR, 'saves'), { recursive: true })
try {
state = JSON.parse(await readFile(STATE_FILE, 'utf8'))
state.games ??= {}
}
catch (err) {
if (err.code !== 'ENOENT')
console.error('state.json unreadable, starting fresh:', err.message)
}
}
/** Atomic write (temp file + rename), one at a time. */
function saveState() {
writing = writing.then(async () => {
await writeFile(`${STATE_FILE}.tmp`, JSON.stringify(state, null, 1))
await rename(`${STATE_FILE}.tmp`, STATE_FILE)
}).catch(err => console.error('saving state.json failed:', err))
return writing
}
const record = id => (state.games[id] ??= {})
async function exists(path) {
return stat(path).then(() => true, () => false)
}
async function gamesWithState() {
const games = await library.scan()
return Promise.all(games.map(async (g) => {
const s = state.games[g.id] ?? {}
return {
id: g.id,
file: g.file,
title: s.title || g.title,
romTitle: g.title,
room: ROOMS.includes(s.room) ? s.room : g.defaultRoom,
defaultRoom: g.defaultRoom,
size: g.size,
addedAt: g.addedAt,
fav: !!s.fav,
plays: s.plays ?? 0,
lastPlayed: s.lastPlayed ?? 0,
hasState: await exists(join(DATA_DIR, 'states', `${g.id}.state`)),
lineup: g.lineup,
}
}))
}
/** ?at=YYYY-MM-DD previews another date's lineup; otherwise today (server time zone, TZ). */
function dateFrom(url) {
const at = /^(\d{4})-(\d{2})-(\d{2})$/.exec(url.searchParams.get('at') ?? '')
return at ? new Date(Number(at[1]), Number(at[2]) - 1, Number(at[3])) : new Date()
}
/** The library plus this window's lineup: which games are on air, and which arrive next time. */
async function libraryFor(date) {
const games = await gamesWithState()
const n = windowIndex(date)
const now = pickLineup(games, n, { size: LINEUP_SIZE })
const next = pickLineup(games, n + 1, { size: LINEUP_SIZE })
return {
games: games.map(g => ({ ...g, onAir: now.onAir.has(g.id), classic: now.classic.has(g.id) })),
window: {
...describeWindow(n),
size: now.onAir.size,
classicPeriods: now.periods.map(i => library.lineup.periods[i]),
comingSoon: games.filter(g => next.onAir.has(g.id) && !now.onAir.has(g.id)).map(g => g.id),
},
}
}
// --- HTTP helpers -----------------------------------------------------------------------------------------------
const TYPES = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.wasm': 'application/wasm',
'.zip': 'application/zip',
'.7z': 'application/x-7z-compressed',
}
function send(res, status, body, headers = {}) {
const isJson = typeof body === 'object' && !Buffer.isBuffer(body)
res.writeHead(status, { 'Content-Type': isJson ? TYPES['.json'] : 'text/plain; charset=utf-8', ...headers })
res.end(isJson ? JSON.stringify(body) : body)
}
async function readBody(req) {
const chunks = []
let size = 0
for await (const chunk of req) {
size += chunk.length
if (size > MAX_BODY)
throw Object.assign(new Error('too large'), { status: 413 })
chunks.push(chunk)
}
return Buffer.concat(chunks)
}
/** Streams a file, honouring Range requests (EmulatorJS and browsers use them for big downloads). */
async function sendFile(req, res, path, cache) {
let st
try {
st = await stat(path)
if (!st.isFile())
throw new Error('not a file')
}
catch {
return send(res, 404, 'not found')
}
const headers = {
'Content-Type': TYPES[extname(path).toLowerCase()] ?? 'application/octet-stream',
'Accept-Ranges': 'bytes',
'Last-Modified': st.mtime.toUTCString(),
'Cache-Control': cache,
}
if (req.headers['if-modified-since'] && new Date(req.headers['if-modified-since']) >= new Date(st.mtime.toUTCString())) {
res.writeHead(304, headers)
return res.end()
}
const range = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range ?? '')
if (range && (range[1] || range[2])) {
const start = range[1] ? Number(range[1]) : Math.max(0, st.size - Number(range[2]))
const end = range[1] && range[2] ? Math.min(Number(range[2]), st.size - 1) : st.size - 1
if (start > end || start >= st.size) {
res.writeHead(416, { 'Content-Range': `bytes */${st.size}` })
return res.end()
}
res.writeHead(206, { ...headers, 'Content-Range': `bytes ${start}-${end}/${st.size}`, 'Content-Length': end - start + 1 })
return req.method === 'HEAD' ? res.end() : createReadStream(path, { start, end }).pipe(res)
}
res.writeHead(200, { ...headers, 'Content-Length': st.size })
return req.method === 'HEAD' ? res.end() : createReadStream(path).pipe(res)
}
/** Joins a URL path onto a folder, refusing anything that climbs out of it. */
function within(base, urlPath) {
const path = normalize(join(base, decodeURIComponent(urlPath)))
return path === base || path.startsWith(base + '/') ? path : undefined
}
async function findGame(id) {
return (await library.scan()).find(g => g.id === id)
}
// --- routes -----------------------------------------------------------------------------------------------------
/** Save states and battery saves share one shape: GET / PUT / DELETE raw bytes. */
async function blob(req, res, id, kind) {
const path = join(DATA_DIR, kind === 'state' ? 'states' : 'saves', `${id}.${kind === 'state' ? 'state' : 'srm'}`)
if (req.method === 'GET' || req.method === 'HEAD')
return sendFile(req, res, path, 'no-store')
if (req.method === 'PUT') {
const body = await readBody(req)
if (!body.length)
return send(res, 400, 'empty')
await writeFile(`${path}.tmp`, body)
await rename(`${path}.tmp`, path)
return send(res, 200, { ok: true, size: body.length, at: Date.now() })
}
if (req.method === 'DELETE') {
await unlink(path).catch(() => {})
return send(res, 200, { ok: true })
}
return send(res, 405, 'method not allowed')
}
async function api(req, res, path, url) {
if (path === '/api/library' && req.method === 'GET') {
const lib = await libraryFor(dateFrom(url))
return send(res, 200, { ...lib, periods: library.lineup.periods, rooms: ROOMS }, { 'Cache-Control': 'no-store' })
}
if (path === '/api/lineups' && req.method === 'GET') {
const owned = new Map()
for (const g of await gamesWithState()) {
for (const t of g.lineup?.titles ?? [])
owned.set(t, g.id)
}
return send(res, 200, {
periods: library.lineup.periods,
games: library.lineup.games.map(g => ({ ...g, gameId: owned.get(g.title) ?? null })),
}, { 'Cache-Control': 'no-store' })
}
const m = /^\/api\/games\/([a-f\d]{12})(?:\/(played|state|sram))?$/.exec(path)
if (!m)
return send(res, 404, { error: 'not found' })
const [, id, action] = m
if (!await findGame(id))
return send(res, 404, { error: 'no such game' })
if (!action && req.method === 'PATCH') {
let patch
try {
patch = JSON.parse((await readBody(req)).toString() || '{}')
}
catch {
return send(res, 400, { error: 'bad json' })
}
const r = record(id)
if ('room' in patch) {
if (!ROOMS.includes(patch.room))
return send(res, 400, { error: `room must be one of ${ROOMS.join(', ')}` })
r.room = patch.room
}
if ('title' in patch)
r.title = String(patch.title ?? '').trim().slice(0, 120) || undefined
if ('fav' in patch)
r.fav = !!patch.fav || undefined
await saveState()
return send(res, 200, (await libraryFor(new Date())).games.find(g => g.id === id))
}
if (action === 'played' && req.method === 'POST') {
const r = record(id)
r.plays = (r.plays ?? 0) + 1
r.lastPlayed = Date.now()
await saveState()
return send(res, 200, { ok: true })
}
if (action === 'state' || action === 'sram')
return blob(req, res, id, action)
return send(res, 405, { error: 'method not allowed' })
}
const PAGES = { '/': 'index.html', '/play': 'play.html', '/lineups': 'lineups.html' }
const server = createServer(async (req, res) => {
const url = new URL(req.url, 'http://x')
const path = url.pathname
try {
if (path.startsWith('/api/'))
return await api(req, res, path, url)
if (req.method !== 'GET' && req.method !== 'HEAD')
return send(res, 405, 'method not allowed')
if (path.startsWith('/roms/')) {
const game = await findGame(path.slice(6).split('/')[0])
return game ? sendFile(req, res, join(ROM_DIR, game.file), 'private, max-age=86400') : send(res, 404, 'not found')
}
if (path.startsWith('/emulatorjs/')) {
const file = within(EJS_DIR, path.slice('/emulatorjs/'.length))
return file ? sendFile(req, res, file, 'public, max-age=604800') : send(res, 404, 'not found')
}
if (path === '/healthz')
return send(res, 200, 'ok')
const page = PAGES[path] ?? PAGES[path.replace(/\.html$/, '').replace(/\/$/, '') || '/']
if (page)
return sendFile(req, res, join(DIST, page), 'no-cache')
const file = within(DIST, path)
// Vite's hashed assets never change; everything else is revalidated.
return file ? sendFile(req, res, file, path.startsWith('/assets/') ? 'public, max-age=31536000, immutable' : 'no-cache') : send(res, 404, 'not found')
}
catch (err) {
console.error(req.method, path, err)
if (!res.headersSent)
send(res, err.status ?? 500, err.status ? err.message : 'server error')
else
res.destroy()
}
})
await loadState()
server.listen(PORT, () => console.log(`sega channel on :${PORT} · roms ${ROM_DIR} · data ${DATA_DIR}`))
for (const sig of ['SIGTERM', 'SIGINT'])
process.on(sig, () => writing.finally(() => process.exit(0)))