Страница импорта и звуковые эффекты из файлов

- метаданные пака (название, id, финал) читаются из самого CSV
- страница /import/<токен>: перетащить таблицу, проверить, сохранить
- пак применяется без перезапуска сервера, если партия не начата
- звуки берутся из content/sfx/, иначе используется синтез
- заголовок таблицы ищется по содержимому, а не по позиции
This commit is contained in:
oskarvitalii committed 2026-11-16 15:19:58 +07:00
1 parent 2f0263e59b
commit ea2d5d905c
21 files changed
+1529 -88

No files matched your search

+117 -8
View File
@@ -7,14 +7,16 @@
*/
import { randomBytes } from 'node:crypto'
import { existsSync } from 'node:fs'
import { existsSync, readdirSync } from 'node:fs'
import path from 'node:path'
import fastifyStatic from '@fastify/static'
import Fastify, { type FastifyInstance } from 'fastify'
import { Server } from 'socket.io'
import type { AuthPayload, Pack } from '@quiz/shared'
import { EVENTS, makeRoomCode } from '@quiz/shared'
import { importPack } from './importing'
import { Room } from './room'
import { SFX_NAMES, scanSfx } from './sfx'
export interface AppOptions {
packs: Pack[]
@@ -23,8 +25,10 @@ export interface AppOptions {
hostToken?: string
/** Каталог собранного интерфейса (packages/web/dist). */
staticDir?: string
/** Каталог с медиа (content/media). */
mediaDir?: string
/** Корень контента: здесь лежат packs/, media/ и sfx/. */
contentDir?: string
/** Перечитать паки с диска: нужен после импорта, без перезапуска сервера. */
reloadPacks?: () => Pack[]
tickMs?: number
logger?: boolean
}
@@ -39,6 +43,18 @@ export interface BuiltApp {
close: () => Promise<void>
}
function listFolders(dir: string | undefined): string[] {
if (!dir || !existsSync(dir)) return []
try {
return readdirSync(dir, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name)
.sort()
} catch {
return []
}
}
export async function buildApp(options: AppOptions): Promise<BuiltApp> {
const pack = options.packId
? options.packs.find((candidate) => candidate.id === options.packId)
@@ -52,6 +68,11 @@ export async function buildApp(options: AppOptions): Promise<BuiltApp> {
const roomCode = (options.roomCode ?? makeRoomCode()).toUpperCase()
const hostToken = options.hostToken ?? randomBytes(6).toString('hex')
const contentDir = options.contentDir
const packsDir = contentDir ? path.join(contentDir, 'packs') : undefined
const mediaDir = contentDir ? path.join(contentDir, 'media') : undefined
const sfxDir = contentDir ? path.join(contentDir, 'sfx') : undefined
const app = Fastify({ logger: options.logger ?? false })
const io = new Server(app.server, {
serveClient: false,
@@ -92,18 +113,39 @@ export async function buildApp(options: AppOptions): Promise<BuiltApp> {
if (options.staticDir && existsSync(options.staticDir)) {
await app.register(fastifyStatic, { root: options.staticDir })
}
if (options.mediaDir && existsSync(options.mediaDir)) {
if (mediaDir && existsSync(mediaDir)) {
await app.register(fastifyStatic, {
root: options.mediaDir,
root: mediaDir,
prefix: '/media/',
decorateReply: false,
})
}
if (sfxDir && existsSync(sfxDir)) {
await app.register(fastifyStatic, {
root: sfxDir,
prefix: '/sfx/',
decorateReply: false,
})
}
// Файл пака приходит сырыми байтами: кодировку определяет сервер.
const rawParser = (
_request: unknown,
body: Buffer,
done: (error: Error | null, result: Buffer) => void,
): void => {
done(null, body)
}
app.addContentTypeParser('application/octet-stream', { parseAs: 'buffer' }, rawParser)
app.addContentTypeParser('text/csv', { parseAs: 'buffer' }, rawParser)
// Запросы без тела (кнопка «применить пак») приходят с произвольным или пустым
// Content-Type; без этого Fastify отвечает 415 ещё до обработчика.
app.addContentTypeParser('*', { parseAs: 'buffer' }, rawParser)
app.get('/health', async () => ({
ok: true,
room: roomCode,
pack: pack.id,
pack: room.pack.id,
phase: room.state.phase,
players: room.state.players.length,
}))
@@ -116,12 +158,79 @@ export async function buildApp(options: AppOptions): Promise<BuiltApp> {
})),
)
// Пак берём у комнаты, а не из настроек сборки: его можно подменить импортом.
app.get('/api/room', async () => ({
code: roomCode,
pack: pack.id,
title: pack.title,
pack: room.pack.id,
title: room.pack.title,
}))
/** Какие звуковые эффекты подменены файлами из content/sfx. */
app.get('/api/sfx', async () => ({ files: scanSfx(sfxDir), names: SFX_NAMES }))
app.get('/api/import/info', async (request, reply) => {
const token = (request.query as { token?: string }).token
if (token !== hostToken) {
return reply.code(403).send({ ok: false, error: 'нужен токен ведущего' })
}
return {
ok: true,
canImport: Boolean(packsDir),
packs: options.packs.map((candidate) => ({
id: candidate.id,
title: candidate.title,
rounds: candidate.rounds.length,
cells: candidate.rounds.reduce(
(sum, round) => sum + round.themes.reduce((n, theme) => n + theme.cells.length, 0),
0,
),
})),
mediaFolders: listFolders(mediaDir),
sfx: scanSfx(sfxDir),
sfxNames: SFX_NAMES,
}
})
app.post('/api/import', async (request, reply) => {
const query = request.query as { token?: string; dry?: string }
if (query.token !== hostToken) {
return reply.code(403).send({ ok: false, error: 'нужен токен ведущего' })
}
if (!packsDir || !contentDir) {
return reply.code(500).send({ ok: false, error: 'сервер не знает, где лежит контент' })
}
if (!Buffer.isBuffer(request.body)) {
return reply.code(400).send({ ok: false, error: 'ожидался файл таблицы' })
}
const outcome = importPack(
request.body,
{ packsDir, contentDir },
// dry=1 — только проверка: файл не пишется, пак не подменяется.
{ write: query.dry !== '1' },
)
return reply.send(outcome)
})
/** Взять свежеимпортированный пак в игру, не перезапуская сервер. */
app.post('/api/packs/apply', async (request, reply) => {
const query = request.query as { token?: string; id?: string }
if (query.token !== hostToken) {
return reply.code(403).send({ ok: false, error: 'нужен токен ведущего' })
}
const fresh = options.reloadPacks ? options.reloadPacks() : options.packs
const next = query.id ? fresh.find((candidate) => candidate.id === query.id) : fresh[0]
if (!next) {
return reply.code(404).send({ ok: false, error: `пак «${query.id ?? ''}» не найден` })
}
const applied = room.usePack(next)
if (!applied.ok) return reply.code(409).send({ ok: false, error: applied.reason })
return { ok: true, pack: { id: next.id, title: next.title }, phase: room.state.phase }
})
// SPA: /board, /play и /host/<token> — это маршруты одного приложения.
app.setNotFoundHandler((request, reply) => {
const url = request.raw.url ?? ''
+111
View File
@@ -0,0 +1,111 @@
/**
* Приём пака из браузера.
*
* Файл приходит сырыми байтами, а не текстом: кодировку (UTF-8 или
* Windows-1251) определяет сервер, иначе русский Excel приезжал бы кракозябрами.
*/
import { existsSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import type { Pack } from '@quiz/shared'
import { decodeTable, parsePack, tableToPack } from '@quiz/shared'
export interface ImportContext {
packsDir: string
contentDir: string
/** Ограничение размера: защита от случайно загруженного видео. */
maxBytes?: number
}
export type ImportOutcome =
| {
ok: true
pack: Pack
stats: { rounds: number; themes: number; cells: number }
encoding: string
/** Медиа, которых нет на диске: играть можно, но вопрос сыграет в тишину. */
missingMedia: string[]
written: boolean
file?: string
/** Пак с таким id уже был — его перезаписали. */
replaced: boolean
}
| { ok: false; errors: Array<{ line: number; message: string }> }
const DEFAULT_MAX_BYTES = 5 * 1024 * 1024
/** Все пути к медиа в паке. */
function mediaSources(pack: Pack): string[] {
const sources: string[] = []
for (const round of pack.rounds) {
for (const theme of round.themes) {
for (const cell of theme.cells) {
if (cell.question.media) sources.push(cell.question.media.src)
}
}
}
if (pack.final?.question.media) sources.push(pack.final.question.media.src)
return sources
}
function missingMedia(pack: Pack, contentDir: string): string[] {
const missing: string[] = []
for (const source of mediaSources(pack)) {
const relative = source.replace(/^\/media\//, '')
const full = path.join(contentDir, 'media', relative)
if (!existsSync(full)) missing.push(source)
}
return missing
}
export function importPack(
bytes: Uint8Array,
context: ImportContext,
options: { write: boolean },
): ImportOutcome {
const limit = context.maxBytes ?? DEFAULT_MAX_BYTES
if (bytes.length === 0) {
return { ok: false, errors: [{ line: 0, message: 'файл пустой' }] }
}
if (bytes.length > limit) {
return {
ok: false,
errors: [
{
line: 0,
message: `файл больше ${Math.round(limit / 1024 / 1024)} МБ — похоже, это не таблица`,
},
],
}
}
const { text, encoding } = decodeTable(bytes)
const parsed = tableToPack(text)
if (!parsed.ok) return { ok: false, errors: parsed.errors }
// Импортёр старается, но последнее слово — за схемой, с которой живёт игра.
const validated = parsePack(parsed.pack)
if (!validated.ok) {
return { ok: false, errors: validated.errors.map((message) => ({ line: 0, message })) }
}
const pack = validated.pack
const missing = missingMedia(pack, context.contentDir)
const file = path.join(context.packsDir, `${pack.id}.json`)
const replaced = existsSync(file)
if (options.write) {
writeFileSync(file, `${JSON.stringify(pack, null, 2)}\n`, 'utf8')
}
return {
ok: true,
pack,
stats: parsed.stats,
encoding,
missingMedia: missing,
written: options.write,
file: path.basename(file),
replaced,
}
}
+3 -2
View File
@@ -16,7 +16,6 @@ const here = path.dirname(fileURLToPath(import.meta.url))
const repoRoot = path.resolve(here, '../../..')
const contentDir = process.env.QUIZ_CONTENT ?? path.join(repoRoot, 'content')
const staticDir = path.join(repoRoot, 'packages/web/dist')
const mediaDir = path.join(contentDir, 'media')
const { packs, problems } = loadPacks(contentDir)
@@ -37,7 +36,9 @@ const built = await buildApp({
roomCode: process.env.QUIZ_ROOM,
hostToken: process.env.QUIZ_HOST_TOKEN,
staticDir,
mediaDir,
contentDir,
// Импорт из браузера не должен требовать перезапуска сервера.
reloadPacks: () => loadPacks(contentDir).packs.map((entry) => entry.pack),
})
try {
+46 -5
View File
@@ -74,11 +74,11 @@ function cleanName(input: unknown, fallback: string): string {
export class Room {
readonly code: string
readonly pack: Pack
readonly hostToken: string
private packValue: Pack
private engineValue: GameEngine
private readonly io: Server
private readonly engine: GameEngine
private readonly clients = new Map<string, Client>()
private readonly playerTokens = new Map<string, string>()
private readonly timer: NodeJS.Timeout
@@ -87,10 +87,10 @@ export class Room {
constructor(options: RoomOptions) {
this.code = options.code.toUpperCase()
this.pack = options.pack
this.packValue = options.pack
this.hostToken = options.hostToken
this.io = options.io
this.engine = new GameEngine(this.pack)
this.engineValue = new GameEngine(this.packValue)
this.timer = setInterval(() => this.tick(), options.tickMs ?? 100)
this.timer.unref()
}
@@ -99,8 +99,49 @@ export class Room {
return `room:${this.code}`
}
get pack(): Pack {
return this.packValue
}
get state() {
return this.engine.current
return this.engineValue.current
}
private get engine(): GameEngine {
return this.engineValue
}
/**
* Подменить пак на лету — после импорта из браузера.
*
* Разрешено только в лобби: посреди партии смена вопросов означала бы, что
* открытые клетки указывают в пустоту. Игроки и их очки остаются.
*/
usePack(pack: Pack): { ok: true } | { ok: false; reason: string } {
if (this.state.phase !== 'lobby') {
return { ok: false, reason: 'партия уже началась: нажмите «⟲ Заново» и повторите' }
}
const current = this.state
this.packValue = pack
this.engineValue = new GameEngine(pack, {
initial: {
seq: current.seq + 1,
phase: 'lobby',
roundIndex: 0,
players: current.players,
turn: current.players[0]?.id,
closed: [],
buzzes: [],
penalized: [],
bets: {},
finalJudged: {},
},
})
this.lastSeq = -1
this.broadcast()
return { ok: true }
}
close(): void {
+44
View File
@@ -0,0 +1,44 @@
/**
* Звуковые эффекты из файлов.
*
* Соглашение простое: положите файл с нужным именем в content/sfx/ —
* и он заменит синтезированный звук. Ничего настраивать не нужно, имя файла
* и есть настройка.
*/
import { existsSync, readdirSync } from 'node:fs'
export const SFX_NAMES = ['open', 'buzz', 'correct', 'wrong', 'tick', 'end'] as const
export type SfxName = (typeof SFX_NAMES)[number]
/** Порядок важен: первый найденный формат побеждает. */
const EXTENSIONS = ['mp3', 'wav', 'ogg', 'm4a', 'aac']
export type SfxManifest = Partial<Record<SfxName, string>>
export function scanSfx(dir: string | undefined): SfxManifest {
const manifest: SfxManifest = {}
if (!dir || !existsSync(dir)) return manifest
let files: string[]
try {
files = readdirSync(dir)
} catch {
return manifest
}
const lowered = files.map((file) => ({ file, lower: file.toLowerCase() }))
for (const name of SFX_NAMES) {
for (const extension of EXTENSIONS) {
const found = lowered.find((entry) => entry.lower === `${name}.${extension}`)
if (found) {
// encodeURIComponent: имена файлов могут быть кириллицей.
manifest[name] = `/sfx/${encodeURIComponent(found.file)}`
break
}
}
}
return manifest
}
+232
View File
@@ -0,0 +1,232 @@
/**
* Приём пака из браузера и звуковые эффекты.
*
* Проверяем не «счастливый путь», а то, что может испортить вечер:
* загрузку без токена, битую таблицу, запись поверх существующего пака
* и отсутствующие медиафайлы.
*/
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import type { Pack } from '@quiz/shared'
import { buildApp, type BuiltApp } from '../src/app'
import { loadPacks } from '../src/content'
const ROOM = 'IMPT'
const TOKEN = 'import-token'
function makePack(): Pack {
return {
id: 'base',
title: 'Базовый',
settings: {
wrongPenalty: 'value',
buzzers: true,
finalEnabled: false,
defaultTimeLimit: 30,
answerTimeLimit: 20,
auctionTimeLimit: 30,
betTimeLimit: 20,
},
rounds: [
{
id: 'r1',
title: 'Раунд',
themes: [{ id: 't1', title: 'Тема', cells: [{ value: 100, kind: 'normal', question: { text: 'В', answer: 'О' } }] }],
},
],
}
}
const CSV = [
'Название;Привезённый квиз',
'ID;imported',
'Финальный вопрос;Финал?',
'Финальный ответ;Ответ финала',
'',
'Тема;Стоимость;Вопрос;Ответ;Медиа',
'Стол;100;Первый;Ответ;',
'Ёлка;100;Второй;Ответ;song.mp3',
].join('\n')
let built: BuiltApp
let contentDir: string
let origin: string
beforeEach(async () => {
contentDir = mkdtempSync(path.join(tmpdir(), 'quiz-content-'))
mkdirSync(path.join(contentDir, 'packs'), { recursive: true })
mkdirSync(path.join(contentDir, 'media', 'imported'), { recursive: true })
mkdirSync(path.join(contentDir, 'sfx'), { recursive: true })
writeFileSync(path.join(contentDir, 'sfx', 'correct.mp3'), 'fake-audio')
built = await buildApp({
packs: [makePack()],
roomCode: ROOM,
hostToken: TOKEN,
contentDir,
reloadPacks: () => loadPacks(contentDir).packs.map((entry) => entry.pack),
})
await built.app.listen({ port: 0, host: '127.0.0.1' })
const address = built.app.server.address()
if (!address || typeof address === 'string') throw new Error('нет порта')
origin = `http://127.0.0.1:${address.port}`
})
afterEach(async () => {
await built.close()
rmSync(contentDir, { recursive: true, force: true })
})
async function postCsv(body: string, query: string): Promise<Response> {
return fetch(`${origin}/api/import?${query}`, {
method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' },
body: new TextEncoder().encode(body),
})
}
describe('загрузка пака', () => {
it('без токена ведущего не пускает', async () => {
const response = await postCsv(CSV, '')
expect(response.status).toBe(403)
})
it('с неверным токеном не пускает', async () => {
const response = await postCsv(CSV, 'token=чужой')
expect(response.status).toBe(403)
})
it('проверка dry=1 ничего не пишет', async () => {
const response = await postCsv(CSV, `token=${TOKEN}&dry=1`)
const data = (await response.json()) as { ok: boolean; written: boolean; pack: Pack }
expect(data.ok).toBe(true)
expect(data.written).toBe(false)
expect(data.pack.title).toBe('Привезённый квиз')
expect(existsSync(path.join(contentDir, 'packs', 'imported.json'))).toBe(false)
})
it('сохраняет пак и рассказывает про недостающие медиа', async () => {
const response = await postCsv(CSV, `token=${TOKEN}`)
const data = (await response.json()) as {
ok: boolean
written: boolean
missingMedia: string[]
stats: { cells: number }
}
expect(data.ok).toBe(true)
expect(data.written).toBe(true)
expect(data.stats.cells).toBe(2)
// song.mp3 в таблице есть, на диске — нет.
expect(data.missingMedia).toEqual(['/media/imported/song.mp3'])
const saved = JSON.parse(
readFileSync(path.join(contentDir, 'packs', 'imported.json'), 'utf8'),
) as Pack
expect(saved.title).toBe('Привезённый квиз')
expect(saved.final?.question.text).toBe('Финал?')
expect(saved.rounds[0]?.themes[0]?.cells[0]?.question.answer).toBe('Ответ')
})
it('сообщает, что перезаписал существующий пак', async () => {
await postCsv(CSV, `token=${TOKEN}`)
const second = await postCsv(CSV, `token=${TOKEN}`)
const data = (await second.json()) as { replaced: boolean }
expect(data.replaced).toBe(true)
})
it('на битой таблице возвращает ошибки со строками', async () => {
const broken = ['Тема;Стоимость;Вопрос;Ответ', 'Стол;100;Без ответа;'].join('\n')
const response = await postCsv(broken, `token=${TOKEN}`)
const data = (await response.json()) as {
ok: boolean
errors: Array<{ line: number; message: string }>
}
expect(data.ok).toBe(false)
expect(data.errors[0]?.line).toBe(2)
expect(data.errors[0]?.message).toMatch(/не указан ответ/)
})
it('на пустом файле не падает', async () => {
const response = await postCsv('', `token=${TOKEN}`)
const data = (await response.json()) as { ok: boolean; errors: Array<{ message: string }> }
expect(data.ok).toBe(false)
expect(data.errors[0]?.message).toMatch(/пустой/)
})
})
describe('применение пака без перезапуска', () => {
it('берёт свежеимпортированный пак в игру', async () => {
await postCsv(CSV, `token=${TOKEN}`)
const response = await fetch(`${origin}/api/packs/apply?token=${TOKEN}&id=imported`, {
method: 'POST',
})
const data = (await response.json()) as {
ok: boolean
pack: { id: string; title: string }
phase: string
}
expect(data.ok).toBe(true)
expect(data.pack.id).toBe('imported')
expect(data.phase).toBe('lobby')
// Комната теперь играет новый пак — это видно и в /api/room.
expect(built.room.pack.id).toBe('imported')
})
it('не находит несуществующий пак', async () => {
const response = await fetch(`${origin}/api/packs/apply?token=${TOKEN}&id=нет`, {
method: 'POST',
})
expect(response.status).toBe(404)
})
it('требует токен ведущего', async () => {
const response = await fetch(`${origin}/api/packs/apply?id=imported`, { method: 'POST' })
expect(response.status).toBe(403)
})
})
describe('список для страницы импорта', () => {
it('отдаёт паки, папки медиа и найденные звуки', async () => {
const response = await fetch(`${origin}/api/import/info?token=${TOKEN}`)
const data = (await response.json()) as {
packs: Array<{ id: string }>
mediaFolders: string[]
sfx: Record<string, string>
}
expect(data.packs.map((pack) => pack.id)).toContain('base')
expect(data.mediaFolders).toContain('imported')
expect(data.sfx.correct).toBe('/sfx/correct.mp3')
})
it('без токена не отдаёт ничего', async () => {
const response = await fetch(`${origin}/api/import/info?token=чужой`)
expect(response.status).toBe(403)
})
})
describe('звуковые файлы', () => {
it('манифест перечисляет только знакомые имена', async () => {
writeFileSync(path.join(contentDir, 'sfx', 'случайный.mp3'), 'x')
const response = await fetch(`${origin}/api/sfx`)
const data = (await response.json()) as { files: Record<string, string>; names: string[] }
expect(data.files.correct).toBe('/sfx/correct.mp3')
expect(Object.keys(data.files)).toEqual(['correct'])
expect(data.names).toContain('wrong')
})
it('отдаёт файл по адресу из манифеста', async () => {
const response = await fetch(`${origin}/sfx/correct.mp3`)
expect(response.status).toBe(200)
expect(await response.text()).toBe('fake-audio')
})
})