Sega-Channel/server/library.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

171 lines
7 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// The game list: every ROM in ROM_DIR, titled from its No-Intro file name and matched against the
// archived 1996–97 Sega Channel lineups (data/sega-channel-lineup.json) to pick its room.
import { createHash } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { readdir, stat } from 'node:fs/promises'
import { join } from 'node:path'
export const ROM_EXTENSIONS = ['.zip', '.bin', '.gen', '.md', '.smd', '.7z']
/** Rooms a game can be filed under. Keep in sync with ASSIGNABLE in src/lib/categories.ts. */
export const ROOMS = ['arcade', 'shooters', 'strategy', 'wheels', 'dungeon', 'sports', 'family', 'picks']
// Archive room names -> this app's rooms. "Test Drives" and "Sega Channel Exclusives" were rotating
// showcases, so a game only lands there if it was never listed anywhere else.
const ARCHIVE_ROOMS = {
'the arcade': 'arcade',
'sharp shooters': 'shooters',
'super games': 'arcade',
'strategy room': 'strategy',
'think tank': 'strategy',
'wings & wheels': 'wheels',
'the dungeon': 'dungeon',
'sports arena': 'sports',
'family room': 'family',
'disney picks': 'family',
'picks of \'96': 'picks',
'test drives': 'arcade',
'sega channel exclusives': 'arcade',
}
const SHOWCASE = new Set(['test drives', 'sega channel exclusives'])
// Rooms for games that never appeared in an archived lineup, keyed by matchKey(title).
// Anything not listed (a ROM added later) starts in The Arcade and can be refiled in the Control Room.
const DEFAULT_ROOMS = {
shooters: [
'Advanced Busterhawk Gleylancer', 'Air Buster', 'Battle Mania Daiginjou', 'Elemental Master', 'Fire Shark',
'Gynoug', 'MUSHA: Metallic Uniframe Super Hybrid Armor', 'Panorama Cotton', 'Steel Empire', 'Super Fantasy Zone', 'Truxton', 'Twinkle Tale',
'Undead Line', 'Arrow Flash', 'Galaxy Force II', 'Thunder Force IV', 'Thunder Force III', 'Lightening Force',
],
strategy: [
'Cannon Fodder', 'Columns III', 'Dune: The Battle for Arrakis', 'General Chaos', 'Herzog Zwei',
'Langrisser II', 'The Lost Vikings', 'Out of This World', 'Pepenga Pengo', 'Puggsy',
],
wheels: ['Desert Strike: Return to the Gulf', 'Outlander', 'Technocop', 'Battletech: A Game of Armored Combat'],
dungeon: [
'Buck Rogers: Countdown to Doomsday', 'Crusader of Centy', 'Gauntlet IV', 'Light Crusader', 'Monster World IV',
'Phantasy Star III: Generations of Doom', 'Wonder Boy in Monster World',
],
sports: [
'Greatest Heavyweights', 'Mutant League Football', 'Mutant League Hockey', 'NBA Jam: Tournament Edition',
'Speedball 2: Brutal Deluxe',
],
family: [
'Alex Kidd in the Enchanted Castle', 'Flicky', 'Haunting Starring Polterguy', 'James Pond: Underwater Agent',
'James Pond 3', 'James Pond II: Codename: Robocod', 'Sonic Spinball', 'Taz in Escape from Mars', 'Taz-Mania',
'ToeJam & Earl in Panic on Funkotron', 'Toy Story', 'Wiz \'N\' Liz', 'World of Illusion Starring Mickey Mouse and Donald Duck',
'Psycho Pinball',
],
picks: ['Sonic The Hedgehog 2', 'Streets of Rage 2', 'ToeJam & Earl', 'Contra: Hard Corps'],
}
// ROM title -> lineup title, where the names differ by more than punctuation or a subtitle.
const ALIASES = {
'Donald in Maui Mallard': 'Maui Mallard in Cold Shadow',
'Granada': 'Granada X',
'QuackShot Starring Donald Duck': 'Quackshot',
'Sub-Terrania': 'Subterrania',
}
/** Loose comparison key: case, punctuation, "The", "Disney's" and & vs "and" don't matter. */
export function matchKey(title) {
return title
.toLowerCase()
.replace(/&/g, ' and ')
.replace(/\bdisney's\b/g, '')
.replace(/^\s*the\s+/, '')
.replace(/[^a-z\d]+/g, '')
}
/**
* "Lost World, The - Jurassic Park (USA, Europe).zip" -> "The Lost World: Jurassic Park".
* Returns the display title plus every name the ROM goes by (for "A ~ B" Japanese/US pairs and
* "A + B" combo carts), so each can be matched against the lineup.
*/
export function titleFromFile(file) {
const base = file
.replace(/\.[^.]+$/, '')
.replace(/\s*[([][^)\]]*[)\]]/g, '')
.trim()
const names = base.split(/\s+[~+]\s+/).map((part) => {
const segs = part.split(' - ').map(s => s.replace(/^(.*), The$/, 'The $1').trim())
return segs.join(': ')
})
// For "Japanese ~ English" names the English one comes last; for "A + B" carts keep the whole thing.
const title = base.includes(' + ') ? names.join(' + ') : names[names.length - 1]
return { title: title || file, names }
}
function loadLineup(path) {
const raw = JSON.parse(readFileSync(path, 'utf8'))
const periods = raw.periods
const games = raw.games.map(g => ({
title: g.title,
rooms: g.rooms,
p: g.periods.map(p => periods.indexOf(p)).filter(i => i >= 0),
exclusive: g.exclusive,
rating: g.rating,
note: g.note ?? null,
source: g.sources?.[0] ?? null,
}))
const byKey = new Map()
for (const g of games) {
byKey.set(matchKey(g.title), g)
// "Landstalker: The Treasures of King Nole" also answers to "Landstalker".
const main = g.title.split(':')[0]
if (main !== g.title && !byKey.has(matchKey(main)))
byKey.set(matchKey(main), g)
}
return { periods, games, byKey }
}
function roomFor(lineupGames) {
const rooms = lineupGames.flatMap(g => g.rooms)
const real = rooms.find(r => !SHOWCASE.has(r.toLowerCase()) && ARCHIVE_ROOMS[r.toLowerCase()])
return ARCHIVE_ROOMS[(real ?? rooms[0] ?? '').toLowerCase()]
}
const defaultRoom = new Map(
Object.entries(DEFAULT_ROOMS).flatMap(([room, titles]) => titles.map(t => [matchKey(t), room])),
)
export function createLibrary({ romDir, lineupPath }) {
const lineup = loadLineup(lineupPath)
let cache = { at: 0, games: [] }
async function scan() {
// Rescan at most every 15 s; the folder only changes when ROMs are copied in.
if (Date.now() - cache.at < 15_000)
return cache.games
const files = (await readdir(romDir, { withFileTypes: true }))
.filter(d => d.isFile() && ROM_EXTENSIONS.some(ext => d.name.toLowerCase().endsWith(ext)))
.map(d => d.name)
const games = await Promise.all(files.map(async (file) => {
const st = await stat(join(romDir, file))
const { title, names } = titleFromFile(file)
const matched = [...new Set(names.map(n => lineup.byKey.get(matchKey(ALIASES[n] ?? n))).filter(Boolean))]
return {
id: createHash('sha1').update(file).digest('hex').slice(0, 12),
file,
title,
size: st.size,
addedAt: Math.round(st.mtimeMs),
defaultRoom: roomFor(matched) ?? defaultRoom.get(matchKey(title)) ?? 'arcade',
lineup: matched.length
? {
titles: matched.map(g => g.title),
p: [...new Set(matched.flatMap(g => g.p))].sort((a, b) => a - b),
exclusive: matched.some(g => g.exclusive),
rating: matched.find(g => g.rating)?.rating ?? null,
note: matched.find(g => g.note)?.note ?? null,
}
: null,
}
}))
cache = { at: Date.now(), games }
return games
}
return { scan, lineup, invalidate: () => (cache.at = 0) }
}