From ea2d5d905cc539122d2d68fcc0f2eefcb8e6ef8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B8=D1=82=D0=B0=D0=BB=D0=B8=D0=B9=20=D0=9E=D1=81?= =?UTF-8?q?=D0=BA=D0=B0=D1=80=D0=B5=D0=B2?= Date: Mon, 16 Nov 2026 15:19:58 +0700 Subject: [PATCH] =?UTF-8?q?=D0=A1=D1=82=D1=80=D0=B0=D0=BD=D0=B8=D1=86?= =?UTF-8?q?=D0=B0=20=D0=B8=D0=BC=D0=BF=D0=BE=D1=80=D1=82=D0=B0=20=D0=B8=20?= =?UTF-8?q?=D0=B7=D0=B2=D1=83=D0=BA=D0=BE=D0=B2=D1=8B=D0=B5=20=D1=8D=D1=84?= =?UTF-8?q?=D1=84=D0=B5=D0=BA=D1=82=D1=8B=20=D0=B8=D0=B7=20=D1=84=D0=B0?= =?UTF-8?q?=D0=B9=D0=BB=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - метаданные пака (название, id, финал) читаются из самого CSV - страница /import/<токен>: перетащить таблицу, проверить, сохранить - пак применяется без перезапуска сервера, если партия не начата - звуки берутся из content/sfx/, иначе используется синтез - заголовок таблицы ищется по содержимому, а не по позиции --- README.md | 71 +++++-- content/sfx/README.md | 26 +++ examples/questions.csv | 6 + packages/server/src/app.ts | 125 ++++++++++- packages/server/src/importing.ts | 111 ++++++++++ packages/server/src/index.ts | 5 +- packages/server/src/room.ts | 51 ++++- packages/server/src/sfx.ts | 44 ++++ packages/server/test/import.test.ts | 232 +++++++++++++++++++++ packages/shared/src/importer.ts | 141 ++++++++++++- packages/shared/src/index.ts | 11 +- packages/shared/test/importer.test.ts | 76 +++++++ packages/web/src/audio/sfx.ts | 105 +++++++--- packages/web/src/router.ts | 2 + packages/web/src/styles.css | 145 +++++++++++++ packages/web/src/views/BoardView.vue | 4 +- packages/web/src/views/HostView.vue | 3 + packages/web/src/views/ImportView.vue | 288 ++++++++++++++++++++++++++ packages/web/vite.config.ts | 1 + scripts/import-pack.ts | 35 ++-- scripts/smoke-import.mjs | 135 ++++++++++++ 21 files changed, 1529 insertions(+), 88 deletions(-) create mode 100644 content/sfx/README.md create mode 100644 packages/server/src/importing.ts create mode 100644 packages/server/src/sfx.ts create mode 100644 packages/server/test/import.test.ts create mode 100644 packages/web/src/views/ImportView.vue create mode 100644 scripts/smoke-import.mjs diff --git a/README.md b/README.md index c92ce5f..bab017b 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ | 4 | Телефоны игроков, QR, реконнект | ✅ | | 5 | Полировка: звук, вспышки, переходы, медиа в финале | ✅ | | 6 | Импорт вопросов из CSV/Excel | ✅ | +| 7 | Страница импорта и звуки из файлов | ✅ | Играть можно по-настоящему: табло на проекторе, ведущий с ноутбука или телефона, игроки со своих телефонов. Комната одна, партия живёт в памяти сервера. @@ -54,15 +55,35 @@ ## Звук -Ни одного аудиофайла: тоны синтезируются в браузере -([audio/sfx.ts](packages/web/src/audio/sfx.ts)). Причина практическая — на -площадке нечему не загрузиться и нечего забыть скопировать на другой ноутбук. +Эффекты берутся из файлов в `content/sfx/`, а если файла нет — синтезируются +в браузере ([audio/sfx.ts](packages/web/src/audio/sfx.ts)). + +Положите файл с нужным именем, и он заменит встроенный звук: + +| Файл | Момент | +|---|---| +| `open.mp3` | открылась клетка | +| `buzz.mp3` | кто-то нажал кнопку | +| `correct.mp3` | верный ответ | +| `wrong.mp3` | неверный ответ или время вышло | +| `tick.mp3` | последние пять секунд | +| `end.mp3` | конец раунда или партии | + +Форматы: mp3, wav, ogg, m4a. Имя важнее расширения; при равенстве побеждает +mp3. Перезапуск не нужен — список читается при каждом открытии табло. + +Синтез остаётся запасным вариантом: игра звучит и на чистом проекте, без +единого аудиофайла. Это же спасает, если файл забыли скопировать на другой +ноутбук. ## Структура ``` quiz/ -├─ content/packs/ паки вопросов (JSON) + content/media/ для аудио и картинок +├─ content/ +│ ├─ packs/ паки вопросов (JSON) +│ ├─ media// картинки, музыка, видео +│ └─ sfx/ звуковые эффекты (необязательно) ├─ examples/ пример таблицы для импорта ├─ docs/architecture.md архитектура и принятые решения └─ packages/ @@ -120,7 +141,33 @@ node scripts/smoke.mjs Набивать 25 вопросов в JSON с кавычками — мучение. Набивайте в Excel или Google Sheets, а пак соберётся сам. -Колонки (заголовок обязателен, порядок любой, регистр не важен): +### Через браузер + +1. Положите картинки и музыку в `content/media//`. +2. В пульте нажмите **⇪ Импорт** (или откройте `/import/<токен>`). +3. Перетащите CSV на страницу. +4. **Проверить** — покажет ошибки с номерами строк, ничего не записывая. +5. **Сохранить пак** — файл появится в `content/packs/`, и сервер сразу возьмёт + его в игру. Перезапускать ничего не нужно, если партия ещё не началась. + +Страница требует токен ведущего: она пишет файлы на сервер. + +### Что писать в таблице + +Над заголовком — необязательный блок метаданных, по строке на значение: + +``` +Название;Новогодний квиз 2027 +ID;novy-god-2027 +Финальный вопрос;Что делают с запиской, на которой написано желание? +Финальный ответ;Сжигают, а пепел высыпают в бокал +Комментарий к финалу;Успеть до последнего удара +``` + +Если `Название` не указано, пак назовётся «Новогодний квиз», а `id` соберётся +из названия транслитом. + +Дальше — обычная таблица (заголовок обязателен, порядок колонок любой): | Колонка | Обязательна | Что писать | |---|---|---| @@ -137,12 +184,14 @@ Sheets, а пак соберётся сам. через `;`, и это работает. Кодировка тоже любая: UTF-8 и Windows-1251 (как сохраняет русский Excel) читаются обе. +Готовый пример со всем сразу — [examples/questions.csv](examples/questions.csv). + +### Из командной строки + ```powershell # PowerShell: npx tsx обязателен, см. примечание ниже +npx tsx scripts/import-pack.ts вопросы.csv --check npx tsx scripts/import-pack.ts вопросы.csv --id=novy-god --title="Новогодний квиз" - -# с финальным вопросом и проверкой без записи -npx tsx scripts/import-pack.ts вопросы.csv --id=test --final=финал.csv --check ``` В `cmd.exe` и bash работает и короткая форма: @@ -155,9 +204,6 @@ npm run import -- вопросы.csv --id=novy-god `--id=`: до скрипта доходит только имя файла. Поэтому в PowerShell вызывайте `npx tsx scripts/import-pack.ts` напрямую. -Готовый пример — [examples/questions.csv](examples/questions.csv) и -[examples/final.csv](examples/final.csv). - Что делает импортёр: - **ругается номерами строк** файла, а не путями в JSON: «строка 7: не указан ответ»; @@ -170,8 +216,7 @@ npm run import -- вопросы.csv --id=novy-god - **прогоняет результат через ту же схему**, что и игра, — сломанный пак не попадёт на диск. -Собранный пак кладётся в `content/packs/.json`. Запустите игру заново — -сервер подхватит его при старте. +Собранный пак кладётся в `content/packs/.json`. ## Как добавить вопросы diff --git a/content/sfx/README.md b/content/sfx/README.md new file mode 100644 index 0000000..2adf132 --- /dev/null +++ b/content/sfx/README.md @@ -0,0 +1,26 @@ +# Звуковые эффекты + +Положите сюда файлы — они заменят встроенные синтезированные звуки. + +| Имя файла | Когда играет | +|---|---| +| `open` | открылась клетка на табло | +| `buzz` | кто-то нажал кнопку ответа | +| `correct` | ответ верный | +| `wrong` | ответ неверный или вышло время | +| `tick` | последние пять секунд вопроса | +| `end` | конец раунда или партии | + +Формат: mp3, wav, ogg, m4a или aac. Расширение определяет сервер, имя — момент. +Например, `correct.mp3` или `wrong.wav`. + +Правила простые: + +- **имя файла важнее расширения**: если есть и `correct.mp3`, и `correct.wav`, + сыграет mp3; +- **нет файла — играет синтез**, ничего не ломается; +- **перезапуск сервера не нужен**: список читается при каждом открытии табло, + достаточно обновить страницу; +- звуки включаются кнопкой 🔊 на табло — браузер не даёт звучать без действия. + +Файлы раздаются по адресу `/sfx/<имя>.<расширение>`. diff --git a/examples/questions.csv b/examples/questions.csv index 31207c5..0d740d0 100644 --- a/examples/questions.csv +++ b/examples/questions.csv @@ -1,3 +1,9 @@ +Название;Новогодний квиз 2027 +ID;example +Финальный вопрос;Что по традиции делают с запиской, на которой написано желание? +Финальный ответ;Сжигают, а пепел высыпают в бокал +Комментарий к финалу;Успеть до последнего удара курантов +; Раунд;Тема;Стоимость;Вопрос;Ответ;Комментарий;Тип;Медиа Раунд 1;Новогодний стол;100;Главный салат новогоднего стола, названный в честь французского повара;Оливье;Люсьен Оливье держал ресторан «Эрмитаж»;; Раунд 1;Новогодний стол;200;Какой цитрус в России традиционно считается новогодним фруктом?;Мандарин;;; diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts index 7519bdc..3346489 100644 --- a/packages/server/src/app.ts +++ b/packages/server/src/app.ts @@ -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 } +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 { const pack = options.packId ? options.packs.find((candidate) => candidate.id === options.packId) @@ -52,6 +68,11 @@ export async function buildApp(options: AppOptions): Promise { 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 { 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 { })), ) + // Пак берём у комнаты, а не из настроек сборки: его можно подменить импортом. 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/ — это маршруты одного приложения. app.setNotFoundHandler((request, reply) => { const url = request.raw.url ?? '' diff --git a/packages/server/src/importing.ts b/packages/server/src/importing.ts new file mode 100644 index 0000000..9d9c8f8 --- /dev/null +++ b/packages/server/src/importing.ts @@ -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, + } +} diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts index 89dd3a5..e2f9930 100644 --- a/packages/server/src/index.ts +++ b/packages/server/src/index.ts @@ -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 { diff --git a/packages/server/src/room.ts b/packages/server/src/room.ts index 798c7f6..36a9fef 100644 --- a/packages/server/src/room.ts +++ b/packages/server/src/room.ts @@ -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() private readonly playerTokens = new Map() 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 { diff --git a/packages/server/src/sfx.ts b/packages/server/src/sfx.ts new file mode 100644 index 0000000..b2e5235 --- /dev/null +++ b/packages/server/src/sfx.ts @@ -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> + +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 +} diff --git a/packages/server/test/import.test.ts b/packages/server/test/import.test.ts new file mode 100644 index 0000000..8d086d5 --- /dev/null +++ b/packages/server/test/import.test.ts @@ -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 { + 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 + } + + 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; 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') + }) +}) diff --git a/packages/shared/src/importer.ts b/packages/shared/src/importer.ts index 3aa5e85..c3b44be 100644 --- a/packages/shared/src/importer.ts +++ b/packages/shared/src/importer.ts @@ -27,8 +27,9 @@ export interface ImportError { } export interface ImportOptions { - id: string - title: string + /** Необязателен: берётся из блока метаданных или из названия. */ + id?: string + title?: string settings?: Partial final?: { question: string; answer: string; comment?: string } } @@ -47,9 +48,98 @@ export interface TableRow { export interface Table { header: string[] + /** Строки над заголовком: название игры, id, финальный вопрос. */ + meta: TableRow[] rows: TableRow[] } +// ─── Метаданные пака ─────────────────────────────────────────────────────── + +export interface PackMeta { + id?: string + title?: string + final?: { question: string; answer: string; comment?: string } +} + +const META_KEYS: Record = { + название: 'title', + игра: 'title', + title: 'title', + id: 'id', + код: 'id', + 'финальный вопрос': 'finalQuestion', + финал: 'finalQuestion', + 'финальный ответ': 'finalAnswer', + 'комментарий к финалу': 'finalComment', +} + +/** Собирает метаданные из строк над заголовком таблицы. */ +export function readMeta(rows: TableRow[]): PackMeta { + const meta: PackMeta = {} + const final: NonNullable = { question: '', answer: '' } + let hasFinal = false + + for (const row of rows) { + const key = META_KEYS[normalizeHeader(row.cells[0] ?? '')] + if (!key) continue + const value = (row.cells[1] ?? '').trim() + if (!value) continue + + if (key === 'title') meta.title = value + else if (key === 'id') meta.id = value + else if (key === 'finalQuestion') { + final.question = value + hasFinal = true + } else if (key === 'finalAnswer') { + final.answer = value + hasFinal = true + } else if (key === 'finalComment') { + final.comment = value + hasFinal = true + } + } + + if (hasFinal && final.question && final.answer) { + meta.final = final.comment + ? { question: final.question, answer: final.answer, comment: final.comment } + : { question: final.question, answer: final.answer } + } + + return meta +} + +// ─── Кодировка и идентификатор ───────────────────────────────────────────── + +/** + * Русский Excel сохраняет CSV в Windows-1251, а не в UTF-8. + * Пробуем UTF-8 строго: если байты не складываются — это ANSI. + */ +export function decodeTable(bytes: Uint8Array): { text: string; encoding: 'utf-8' | 'windows-1251' } { + try { + return { text: new TextDecoder('utf-8', { fatal: true }).decode(bytes), encoding: 'utf-8' } + } catch { + return { text: new TextDecoder('windows-1251').decode(bytes), encoding: 'windows-1251' } + } +} + +const TRANSLIT: Record = { + а: 'a', б: 'b', в: 'v', г: 'g', д: 'd', е: 'e', ё: 'e', ж: 'zh', з: 'z', + и: 'i', й: 'y', к: 'k', л: 'l', м: 'm', н: 'n', о: 'o', п: 'p', р: 'r', + с: 's', т: 't', у: 'u', ф: 'f', х: 'h', ц: 'c', ч: 'ch', ш: 'sh', щ: 'sch', + ъ: '', ы: 'y', ь: '', э: 'e', ю: 'yu', я: 'ya', +} + +/** «Новогодний квиз 2027» → «novogodniy-kviz-2027». */ +export function slugify(input: string): string { + const latin = Array.from(input.toLowerCase()) + .map((char) => TRANSLIT[char] ?? char) + .join('') + const slug = latin + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + return slug || 'quiz' +} + const DELIMITERS = [',', ';', '\t'] as const function firstLine(text: string): string { @@ -156,8 +246,31 @@ export function parseTable(text: string): Table { if (touched || field.length > 0 || record.length > 0) pushRecord() - const header = rows.shift() - return { header: header?.cells ?? [], rows } + // Заголовок ищем по содержимому, а не по позиции: над ним может стоять + // блок «Название игры; …». Без этого любая строка метаданных ломала импорт. + const headerIndex = rows.findIndex((row) => looksLikeHeader(row.cells)) + if (headerIndex < 0) { + const first = rows.shift() + return { header: first?.cells ?? [], meta: [], rows } + } + + const meta = rows.slice(0, headerIndex) + const header = rows[headerIndex] + return { + header: header?.cells ?? [], + meta, + rows: rows.slice(headerIndex + 1), + } +} + +function looksLikeHeader(cells: string[]): boolean { + const found = new Set() + for (const raw of cells) { + const column = HEADER_ALIASES[normalizeHeader(raw)] + if (column) found.add(column) + } + // «Тема» плюс хоть что-то из содержимого клетки — это заголовок таблицы. + return found.has('theme') && (found.has('value') || found.has('question') || found.has('answer')) } // ─── Заголовки ───────────────────────────────────────────────────────────── @@ -289,9 +402,11 @@ interface Entry { line: number // ─── Сборка пака ─────────────────────────────────────────────────────────── -export function tableToPack(text: string, options: ImportOptions): ImportResult { +export function tableToPack(text: string, options: ImportOptions = {}): ImportResult { const table = parseTable(text) + const meta = readMeta(table.meta) const errors: ImportError[] = [] + const packId = options.id ?? meta.id ?? slugify(options.title ?? meta.title ?? 'quiz') const columns = new Map() table.header.forEach((raw, index) => { @@ -358,7 +473,7 @@ export function tableToPack(text: string, options: ImportOptions): ImportResult let media: string | undefined if (mediaRaw) { - media = normalizeMediaSource(mediaRaw, options.id) + media = normalizeMediaSource(mediaRaw, packId) if (!mediaKindOf(media)) { errors.push({ line: row.line, @@ -464,16 +579,20 @@ export function tableToPack(text: string, options: ImportOptions): ImportResult return { id: `r${roundIndex + 1}`, title: roundTitle, themes } }) + const title = options.title ?? meta.title ?? 'Новогодний квиз' const pack: Pack = { - id: options.id, - title: options.title, + id: packId, + title, settings: { ...DEFAULT_SETTINGS, ...options.settings }, rounds, } - if (options.final) { + + // Финальный вопрос: приоритет у явного аргумента, иначе — из метаданных. + const final = options.final ?? meta.final + if (final) { // В паке финал — это Question, а не строка: у него есть text и answer. - const question: Question = { text: options.final.question, answer: options.final.answer } - if (options.final.comment) question.comment = options.final.comment + const question: Question = { text: final.question, answer: final.answer } + if (final.comment) question.comment = final.comment pack.final = { question } } diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index e63c370..0c79bcd 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -13,11 +13,20 @@ export { } from './pack' export type { CellKeyParts, FoundCell, ParsePackResult, ParsedPack } from './pack' -export { detectDelimiter, parseTable, tableToPack, parseFinal } from './importer' +export { + detectDelimiter, + parseTable, + tableToPack, + parseFinal, + readMeta, + decodeTable, + slugify, +} from './importer' export type { ImportError, ImportOptions, ImportResult, + PackMeta, Table, TableRow, } from './importer' diff --git a/packages/shared/test/importer.test.ts b/packages/shared/test/importer.test.ts index 4913e80..e60d3db 100644 --- a/packages/shared/test/importer.test.ts +++ b/packages/shared/test/importer.test.ts @@ -47,6 +47,82 @@ describe('разбор таблицы', () => { }) }) +describe('кодировка', () => { + it('узнаёт Windows-1251, где байты не складываются в UTF-8', async () => { + const { decodeTable } = await import('../src/index') + // «Тема» в Windows-1251: D2 E5 EC E0. + const bytes = Uint8Array.from([0xd2, 0xe5, 0xec, 0xe0]) + const decoded = decodeTable(bytes) + expect(decoded.encoding).toBe('windows-1251') + expect(decoded.text).toBe('Тема') + }) + + it('читает UTF-8 как UTF-8', async () => { + const { decodeTable } = await import('../src/index') + const decoded = decodeTable(new TextEncoder().encode('Тема')) + expect(decoded.encoding).toBe('utf-8') + expect(decoded.text).toBe('Тема') + }) +}) + +describe('метаданные над заголовком', () => { + const csv = [ + 'Название;Новогодний квиз 2027', + 'ID;novy-god-2027', + 'Финальный вопрос;Что делают с запиской?', + 'Финальный ответ;Сжигают', + 'Комментарий к финалу;До последнего удара', + '', + 'Тема;Стоимость;Вопрос;Ответ', + 'Стол;100;Вопрос;Ответ', + 'Ёлка;100;Вопрос;Ответ', + ].join('\n') + + it('берёт название, id и финал из самого файла', () => { + const result = tableToPack(csv) + if (!result.ok) throw new Error(result.errors.map((e) => e.message).join(', ')) + + expect(result.pack.title).toBe('Новогодний квиз 2027') + expect(result.pack.id).toBe('novy-god-2027') + expect(result.pack.final?.question.text).toBe('Что делают с запиской?') + expect(result.pack.final?.question.answer).toBe('Сжигают') + expect(result.pack.final?.question.comment).toBe('До последнего удара') + expect(result.stats.cells).toBe(2) + }) + + it('явные аргументы важнее метаданных', () => { + const result = tableToPack(csv, { id: 'forced', title: 'Своё название' }) + if (!result.ok) throw new Error('пак не собрался') + expect(result.pack.id).toBe('forced') + expect(result.pack.title).toBe('Своё название') + }) + + it('выводит id из названия транслитом', () => { + const result = tableToPack(['Название;Ёлки-палки 2027', 'Тема;Стоимость;Вопрос;Ответ', 'Стол;100;В;О'].join('\n')) + if (!result.ok) throw new Error('пак не собрался') + expect(result.pack.id).toBe('elki-palki-2027') + }) + + it('без метаданных не падает и даёт осмысленный id', () => { + const result = tableToPack('Тема,Стоимость,Вопрос,Ответ\nСтол,100,В,О') + if (!result.ok) throw new Error('пак не собрался') + expect(result.pack.id).toBe('quiz') + expect(result.pack.title).toBe('Новогодний квиз') + }) + + it('финал без вопроса или без ответа не попадает в пак', () => { + const text = [ + 'Название;Тест', + 'Финальный вопрос;Вопрос без ответа', + 'Тема;Стоимость;Вопрос;Ответ', + 'Стол;100;В;О', + ].join('\n') + const result = tableToPack(text) + if (!result.ok) throw new Error('пак не собрался') + expect(result.pack.final).toBeUndefined() + }) +}) + describe('сборка пака', () => { const csv = [ 'Раунд,Тема,Стоимость,Вопрос,Ответ,Комментарий,Тип,Медиа', diff --git a/packages/web/src/audio/sfx.ts b/packages/web/src/audio/sfx.ts index 3f45382..726478e 100644 --- a/packages/web/src/audio/sfx.ts +++ b/packages/web/src/audio/sfx.ts @@ -1,19 +1,24 @@ /** - * Звуки квиза, синтезированные на месте. + * Звуковые эффекты: файлы, а на случай их отсутствия — синтез. * - * Ни одного mp3 в репозитории: звук собирается из осцилляторов. Причина не в - * экономии — на площадке нечему «не загрузиться», и папку с ассетами нельзя - * забыть скопировать на другой ноутбук. + * Положите в content/sfx/ файл с нужным именем (correct.mp3, buzz.wav, …) — + * сервер сам отдаст его как /sfx/…, и он заменит встроенный звук. Ничего + * настраивать не нужно: имя файла и есть настройка. * - * Браузер не даёт звучать до действия пользователя, поэтому на табло есть - * кнопка включения: один клик при настройке — и дальше всё играет само. + * Синтез остаётся запасным вариантом, чтобы игра звучала и на чистом проекте. */ const STORAGE_KEY = 'quiz:sound' +export const SFX_NAMES = ['open', 'buzz', 'correct', 'wrong', 'tick', 'end'] as const +export type SfxName = (typeof SFX_NAMES)[number] + let context: AudioContext | null = null let enabled = false +const files = new Map() +const players = new Map() + export function preferredSound(): boolean { try { return localStorage.getItem(STORAGE_KEY) === '1' @@ -26,6 +31,34 @@ export function soundEnabled(): boolean { return enabled } +export function availableSfx(): SfxName[] { + return [...files.keys()] +} + +/** + * Спрашивает у сервера, какие эффекты заменены файлами, и заранее их грузит. + * Ошибка сети не критична: останется синтез. + */ +export async function loadSfx(): Promise { + try { + const response = await fetch('/api/sfx') + if (!response.ok) return + const data = (await response.json()) as { files?: Record } + for (const name of SFX_NAMES) { + const url = data.files?.[name] + if (!url) continue + files.set(name, url) + const audio = new Audio() + audio.src = url + audio.preload = 'auto' + audio.volume = 0.85 + players.set(name, audio) + } + } catch { + // Сервер мог быть ещё не готов — останется синтез. + } +} + export async function enableSound(): Promise { if (typeof window === 'undefined') return false try { @@ -48,6 +81,8 @@ export function disableSound(): void { } } +// ─── Синтез (запасной вариант) ───────────────────────────────────────────── + interface ToneOptions { frequency: number duration: number @@ -58,7 +93,7 @@ interface ToneOptions { } function tone(options: ToneOptions): void { - if (!enabled || !context || context.state !== 'running') return + if (!context || context.state !== 'running') return const start = context.currentTime + (options.delay ?? 0) const oscillator = context.createOscillator() @@ -81,32 +116,46 @@ function tone(options: ToneOptions): void { oscillator.stop(start + options.duration + 0.03) } -export const sfx = { - /** Открылась клетка. */ - open(): void { - tone({ frequency: 520, sweepTo: 880, duration: 0.12, type: 'triangle', gain: 0.1 }) - }, - /** Кто-то нажал кнопку. */ - buzz(): void { - tone({ frequency: 190, sweepTo: 120, duration: 0.16, type: 'square', gain: 0.12 }) - }, - /** Ответ верный. */ - correct(): void { +const SYNTH: Record void> = { + open: () => tone({ frequency: 520, sweepTo: 880, duration: 0.12, type: 'triangle', gain: 0.1 }), + buzz: () => tone({ frequency: 190, sweepTo: 120, duration: 0.16, type: 'square', gain: 0.12 }), + correct: () => { tone({ frequency: 660, duration: 0.16, type: 'sine', gain: 0.16 }) tone({ frequency: 990, duration: 0.24, type: 'sine', gain: 0.14, delay: 0.12 }) }, - /** Ответ неверный или время вышло. */ - wrong(): void { - tone({ frequency: 240, sweepTo: 110, duration: 0.38, type: 'sawtooth', gain: 0.1 }) - }, - /** Последние секунды. */ - tick(): void { - tone({ frequency: 1200, duration: 0.045, type: 'sine', gain: 0.05 }) - }, - /** Раунд или партия закончились. */ - end(): void { + wrong: () => tone({ frequency: 240, sweepTo: 110, duration: 0.38, type: 'sawtooth', gain: 0.1 }), + tick: () => tone({ frequency: 1200, duration: 0.045, type: 'sine', gain: 0.05 }), + end: () => { for (const [index, frequency] of [523, 659, 784].entries()) { tone({ frequency, duration: 0.5, type: 'sine', gain: 0.1, delay: index * 0.09 }) } }, } + +// ─── Воспроизведение ─────────────────────────────────────────────────────── + +function play(name: SfxName): void { + if (!enabled) return + + const player = players.get(name) + if (player) { + try { + player.currentTime = 0 + void player.play() + return + } catch { + // Файл не проигрался — не повод молчать, сыграем синтезом. + } + } + + SYNTH[name]() +} + +export const sfx = { + open: (): void => play('open'), + buzz: (): void => play('buzz'), + correct: (): void => play('correct'), + wrong: (): void => play('wrong'), + tick: (): void => play('tick'), + end: (): void => play('end'), +} diff --git a/packages/web/src/router.ts b/packages/web/src/router.ts index 0201abb..8ad0cba 100644 --- a/packages/web/src/router.ts +++ b/packages/web/src/router.ts @@ -2,6 +2,7 @@ import { createRouter, createWebHistory } from 'vue-router' import BoardView from './views/BoardView.vue' import HomeView from './views/HomeView.vue' import HostView from './views/HostView.vue' +import ImportView from './views/ImportView.vue' import PlayerView from './views/PlayerView.vue' export const router = createRouter({ @@ -10,6 +11,7 @@ export const router = createRouter({ { path: '/', name: 'home', component: HomeView }, { path: '/board', name: 'board', component: BoardView }, { path: '/host/:token', name: 'host', component: HostView }, + { path: '/import/:token', name: 'import', component: ImportView }, { path: '/play', name: 'play', component: PlayerView }, { path: '/:pathMatch(.*)*', redirect: '/' }, ], diff --git a/packages/web/src/styles.css b/packages/web/src/styles.css index 6401eb7..830ac75 100644 --- a/packages/web/src/styles.css +++ b/packages/web/src/styles.css @@ -874,3 +874,148 @@ input:focus { transform: none; } } + +/* ─── Страница импорта ───────────────────────────────────────────────── */ + +.import { + flex: 1; + display: grid; + grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); + gap: clamp(0.7rem, 1.6vmin, 1.2rem); + align-content: start; + padding-bottom: 2rem; +} + +.import-card { + display: flex; + flex-direction: column; + gap: 0.6rem; + padding: clamp(0.9rem, 2vmin, 1.4rem); + border-radius: var(--radius); + background: var(--panel); + border: 1px solid rgba(255, 255, 255, 0.07); +} + +.import-card .note { + max-width: none; + text-align: left; +} + +.import-card code { + background: rgba(0, 0, 0, 0.32); + border-radius: 6px; + padding: 0.1em 0.4em; + font-size: 0.9em; + color: var(--gold); + word-break: break-word; +} + +.bad-card { + border-color: rgba(226, 103, 95, 0.45); + background: rgba(226, 103, 95, 0.07); +} + +.ok-card { + border-color: rgba(72, 185, 138, 0.45); + background: rgba(72, 185, 138, 0.07); +} + +.import-title { + margin: 0; + font-size: clamp(1.1rem, 2.6vmin, 1.6rem); + font-weight: 650; + color: var(--gold); +} + +.drop { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 0.35rem; + min-height: 120px; + padding: 1rem; + border-radius: var(--radius); + border: 2px dashed rgba(233, 196, 106, 0.35); + background: rgba(0, 0, 0, 0.18); + cursor: pointer; + text-align: center; + transition: border-color 0.15s, background 0.15s; +} + +.drop:hover, +.drop.over { + border-color: var(--gold); + background: var(--gold-soft); +} + +.drop.filled { + border-style: solid; +} + +.drop-title { + font-size: clamp(0.95rem, 2vmin, 1.15rem); + font-weight: 600; + word-break: break-all; +} + +.drop-hint { + font-size: 0.78rem; + color: var(--muted); +} + +.error-list { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + gap: 0.4rem; + font-size: 0.88rem; +} + +.error-list li { + display: flex; + gap: 0.6rem; + align-items: baseline; +} + +.line-no { + flex: none; + color: var(--bad); + font-variant-numeric: tabular-nums; + font-size: 0.78rem; + min-width: 4.6rem; +} + +.warn-block { + margin-top: 0.4rem; + padding-top: 0.5rem; + border-top: 1px solid rgba(255, 255, 255, 0.08); +} + +.pack-list { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + gap: 0.45rem; + font-size: 0.88rem; +} + +.pack-list li { + display: flex; + flex-direction: column; + gap: 0.1rem; +} + +.pack-list .note { + font-size: 0.76rem; + color: var(--muted); +} + +a.ghost { + text-decoration: none; + display: inline-block; +} diff --git a/packages/web/src/views/BoardView.vue b/packages/web/src/views/BoardView.vue index bf5b7b9..bb371f0 100644 --- a/packages/web/src/views/BoardView.vue +++ b/packages/web/src/views/BoardView.vue @@ -14,7 +14,7 @@ import BoardGrid from '../components/BoardGrid.vue' import Countdown from '../components/Countdown.vue' import QuestionMedia from '../components/QuestionMedia.vue' import ScoreBar from '../components/ScoreBar.vue' -import { disableSound, enableSound, preferredSound, sfx } from '../audio/sfx' +import { disableSound, enableSound, loadSfx, preferredSound, sfx } from '../audio/sfx' import { game } from '../net/game' import { rememberRoom, resolveRoom } from '../net/room' @@ -85,6 +85,8 @@ onMounted(async () => { } rememberRoom(room.value) game.connect({ role: 'board', room: room.value }) + // Файловые звуки из content/sfx подхватываются до первого вопроса. + void loadSfx() timer = setInterval(() => { now.value = Date.now() }, 200) diff --git a/packages/web/src/views/HostView.vue b/packages/web/src/views/HostView.vue index 519f1ec..0daefc4 100644 --- a/packages/web/src/views/HostView.vue +++ b/packages/web/src/views/HostView.vue @@ -147,6 +147,9 @@ function selectCell(key: string): void { комната {{ room }} {{ label }} + + ⇪ Импорт + diff --git a/packages/web/src/views/ImportView.vue b/packages/web/src/views/ImportView.vue new file mode 100644 index 0000000..3271ca6 --- /dev/null +++ b/packages/web/src/views/ImportView.vue @@ -0,0 +1,288 @@ + + + diff --git a/packages/web/vite.config.ts b/packages/web/vite.config.ts index 0f01e30..0c84374 100644 --- a/packages/web/vite.config.ts +++ b/packages/web/vite.config.ts @@ -25,6 +25,7 @@ export default defineConfig({ '/socket.io': { target: 'http://127.0.0.1:3000', ws: true }, '/api': { target: 'http://127.0.0.1:3000' }, '/media': { target: 'http://127.0.0.1:3000' }, + '/sfx': { target: 'http://127.0.0.1:3000' }, }, }, }) diff --git a/scripts/import-pack.ts b/scripts/import-pack.ts index 1278214..05b00fb 100644 --- a/scripts/import-pack.ts +++ b/scripts/import-pack.ts @@ -15,7 +15,7 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' -import { parseFinal, parsePack, tableToPack } from '../packages/shared/src/index' +import { decodeTable, parseFinal, parsePack, tableToPack } from '../packages/shared/src/index' const root = fileURLToPath(new URL('../', import.meta.url)) const packsDir = path.join(root, 'content', 'packs') @@ -88,15 +88,6 @@ function usage(): void { ) } -/** Русский Excel сохраняет CSV в Windows-1251, а не в UTF-8. */ -function decode(buffer: Buffer): { text: string; encoding: string } { - try { - return { text: new TextDecoder('utf-8', { fatal: true }).decode(buffer), encoding: 'utf-8' } - } catch { - return { text: new TextDecoder('windows-1251').decode(buffer), encoding: 'windows-1251' } - } -} - function slug(input: string): string { return input .replace(/\.(csv|tsv|txt)$/i, '') @@ -122,16 +113,16 @@ if (args.help || !args.input) { const inputPath = path.resolve(args.input) if (!existsSync(inputPath)) fail(`файл не найден: ${inputPath}`) -const id = args.id ?? slug(path.basename(inputPath)) ?? 'quiz' -if (!/^[a-z0-9][a-z0-9-]*$/.test(id)) { - fail(`идентификатор «${id}» не подходит`, [ +// Без --id берём его из блока метаданных в самой таблице, иначе из имени файла. +const idFromArgs = args.id ?? slug(path.basename(inputPath)) +if (args.id && !/^[a-z0-9][a-z0-9-]*$/.test(args.id)) { + fail(`идентификатор «${args.id}» не подходит`, [ 'нужны строчные латинские буквы, цифры и дефис', - 'задайте его явно: --id=novy-god', + 'пример: --id=novy-god', ]) } -const title = args.title ?? id -const decoded = decode(readFileSync(inputPath)) +const decoded = decodeTable(readFileSync(inputPath)) console.log(`\nчитаю ${path.relative(root, inputPath)} (${decoded.encoding})`) @@ -139,14 +130,18 @@ let final: { question: string; answer: string; comment?: string } | undefined if (args.final) { const finalPath = path.resolve(args.final) if (!existsSync(finalPath)) fail(`файл финала не найден: ${finalPath}`) - const parsedFinal = parseFinal(decode(readFileSync(finalPath)).text) + const parsedFinal = parseFinal(decodeTable(readFileSync(finalPath)).text) if (!parsedFinal.ok) { fail('финальный вопрос не разобрался', parsedFinal.errors.map((e) => `строка ${e.line}: ${e.message}`)) } final = parsedFinal.final } -const result = tableToPack(decoded.text, { id, title, ...(final ? { final } : {}) }) +const result = tableToPack(decoded.text, { + id: idFromArgs, + ...(args.title ? { title: args.title } : {}), + ...(final ? { final } : {}), +}) if (!result.ok) { fail('в таблице есть ошибки', result.errors.map((error) => `строка ${error.line}: ${error.message}`)) @@ -166,7 +161,9 @@ if (args.check) { process.exit(0) } -const outPath = args.out ? path.resolve(args.out) : path.join(packsDir, `${id}.json`) +const outPath = args.out + ? path.resolve(args.out) + : path.join(packsDir, `${validated.pack.id}.json`) writeFileSync(outPath, `${JSON.stringify(validated.pack, null, 2)}\n`, 'utf8') console.log(`записано: ${path.relative(root, outPath)}`) diff --git a/scripts/smoke-import.mjs b/scripts/smoke-import.mjs new file mode 100644 index 0000000..68d0b8d --- /dev/null +++ b/scripts/smoke-import.mjs @@ -0,0 +1,135 @@ +/** + * Проверка страницы импорта в браузере: перетаскивание файла, проверка, + * показ ошибок и сохранение. + * + * Требует запущенного `npm run dev` с известным токеном: + * $env:QUIZ_ROOM='TEST'; $env:QUIZ_HOST_TOKEN='smoke-token'; npm run dev + * + * Запуск: node scripts/smoke-import.mjs + */ + +import { mkdirSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import puppeteer from 'puppeteer-core' + +const BASE = process.env.QUIZ_URL ?? 'http://127.0.0.1:5173' +const TOKEN = process.env.QUIZ_HOST_TOKEN ?? 'smoke-token' +const OUT = fileURLToPath(new URL('../.screenshots/', import.meta.url)) +const ROOT = fileURLToPath(new URL('../', import.meta.url)) +const CHROME = + process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe' + +mkdirSync(OUT, { recursive: true }) + +const browser = await puppeteer.launch({ + executablePath: CHROME, + headless: 'new', + args: ['--disable-gpu', '--no-first-run', '--no-default-browser-check'], + defaultViewport: { width: 1440, height: 1100 }, +}) + +const problems = [] +const page = await browser.newPage() +page.on('pageerror', (error) => problems.push(`pageerror: ${error.message}`)) +page.on('console', (message) => { + if (message.type() === 'error') problems.push(`console: ${message.text()}`) +}) + +async function shot(name) { + await page.screenshot({ path: `${OUT}${name}.png`, fullPage: true }) + console.log(` снимок: ${name}.png`) +} + +try { + console.log('1. страница импорта') + await page.goto(`${BASE}/import/${TOKEN}`, { waitUntil: 'networkidle0' }) + await page.waitForSelector('.drop', { timeout: 15000 }) + await shot('20-import-empty') + + console.log('2. загрузка таблицы') + const input = await page.$('input[type=file]') + if (!input) throw new Error('нет поля выбора файла') + await input.uploadFile(`${ROOT}examples/questions.csv`) + await page.waitForSelector('.drop.filled', { timeout: 15000 }) + + console.log('3. проверка без записи') + const [check] = await Promise.all([ + page.waitForResponse((response) => response.url().includes('/api/import?')), + page.evaluate(() => { + const button = Array.from(document.querySelectorAll('button')).find( + (node) => node.textContent?.trim() === 'Проверить', + ) + button?.click() + }), + ]) + const checked = await check.json() + console.log(` статус ${check.status()}, клеток ${checked?.stats?.cells}`) + if (!checked?.ok) throw new Error(`проверка не прошла: ${JSON.stringify(checked)}`) + if (checked.written !== false) throw new Error('dry-run записал файл') + + await page.waitForSelector('.ok-card', { timeout: 15000 }) + const title = await page.$eval('.import-title', (node) => node.textContent?.trim()) + console.log(` название из таблицы: ${title}`) + if (title !== 'Новогодний квиз 2027') throw new Error(`не то название: ${title}`) + await shot('21-import-checked') + + console.log('4. ошибки в таблице') + // Битый файл создаём на диске, чтобы проверить показ ошибок. + const { writeFileSync } = await import('node:fs') + const broken = `${ROOT}.screenshots/broken.csv` + writeFileSync(broken, 'Тема;Стоимость;Вопрос;Ответ\nСтол;100;Без ответа;\n', 'utf8') + const input2 = await page.$('input[type=file]') + await input2.uploadFile(broken) + await page.waitForSelector('.drop.filled', { timeout: 15000 }) + + await Promise.all([ + page.waitForResponse((response) => response.url().includes('/api/import?')), + page.evaluate(() => { + const button = Array.from(document.querySelectorAll('button')).find( + (node) => node.textContent?.trim() === 'Проверить', + ) + button?.click() + }), + ]) + await page.waitForSelector('.bad-card', { timeout: 15000 }) + const errorText = await page.$eval('.error-list', (node) => node.textContent?.replace(/\s+/g, ' ')) + console.log(` ошибка: ${errorText?.trim()}`) + if (!errorText?.includes('строка 2')) throw new Error('ошибка без номера строки') + await shot('22-import-errors') + + console.log('5. сохранение и применение') + const input3 = await page.$('input[type=file]') + await input3.uploadFile(`${ROOT}examples/questions.csv`) + await page.waitForSelector('.drop.filled', { timeout: 15000 }) + + const [saved] = await Promise.all([ + page.waitForResponse( + (response) => response.url().includes('/api/import?') && !response.url().includes('dry=1'), + ), + page.evaluate(() => { + const button = Array.from(document.querySelectorAll('button')).find( + (node) => node.textContent?.trim() === 'Сохранить пак', + ) + button?.click() + }), + ]) + const saveResult = await saved.json() + if (!saveResult?.ok || !saveResult.written) throw new Error('пак не сохранился') + + await page.waitForSelector('.ok-card', { timeout: 15000 }) + await shot('23-import-saved') + + const room = await (await fetch(`${BASE}/api/room`)).json() + console.log(` комната играет пак: ${room.pack}`) + if (room.pack !== 'example') throw new Error(`пак не применился: ${room.pack}`) + + if (problems.length > 0) { + console.error('\nОшибки в консоли браузера:') + for (const problem of problems) console.error(` - ${problem}`) + process.exitCode = 1 + } else { + console.log('\nOK: импорт работает через интерфейс, ошибки показываются со строками') + } +} finally { + await browser.close() +}