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

- метаданные пака (название, 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

+58 -13
View File
@@ -16,6 +16,7 @@
| 4 | Телефоны игроков, QR, реконнект | ✅ | | 4 | Телефоны игроков, QR, реконнект | ✅ |
| 5 | Полировка: звук, вспышки, переходы, медиа в финале | ✅ | | 5 | Полировка: звук, вспышки, переходы, медиа в финале | ✅ |
| 6 | Импорт вопросов из CSV/Excel | ✅ | | 6 | Импорт вопросов из CSV/Excel | ✅ |
| 7 | Страница импорта и звуки из файлов | ✅ |
Играть можно по-настоящему: табло на проекторе, ведущий с ноутбука или телефона, Играть можно по-настоящему: табло на проекторе, ведущий с ноутбука или телефона,
игроки со своих телефонов. Комната одна, партия живёт в памяти сервера. игроки со своих телефонов. Комната одна, партия живёт в памяти сервера.
@@ -54,15 +55,35 @@
## Звук ## Звук
Ни одного аудиофайла: тоны синтезируются в браузере Эффекты берутся из файлов в `content/sfx/`, а если файла нет — синтезируются
([audio/sfx.ts](packages/web/src/audio/sfx.ts)). Причина практическая — на в браузере ([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/ quiz/
├─ content/packs/ паки вопросов (JSON) + content/media/ для аудио и картинок ├─ content/
│ ├─ packs/ паки вопросов (JSON)
│ ├─ media/<id>/ картинки, музыка, видео
│ └─ sfx/ звуковые эффекты (необязательно)
├─ examples/ пример таблицы для импорта ├─ examples/ пример таблицы для импорта
├─ docs/architecture.md архитектура и принятые решения ├─ docs/architecture.md архитектура и принятые решения
└─ packages/ └─ packages/
@@ -120,7 +141,33 @@ node scripts/smoke.mjs
Набивать 25 вопросов в JSON с кавычками — мучение. Набивайте в Excel или Google Набивать 25 вопросов в JSON с кавычками — мучение. Набивайте в Excel или Google
Sheets, а пак соберётся сам. Sheets, а пак соберётся сам.
Колонки (заголовок обязателен, порядок любой, регистр не важен): ### Через браузер
1. Положите картинки и музыку в `content/media/<id-пака>/`.
2. В пульте нажмите **⇪ Импорт** (или откройте `/import/<токен>`).
3. Перетащите CSV на страницу.
4. **Проверить** — покажет ошибки с номерами строк, ничего не записывая.
5. **Сохранить пак** — файл появится в `content/packs/`, и сервер сразу возьмёт
его в игру. Перезапускать ничего не нужно, если партия ещё не началась.
Страница требует токен ведущего: она пишет файлы на сервер.
### Что писать в таблице
Над заголовком — необязательный блок метаданных, по строке на значение:
```
Название;Новогодний квиз 2027
ID;novy-god-2027
Финальный вопрос;Что делают с запиской, на которой написано желание?
Финальный ответ;Сжигают, а пепел высыпают в бокал
Комментарий к финалу;Успеть до последнего удара
```
Если `Название` не указано, пак назовётся «Новогодний квиз», а `id` соберётся
из названия транслитом.
Дальше — обычная таблица (заголовок обязателен, порядок колонок любой):
| Колонка | Обязательна | Что писать | | Колонка | Обязательна | Что писать |
|---|---|---| |---|---|---|
@@ -137,12 +184,14 @@ Sheets, а пак соберётся сам.
через `;`, и это работает. Кодировка тоже любая: UTF-8 и Windows-1251 через `;`, и это работает. Кодировка тоже любая: UTF-8 и Windows-1251
(как сохраняет русский Excel) читаются обе. (как сохраняет русский Excel) читаются обе.
Готовый пример со всем сразу — [examples/questions.csv](examples/questions.csv).
### Из командной строки
```powershell ```powershell
# PowerShell: npx tsx обязателен, см. примечание ниже # 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=novy-god --title="Новогодний квиз"
# с финальным вопросом и проверкой без записи
npx tsx scripts/import-pack.ts вопросы.csv --id=test --final=финал.csv --check
``` ```
В `cmd.exe` и bash работает и короткая форма: В `cmd.exe` и bash работает и короткая форма:
@@ -155,9 +204,6 @@ npm run import -- вопросы.csv --id=novy-god
`--id=`: до скрипта доходит только имя файла. Поэтому в PowerShell вызывайте `--id=`: до скрипта доходит только имя файла. Поэтому в PowerShell вызывайте
`npx tsx scripts/import-pack.ts` напрямую. `npx tsx scripts/import-pack.ts` напрямую.
Готовый пример — [examples/questions.csv](examples/questions.csv) и
[examples/final.csv](examples/final.csv).
Что делает импортёр: Что делает импортёр:
- **ругается номерами строк** файла, а не путями в JSON: «строка 7: не указан ответ»; - **ругается номерами строк** файла, а не путями в JSON: «строка 7: не указан ответ»;
@@ -170,8 +216,7 @@ npm run import -- вопросы.csv --id=novy-god
- **прогоняет результат через ту же схему**, что и игра, — сломанный пак не - **прогоняет результат через ту же схему**, что и игра, — сломанный пак не
попадёт на диск. попадёт на диск.
Собранный пак кладётся в `content/packs/<id>.json`. Запустите игру заново — Собранный пак кладётся в `content/packs/<id>.json`.
сервер подхватит его при старте.
## Как добавить вопросы ## Как добавить вопросы
+26
View File
@@ -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/<имя>.<расширение>`.
+6
View File
@@ -1,3 +1,9 @@
Название;Новогодний квиз 2027
ID;example
Финальный вопрос;Что по традиции делают с запиской, на которой написано желание?
Финальный ответ;Сжигают, а пепел высыпают в бокал
Комментарий к финалу;Успеть до последнего удара курантов
;
Раунд;Тема;Стоимость;Вопрос;Ответ;Комментарий;Тип;Медиа Раунд;Тема;Стоимость;Вопрос;Ответ;Комментарий;Тип;Медиа
Раунд 1;Новогодний стол;100;Главный салат новогоднего стола, названный в честь французского повара;Оливье;Люсьен Оливье держал ресторан «Эрмитаж»;; Раунд 1;Новогодний стол;100;Главный салат новогоднего стола, названный в честь французского повара;Оливье;Люсьен Оливье держал ресторан «Эрмитаж»;;
Раунд 1;Новогодний стол;200;Какой цитрус в России традиционно считается новогодним фруктом?;Мандарин;;; Раунд 1;Новогодний стол;200;Какой цитрус в России традиционно считается новогодним фруктом?;Мандарин;;;
1 Раунд Название;Новогодний квиз 2027 Тема Стоимость Вопрос Ответ Комментарий Тип Медиа
1 Название;Новогодний квиз 2027
2 ID;example
3 Финальный вопрос;Что по традиции делают с запиской, на которой написано желание?
4 Финальный ответ;Сжигают, а пепел высыпают в бокал
5 Комментарий к финалу;Успеть до последнего удара курантов
6 ;
7 Раунд Раунд;Тема;Стоимость;Вопрос;Ответ;Комментарий;Тип;Медиа Тема Стоимость Вопрос Ответ Комментарий Тип Медиа
8 Раунд 1 Раунд 1;Новогодний стол;100;Главный салат новогоднего стола, названный в честь французского повара;Оливье;Люсьен Оливье держал ресторан «Эрмитаж»;; Новогодний стол 100 Главный салат новогоднего стола, названный в честь французского повара Оливье Люсьен Оливье держал ресторан «Эрмитаж»
9 Раунд 1 Раунд 1;Новогодний стол;200;Какой цитрус в России традиционно считается новогодним фруктом?;Мандарин;;; Новогодний стол 200 Какой цитрус в России традиционно считается новогодним фруктом? Мандарин
+117 -8
View File
@@ -7,14 +7,16 @@
*/ */
import { randomBytes } from 'node:crypto' import { randomBytes } from 'node:crypto'
import { existsSync } from 'node:fs' import { existsSync, readdirSync } from 'node:fs'
import path from 'node:path' import path from 'node:path'
import fastifyStatic from '@fastify/static' import fastifyStatic from '@fastify/static'
import Fastify, { type FastifyInstance } from 'fastify' import Fastify, { type FastifyInstance } from 'fastify'
import { Server } from 'socket.io' import { Server } from 'socket.io'
import type { AuthPayload, Pack } from '@quiz/shared' import type { AuthPayload, Pack } from '@quiz/shared'
import { EVENTS, makeRoomCode } from '@quiz/shared' import { EVENTS, makeRoomCode } from '@quiz/shared'
import { importPack } from './importing'
import { Room } from './room' import { Room } from './room'
import { SFX_NAMES, scanSfx } from './sfx'
export interface AppOptions { export interface AppOptions {
packs: Pack[] packs: Pack[]
@@ -23,8 +25,10 @@ export interface AppOptions {
hostToken?: string hostToken?: string
/** Каталог собранного интерфейса (packages/web/dist). */ /** Каталог собранного интерфейса (packages/web/dist). */
staticDir?: string staticDir?: string
/** Каталог с медиа (content/media). */ /** Корень контента: здесь лежат packs/, media/ и sfx/. */
mediaDir?: string contentDir?: string
/** Перечитать паки с диска: нужен после импорта, без перезапуска сервера. */
reloadPacks?: () => Pack[]
tickMs?: number tickMs?: number
logger?: boolean logger?: boolean
} }
@@ -39,6 +43,18 @@ export interface BuiltApp {
close: () => Promise<void> 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> { export async function buildApp(options: AppOptions): Promise<BuiltApp> {
const pack = options.packId const pack = options.packId
? options.packs.find((candidate) => candidate.id === 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 roomCode = (options.roomCode ?? makeRoomCode()).toUpperCase()
const hostToken = options.hostToken ?? randomBytes(6).toString('hex') 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 app = Fastify({ logger: options.logger ?? false })
const io = new Server(app.server, { const io = new Server(app.server, {
serveClient: false, serveClient: false,
@@ -92,18 +113,39 @@ export async function buildApp(options: AppOptions): Promise<BuiltApp> {
if (options.staticDir && existsSync(options.staticDir)) { if (options.staticDir && existsSync(options.staticDir)) {
await app.register(fastifyStatic, { root: options.staticDir }) await app.register(fastifyStatic, { root: options.staticDir })
} }
if (options.mediaDir && existsSync(options.mediaDir)) { if (mediaDir && existsSync(mediaDir)) {
await app.register(fastifyStatic, { await app.register(fastifyStatic, {
root: options.mediaDir, root: mediaDir,
prefix: '/media/', prefix: '/media/',
decorateReply: false, 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 () => ({ app.get('/health', async () => ({
ok: true, ok: true,
room: roomCode, room: roomCode,
pack: pack.id, pack: room.pack.id,
phase: room.state.phase, phase: room.state.phase,
players: room.state.players.length, players: room.state.players.length,
})) }))
@@ -116,12 +158,79 @@ export async function buildApp(options: AppOptions): Promise<BuiltApp> {
})), })),
) )
// Пак берём у комнаты, а не из настроек сборки: его можно подменить импортом.
app.get('/api/room', async () => ({ app.get('/api/room', async () => ({
code: roomCode, code: roomCode,
pack: pack.id, pack: room.pack.id,
title: pack.title, 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> — это маршруты одного приложения. // SPA: /board, /play и /host/<token> — это маршруты одного приложения.
app.setNotFoundHandler((request, reply) => { app.setNotFoundHandler((request, reply) => {
const url = request.raw.url ?? '' 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 repoRoot = path.resolve(here, '../../..')
const contentDir = process.env.QUIZ_CONTENT ?? path.join(repoRoot, 'content') const contentDir = process.env.QUIZ_CONTENT ?? path.join(repoRoot, 'content')
const staticDir = path.join(repoRoot, 'packages/web/dist') const staticDir = path.join(repoRoot, 'packages/web/dist')
const mediaDir = path.join(contentDir, 'media')
const { packs, problems } = loadPacks(contentDir) const { packs, problems } = loadPacks(contentDir)
@@ -37,7 +36,9 @@ const built = await buildApp({
roomCode: process.env.QUIZ_ROOM, roomCode: process.env.QUIZ_ROOM,
hostToken: process.env.QUIZ_HOST_TOKEN, hostToken: process.env.QUIZ_HOST_TOKEN,
staticDir, staticDir,
mediaDir, contentDir,
// Импорт из браузера не должен требовать перезапуска сервера.
reloadPacks: () => loadPacks(contentDir).packs.map((entry) => entry.pack),
}) })
try { try {
+46 -5
View File
@@ -74,11 +74,11 @@ function cleanName(input: unknown, fallback: string): string {
export class Room { export class Room {
readonly code: string readonly code: string
readonly pack: Pack
readonly hostToken: string readonly hostToken: string
private packValue: Pack
private engineValue: GameEngine
private readonly io: Server private readonly io: Server
private readonly engine: GameEngine
private readonly clients = new Map<string, Client>() private readonly clients = new Map<string, Client>()
private readonly playerTokens = new Map<string, string>() private readonly playerTokens = new Map<string, string>()
private readonly timer: NodeJS.Timeout private readonly timer: NodeJS.Timeout
@@ -87,10 +87,10 @@ export class Room {
constructor(options: RoomOptions) { constructor(options: RoomOptions) {
this.code = options.code.toUpperCase() this.code = options.code.toUpperCase()
this.pack = options.pack this.packValue = options.pack
this.hostToken = options.hostToken this.hostToken = options.hostToken
this.io = options.io 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 = setInterval(() => this.tick(), options.tickMs ?? 100)
this.timer.unref() this.timer.unref()
} }
@@ -99,8 +99,49 @@ export class Room {
return `room:${this.code}` return `room:${this.code}`
} }
get pack(): Pack {
return this.packValue
}
get state() { 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 { 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')
})
})
+130 -11
View File
@@ -27,8 +27,9 @@ export interface ImportError {
} }
export interface ImportOptions { export interface ImportOptions {
id: string /** Необязателен: берётся из блока метаданных или из названия. */
title: string id?: string
title?: string
settings?: Partial<PackSettings> settings?: Partial<PackSettings>
final?: { question: string; answer: string; comment?: string } final?: { question: string; answer: string; comment?: string }
} }
@@ -47,9 +48,98 @@ export interface TableRow {
export interface Table { export interface Table {
header: string[] header: string[]
/** Строки над заголовком: название игры, id, финальный вопрос. */
meta: TableRow[]
rows: TableRow[] rows: TableRow[]
} }
// ─── Метаданные пака ───────────────────────────────────────────────────────
export interface PackMeta {
id?: string
title?: string
final?: { question: string; answer: string; comment?: string }
}
const META_KEYS: Record<string, 'title' | 'id' | 'finalQuestion' | 'finalAnswer' | 'finalComment'> = {
название: 'title',
игра: 'title',
title: 'title',
id: 'id',
код: 'id',
'финальный вопрос': 'finalQuestion',
финал: 'finalQuestion',
'финальный ответ': 'finalAnswer',
'комментарий к финалу': 'finalComment',
}
/** Собирает метаданные из строк над заголовком таблицы. */
export function readMeta(rows: TableRow[]): PackMeta {
const meta: PackMeta = {}
const final: NonNullable<PackMeta['final']> = { 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<string, string> = {
а: '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 const DELIMITERS = [',', ';', '\t'] as const
function firstLine(text: string): string { function firstLine(text: string): string {
@@ -156,8 +246,31 @@ export function parseTable(text: string): Table {
if (touched || field.length > 0 || record.length > 0) pushRecord() 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<Column>()
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 table = parseTable(text)
const meta = readMeta(table.meta)
const errors: ImportError[] = [] const errors: ImportError[] = []
const packId = options.id ?? meta.id ?? slugify(options.title ?? meta.title ?? 'quiz')
const columns = new Map<Column, number>() const columns = new Map<Column, number>()
table.header.forEach((raw, index) => { table.header.forEach((raw, index) => {
@@ -358,7 +473,7 @@ export function tableToPack(text: string, options: ImportOptions): ImportResult
let media: string | undefined let media: string | undefined
if (mediaRaw) { if (mediaRaw) {
media = normalizeMediaSource(mediaRaw, options.id) media = normalizeMediaSource(mediaRaw, packId)
if (!mediaKindOf(media)) { if (!mediaKindOf(media)) {
errors.push({ errors.push({
line: row.line, line: row.line,
@@ -464,16 +579,20 @@ export function tableToPack(text: string, options: ImportOptions): ImportResult
return { id: `r${roundIndex + 1}`, title: roundTitle, themes } return { id: `r${roundIndex + 1}`, title: roundTitle, themes }
}) })
const title = options.title ?? meta.title ?? 'Новогодний квиз'
const pack: Pack = { const pack: Pack = {
id: options.id, id: packId,
title: options.title, title,
settings: { ...DEFAULT_SETTINGS, ...options.settings }, settings: { ...DEFAULT_SETTINGS, ...options.settings },
rounds, rounds,
} }
if (options.final) {
// Финальный вопрос: приоритет у явного аргумента, иначе — из метаданных.
const final = options.final ?? meta.final
if (final) {
// В паке финал — это Question, а не строка: у него есть text и answer. // В паке финал — это Question, а не строка: у него есть text и answer.
const question: Question = { text: options.final.question, answer: options.final.answer } const question: Question = { text: final.question, answer: final.answer }
if (options.final.comment) question.comment = options.final.comment if (final.comment) question.comment = final.comment
pack.final = { question } pack.final = { question }
} }
+10 -1
View File
@@ -13,11 +13,20 @@ export {
} from './pack' } from './pack'
export type { CellKeyParts, FoundCell, ParsePackResult, ParsedPack } 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 { export type {
ImportError, ImportError,
ImportOptions, ImportOptions,
ImportResult, ImportResult,
PackMeta,
Table, Table,
TableRow, TableRow,
} from './importer' } from './importer'
+76
View File
@@ -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('сборка пака', () => { describe('сборка пака', () => {
const csv = [ const csv = [
'Раунд,Тема,Стоимость,Вопрос,Ответ,Комментарий,Тип,Медиа', 'Раунд,Тема,Стоимость,Вопрос,Ответ,Комментарий,Тип,Медиа',
+77 -28
View File
@@ -1,19 +1,24 @@
/** /**
* Звуки квиза, синтезированные на месте. * Звуковые эффекты: файлы, а на случай их отсутствия — синтез.
* *
* Ни одного mp3 в репозитории: звук собирается из осцилляторов. Причина не в * Положите в content/sfx/ файл с нужным именем (correct.mp3, buzz.wav, …) —
* экономии — на площадке нечему «не загрузиться», и папку с ассетами нельзя * сервер сам отдаст его как /sfx/…, и он заменит встроенный звук. Ничего
* забыть скопировать на другой ноутбук. * настраивать не нужно: имя файла и есть настройка.
* *
* Браузер не даёт звучать до действия пользователя, поэтому на табло есть * Синтез остаётся запасным вариантом, чтобы игра звучала и на чистом проекте.
* кнопка включения: один клик при настройке — и дальше всё играет само.
*/ */
const STORAGE_KEY = 'quiz:sound' 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 context: AudioContext | null = null
let enabled = false let enabled = false
const files = new Map<SfxName, string>()
const players = new Map<SfxName, HTMLAudioElement>()
export function preferredSound(): boolean { export function preferredSound(): boolean {
try { try {
return localStorage.getItem(STORAGE_KEY) === '1' return localStorage.getItem(STORAGE_KEY) === '1'
@@ -26,6 +31,34 @@ export function soundEnabled(): boolean {
return enabled return enabled
} }
export function availableSfx(): SfxName[] {
return [...files.keys()]
}
/**
* Спрашивает у сервера, какие эффекты заменены файлами, и заранее их грузит.
* Ошибка сети не критична: останется синтез.
*/
export async function loadSfx(): Promise<void> {
try {
const response = await fetch('/api/sfx')
if (!response.ok) return
const data = (await response.json()) as { files?: Record<string, string> }
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<boolean> { export async function enableSound(): Promise<boolean> {
if (typeof window === 'undefined') return false if (typeof window === 'undefined') return false
try { try {
@@ -48,6 +81,8 @@ export function disableSound(): void {
} }
} }
// ─── Синтез (запасной вариант) ─────────────────────────────────────────────
interface ToneOptions { interface ToneOptions {
frequency: number frequency: number
duration: number duration: number
@@ -58,7 +93,7 @@ interface ToneOptions {
} }
function tone(options: ToneOptions): void { 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 start = context.currentTime + (options.delay ?? 0)
const oscillator = context.createOscillator() const oscillator = context.createOscillator()
@@ -81,32 +116,46 @@ function tone(options: ToneOptions): void {
oscillator.stop(start + options.duration + 0.03) oscillator.stop(start + options.duration + 0.03)
} }
export const sfx = { const SYNTH: Record<SfxName, () => void> = {
/** Открылась клетка. */ open: () => tone({ frequency: 520, sweepTo: 880, duration: 0.12, type: 'triangle', gain: 0.1 }),
open(): void { buzz: () => tone({ frequency: 190, sweepTo: 120, duration: 0.16, type: 'square', gain: 0.12 }),
tone({ frequency: 520, sweepTo: 880, duration: 0.12, type: 'triangle', gain: 0.1 }) correct: () => {
},
/** Кто-то нажал кнопку. */
buzz(): void {
tone({ frequency: 190, sweepTo: 120, duration: 0.16, type: 'square', gain: 0.12 })
},
/** Ответ верный. */
correct(): void {
tone({ frequency: 660, duration: 0.16, type: 'sine', gain: 0.16 }) 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 }) tone({ frequency: 990, duration: 0.24, type: 'sine', gain: 0.14, delay: 0.12 })
}, },
/** Ответ неверный или время вышло. */ wrong: () => tone({ frequency: 240, sweepTo: 110, duration: 0.38, type: 'sawtooth', gain: 0.1 }),
wrong(): void { tick: () => tone({ frequency: 1200, duration: 0.045, type: 'sine', gain: 0.05 }),
tone({ frequency: 240, sweepTo: 110, duration: 0.38, type: 'sawtooth', gain: 0.1 }) end: () => {
},
/** Последние секунды. */
tick(): void {
tone({ frequency: 1200, duration: 0.045, type: 'sine', gain: 0.05 })
},
/** Раунд или партия закончились. */
end(): void {
for (const [index, frequency] of [523, 659, 784].entries()) { for (const [index, frequency] of [523, 659, 784].entries()) {
tone({ frequency, duration: 0.5, type: 'sine', gain: 0.1, delay: index * 0.09 }) 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'),
}
+2
View File
@@ -2,6 +2,7 @@ import { createRouter, createWebHistory } from 'vue-router'
import BoardView from './views/BoardView.vue' import BoardView from './views/BoardView.vue'
import HomeView from './views/HomeView.vue' import HomeView from './views/HomeView.vue'
import HostView from './views/HostView.vue' import HostView from './views/HostView.vue'
import ImportView from './views/ImportView.vue'
import PlayerView from './views/PlayerView.vue' import PlayerView from './views/PlayerView.vue'
export const router = createRouter({ export const router = createRouter({
@@ -10,6 +11,7 @@ export const router = createRouter({
{ path: '/', name: 'home', component: HomeView }, { path: '/', name: 'home', component: HomeView },
{ path: '/board', name: 'board', component: BoardView }, { path: '/board', name: 'board', component: BoardView },
{ path: '/host/:token', name: 'host', component: HostView }, { path: '/host/:token', name: 'host', component: HostView },
{ path: '/import/:token', name: 'import', component: ImportView },
{ path: '/play', name: 'play', component: PlayerView }, { path: '/play', name: 'play', component: PlayerView },
{ path: '/:pathMatch(.*)*', redirect: '/' }, { path: '/:pathMatch(.*)*', redirect: '/' },
], ],
+145
View File
@@ -874,3 +874,148 @@ input:focus {
transform: none; 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;
}
+3 -1
View File
@@ -14,7 +14,7 @@ import BoardGrid from '../components/BoardGrid.vue'
import Countdown from '../components/Countdown.vue' import Countdown from '../components/Countdown.vue'
import QuestionMedia from '../components/QuestionMedia.vue' import QuestionMedia from '../components/QuestionMedia.vue'
import ScoreBar from '../components/ScoreBar.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 { game } from '../net/game'
import { rememberRoom, resolveRoom } from '../net/room' import { rememberRoom, resolveRoom } from '../net/room'
@@ -85,6 +85,8 @@ onMounted(async () => {
} }
rememberRoom(room.value) rememberRoom(room.value)
game.connect({ role: 'board', room: room.value }) game.connect({ role: 'board', room: room.value })
// Файловые звуки из content/sfx подхватываются до первого вопроса.
void loadSfx()
timer = setInterval(() => { timer = setInterval(() => {
now.value = Date.now() now.value = Date.now()
}, 200) }, 200)
+3
View File
@@ -147,6 +147,9 @@ function selectCell(key: string): void {
<span class="spacer" /> <span class="spacer" />
<span v-if="room" class="room-tag">комната {{ room }}</span> <span v-if="room" class="room-tag">комната {{ room }}</span>
<span v-if="state" class="phase-badge">{{ label }}</span> <span v-if="state" class="phase-badge">{{ label }}</span>
<RouterLink class="ghost" :to="`/import/${String(route.params.token ?? '')}`" title="Загрузить вопросы из таблицы">
⇪ Импорт
</RouterLink>
<button v-if="phase !== 'lobby'" class="ghost" title="Начать партию заново" @click="resetGame"> <button v-if="phase !== 'lobby'" class="ghost" title="Начать партию заново" @click="resetGame">
⟲ Заново ⟲ Заново
</button> </button>
+288
View File
@@ -0,0 +1,288 @@
<script setup lang="ts">
/**
* Загрузка пака из таблицы.
*
* Сценарий: положить медиа в content/media/<id-пака>/, подготовить CSV с
* названием игры и вопросами, перетащить файл сюда. Всё остальное — здесь.
*
* Страница требует токен ведущего: она пишет файлы на сервер, и открывать её
* кому попало нельзя.
*/
import { computed, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
interface ImportError {
line: number
message: string
}
interface ImportSuccess {
ok: true
pack: { id: string; title: string; rounds: unknown[] }
stats: { rounds: number; themes: number; cells: number }
encoding: string
missingMedia: string[]
written: boolean
file?: string
replaced: boolean
}
interface ImportFailure {
ok: false
errors: ImportError[]
}
interface PackInfo {
id: string
title: string
rounds: number
cells: number
}
interface Info {
packs: PackInfo[]
mediaFolders: string[]
sfx: Record<string, string>
sfxNames: string[]
}
const route = useRoute()
const token = computed(() => String(route.params.token ?? ''))
const info = ref<Info | null>(null)
const fatal = ref('')
const fileName = ref('')
const payload = ref<ArrayBuffer | null>(null)
const busy = ref(false)
const dragging = ref(false)
const result = ref<ImportSuccess | null>(null)
const errors = ref<ImportError[]>([])
const hasFile = computed(() => payload.value !== null)
async function refreshInfo(): Promise<void> {
try {
const response = await fetch(`/api/import/info?token=${encodeURIComponent(token.value)}`)
if (response.status === 403) {
fatal.value = 'Неверный токен ведущего'
return
}
if (!response.ok) {
fatal.value = 'Сервер не ответил'
return
}
info.value = (await response.json()) as Info
} catch {
fatal.value = 'Нет связи с сервером'
}
}
onMounted(refreshInfo)
function reset(): void {
result.value = null
errors.value = []
}
async function takeFile(file: File | undefined): Promise<void> {
if (!file) return
reset()
fileName.value = file.name
payload.value = await file.arrayBuffer()
}
function onDrop(event: DragEvent): void {
dragging.value = false
const file = event.dataTransfer?.files?.[0]
void takeFile(file)
}
function onPick(event: Event): void {
const input = event.target as HTMLInputElement
void takeFile(input.files?.[0])
}
const applied = ref('')
const applyError = ref('')
async function applyPack(id: string): Promise<void> {
applied.value = ''
applyError.value = ''
try {
const response = await fetch(
`/api/packs/apply?token=${encodeURIComponent(token.value)}&id=${encodeURIComponent(id)}`,
{ method: 'POST' },
)
const data = (await response.json()) as { ok: boolean; error?: string }
if (data.ok) applied.value = id
else applyError.value = data.error ?? 'не удалось применить пак'
} catch {
applyError.value = 'не удалось применить пак'
}
}
async function send(dry: boolean): Promise<void> {
if (!payload.value || busy.value) return
busy.value = true
reset()
try {
const query = new URLSearchParams({ token: token.value })
if (dry) query.set('dry', '1')
const response = await fetch(`/api/import?${query.toString()}`, {
method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' },
body: payload.value,
})
const data = (await response.json()) as ImportSuccess | ImportFailure | { error: string }
if (!response.ok || !('ok' in data)) {
errors.value = [{ line: 0, message: 'error' in data ? data.error : 'сервер отказал' }]
return
}
if (data.ok) {
result.value = data
if (!dry) {
// Сразу берём пак в игру: сервер разрешает это только в лобби.
await applyPack(data.pack.id)
await refreshInfo()
}
} else {
errors.value = data.errors
}
} catch {
errors.value = [{ line: 0, message: 'не удалось отправить файл' }]
} finally {
busy.value = false
}
}
</script>
<template>
<div class="shell">
<header class="topbar">
<h1>Импорт из таблицы</h1>
<span class="spacer" />
<RouterLink class="ghost" :to="`/host/${token}`">← К пульту</RouterLink>
</header>
<div v-if="fatal" class="fatal">
<h2>Импорт недоступен</h2>
<p>{{ fatal }}</p>
</div>
<main v-else class="import">
<section class="import-card">
<p class="kicker">1. Подготовьте медиа</p>
<p class="note">
Положите картинки и музыку в
<code>content/media/&lt;id-пака&gt;/</code>. В таблице достаточно имени файла —
путь допишется сам.
</p>
<p v-if="info?.mediaFolders.length" class="note">
Уже есть:
<span v-for="folder in info.mediaFolders" :key="folder" class="tag">{{ folder }}</span>
</p>
<p v-else class="note">Папок с медиа пока нет</p>
</section>
<section class="import-card">
<p class="kicker">2. Перетащите CSV</p>
<label
class="drop"
:class="{ over: dragging, filled: hasFile }"
@dragover.prevent="dragging = true"
@dragleave.prevent="dragging = false"
@drop.prevent="onDrop"
>
<input type="file" accept=".csv,.tsv,.txt,text/csv" hidden @change="onPick" />
<span v-if="!hasFile" class="drop-title">Файл таблицы</span>
<span v-else class="drop-title">{{ fileName }}</span>
<span class="drop-hint">
{{ hasFile ? 'Можно выбрать другой файл' : 'CSV или TSV, UTF-8 или Windows-1251' }}
</span>
</label>
<p class="note">
Колонки: <code>Тема</code>, <code>Стоимость</code>, <code>Вопрос</code>,
<code>Ответ</code>, по желанию <code>Раунд</code>, <code>Комментарий</code>,
<code>Тип</code>, <code>Медиа</code>. Название игры и финальный вопрос —
строками выше заголовка: <code>Название;Новогодний квиз 2027</code>.
</p>
<div class="chips">
<button class="ghost" :disabled="!hasFile || busy" @click="send(true)">
Проверить
</button>
<button class="primary" :disabled="!hasFile || busy" @click="send(false)">
{{ busy ? 'Отправляю…' : 'Сохранить пак' }}
</button>
</div>
</section>
<section v-if="errors.length" class="import-card bad-card">
<p class="kicker">Ошибки в таблице</p>
<ul class="error-list">
<li v-for="(error, index) in errors" :key="index">
<span v-if="error.line > 0" class="line-no">строка {{ error.line }}</span>
<span v-else class="line-no">пак</span>
{{ error.message }}
</li>
</ul>
</section>
<section v-if="result" class="import-card ok-card">
<p class="kicker">{{ result.written ? 'Пак сохранён' : 'Проверка пройдена' }}</p>
<p class="import-title">{{ result.pack.title }}</p>
<p class="note">
id: <code>{{ result.pack.id }}</code> · раундов {{ result.stats.rounds }} · тем
{{ result.stats.themes }} · клеток {{ result.stats.cells }} · кодировка
{{ result.encoding }}
</p>
<p v-if="result.replaced && result.written" class="note">
Пак с таким id уже был — он перезаписан.
</p>
<div v-if="result.missingMedia.length" class="warn-block">
<p class="kicker">Медиа не найдено на диске</p>
<p v-for="source in result.missingMedia" :key="source" class="warn">{{ source }}</p>
<p class="note">Вопрос сыграет без файла — проверьте папку content/media.</p>
</div>
<p v-if="applied" class="note">
Пак уже в игре — можно открывать табло. Если партия была начата, сервер
попросит нажать «⟲ Заново».
</p>
<p v-if="applyError" class="warn">{{ applyError }}</p>
</section>
<section v-if="info?.packs.length" class="import-card">
<p class="kicker">Паки на диске</p>
<ul class="pack-list">
<li v-for="pack in info.packs" :key="pack.id">
<b>{{ pack.title }}</b>
<span class="note">{{ pack.id }} · {{ pack.rounds }} р. · {{ pack.cells }} вопросов</span>
</li>
</ul>
</section>
<section class="import-card">
<p class="kicker">Звуковые эффекты</p>
<p class="note">
Сейчас из файлов:
<template v-if="Object.keys(info?.sfx ?? {}).length">
<span v-for="(url, name) in info?.sfx" :key="name" class="tag">{{ name }}</span>
</template>
<template v-else>ни одного, играет встроенный синтез</template>
</p>
<p class="note">
Положите файл в <code>content/sfx/</code> с именем
<code>correct.mp3</code>, <code>wrong.wav</code>, <code>buzz.mp3</code>,
<code>open.mp3</code>, <code>tick.mp3</code> или <code>end.mp3</code> — он
заменит встроенный звук.
</p>
</section>
</main>
</div>
</template>
+1
View File
@@ -25,6 +25,7 @@ export default defineConfig({
'/socket.io': { target: 'http://127.0.0.1:3000', ws: true }, '/socket.io': { target: 'http://127.0.0.1:3000', ws: true },
'/api': { target: 'http://127.0.0.1:3000' }, '/api': { target: 'http://127.0.0.1:3000' },
'/media': { target: 'http://127.0.0.1:3000' }, '/media': { target: 'http://127.0.0.1:3000' },
'/sfx': { target: 'http://127.0.0.1:3000' },
}, },
}, },
}) })
+16 -19
View File
@@ -15,7 +15,7 @@
import { existsSync, readFileSync, writeFileSync } from 'node:fs' import { existsSync, readFileSync, writeFileSync } from 'node:fs'
import path from 'node:path' import path from 'node:path'
import { fileURLToPath } from 'node:url' 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 root = fileURLToPath(new URL('../', import.meta.url))
const packsDir = path.join(root, 'content', 'packs') 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 { function slug(input: string): string {
return input return input
.replace(/\.(csv|tsv|txt)$/i, '') .replace(/\.(csv|tsv|txt)$/i, '')
@@ -122,16 +113,16 @@ if (args.help || !args.input) {
const inputPath = path.resolve(args.input) const inputPath = path.resolve(args.input)
if (!existsSync(inputPath)) fail(`файл не найден: ${inputPath}`) if (!existsSync(inputPath)) fail(`файл не найден: ${inputPath}`)
const id = args.id ?? slug(path.basename(inputPath)) ?? 'quiz' // Без --id берём его из блока метаданных в самой таблице, иначе из имени файла.
if (!/^[a-z0-9][a-z0-9-]*$/.test(id)) { const idFromArgs = args.id ?? slug(path.basename(inputPath))
fail(`идентификатор «${id}» не подходит`, [ 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 = decodeTable(readFileSync(inputPath))
const decoded = decode(readFileSync(inputPath))
console.log(`\nчитаю ${path.relative(root, inputPath)} (${decoded.encoding})`) 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) { if (args.final) {
const finalPath = path.resolve(args.final) const finalPath = path.resolve(args.final)
if (!existsSync(finalPath)) fail(`файл финала не найден: ${finalPath}`) if (!existsSync(finalPath)) fail(`файл финала не найден: ${finalPath}`)
const parsedFinal = parseFinal(decode(readFileSync(finalPath)).text) const parsedFinal = parseFinal(decodeTable(readFileSync(finalPath)).text)
if (!parsedFinal.ok) { if (!parsedFinal.ok) {
fail('финальный вопрос не разобрался', parsedFinal.errors.map((e) => `строка ${e.line}: ${e.message}`)) fail('финальный вопрос не разобрался', parsedFinal.errors.map((e) => `строка ${e.line}: ${e.message}`))
} }
final = parsedFinal.final 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) { if (!result.ok) {
fail('в таблице есть ошибки', result.errors.map((error) => `строка ${error.line}: ${error.message}`)) fail('в таблице есть ошибки', result.errors.map((error) => `строка ${error.line}: ${error.message}`))
@@ -166,7 +161,9 @@ if (args.check) {
process.exit(0) 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') writeFileSync(outPath, `${JSON.stringify(validated.pack, null, 2)}\n`, 'utf8')
console.log(`записано: ${path.relative(root, outPath)}`) console.log(`записано: ${path.relative(root, outPath)}`)
+135
View File
@@ -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()
}