Files
fly-quiz/scripts/check-media.mjs
T
oskarvitalii 7dfe61695d Музыка и видео играют на табло, пульт управляет
- канал media: пульт шлёт действие, сервер передаёт табло
- табло отчитывается о воспроизведении, пульт показывает статус и время
- на пульте больше нет своего аудиоэлемента
- проверка scripts/check-media.mjs: время растёт на табло, пауза доходит
2026-11-18 20:34:59 +07:00

213 lines
8.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Проверка музыкального вопроса: играет табло, а не пульт.
*
* Требует запущенного сервера:
* $env:PORT='3100'; $env:QUIZ_ROOM='TEST'; $env:QUIZ_HOST_TOKEN='smoke-token'; npm start
* $env:QUIZ_URL='http://127.0.0.1:3100'; node scripts/check-media.mjs
*/
import { writeFileSync, rmSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import puppeteer from 'puppeteer-core'
import { io } from 'socket.io-client'
const BASE = process.env.QUIZ_URL ?? 'http://127.0.0.1:3100'
const TOKEN = process.env.QUIZ_HOST_TOKEN ?? 'smoke-token'
const ROOM = process.env.QUIZ_ROOM ?? 'TEST'
const ROOT = fileURLToPath(new URL('../', import.meta.url))
const PACK_ID = 'media-check'
const PACK_FILE = `${ROOT}content/packs/${PACK_ID}.json`
const CHROME =
process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe'
const pack = {
id: PACK_ID,
title: 'Проверка музыки',
settings: {
wrongPenalty: 'value',
buzzers: true,
finalEnabled: false,
defaultTimeLimit: 40,
answerTimeLimit: 20,
auctionTimeLimit: 30,
betTimeLimit: 20,
},
rounds: [
{
id: 'r1',
title: 'Раунд с музыкой',
themes: [
{
id: 't1',
title: 'Музыка',
cells: [
{
value: 100,
kind: 'normal',
question: {
media: { kind: 'audio', src: '/media/demo/jingle-bells.wav' },
answer: 'Jingle Bells',
},
},
],
},
],
},
],
}
async function connectAs(auth) {
const socket = io(BASE, { auth, transports: ['websocket'], reconnection: false })
await new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('не подключился')), 10000)
socket.once('hello', () => {
clearTimeout(timer)
resolve()
})
socket.once('connect_error', (error) => {
clearTimeout(timer)
reject(error)
})
})
return socket
}
// Чистое лобби: иначе пак не подменить.
const resetter = await connectAs({ room: ROOM, role: 'host', token: TOKEN })
resetter.emit('cmd', { cmdId: 'media-reset', command: { type: 'resetGame' } })
await new Promise((resolve) => setTimeout(resolve, 400))
resetter.disconnect()
writeFileSync(PACK_FILE, JSON.stringify(pack, null, 2), 'utf8')
const applied = await (
await fetch(`${BASE}/api/packs/apply?token=${TOKEN}&id=${PACK_ID}`, { method: 'POST' })
).json()
if (!applied.ok) throw new Error(`пак не применился: ${applied.error}`)
const player = await connectAs({ room: ROOM, role: 'player', name: 'Тест' })
const browser = await puppeteer.launch({
executablePath: CHROME,
headless: 'new',
args: [
'--disable-gpu',
'--no-first-run',
// Без этого Chrome в headless не запускает звук без клика мышью.
'--autoplay-policy=no-user-gesture-required',
'--mute-audio',
],
defaultViewport: { width: 1600, height: 900 },
})
const problems = []
try {
const board = await browser.newPage()
board.on('pageerror', (error) => problems.push(`board: ${error.message}`))
await board.goto(`${BASE}/board`, { waitUntil: 'networkidle0' })
await board.waitForSelector('.lobby-join', { timeout: 15000 })
const host = await browser.newPage()
host.on('pageerror', (error) => problems.push(`host: ${error.message}`))
await host.goto(`${BASE}/host/${TOKEN}`, { waitUntil: 'networkidle0' })
await host.waitForSelector('.topbar', { timeout: 15000 })
console.log('1. старт партии')
await host.evaluate(() => {
const button = Array.from(document.querySelectorAll('button.primary.big')).find((node) =>
node.textContent?.includes('Начать игру'),
)
button?.click()
})
await host.waitForSelector('.round-title', { timeout: 10000 })
await host.evaluate(() => {
const button = Array.from(document.querySelectorAll('button.primary.big')).find((node) =>
node.textContent?.includes('К табло'),
)
button?.click()
})
await host.waitForSelector('.board', { timeout: 10000 })
console.log('2. открываю музыкальный вопрос')
await host.click('.cell:not(.closed)')
await host.waitForSelector('.media-remote', { timeout: 10000 })
const onHost = await host.$eval('.remote-note', (node) => node.textContent?.replace(/\s+/g, ' ').trim())
console.log(` пульт: ${onHost ?? 'нет статуса'}`)
console.log('3. жму «Играть» на пульте')
await host.evaluate(() => {
const button = Array.from(document.querySelectorAll('.media-remote button')).find((node) =>
node.textContent?.includes('Играть'),
)
button?.click()
})
// Chrome приостанавливает медиа в фоновой вкладке, поэтому табло выводим
// вперёд — в жизни оно и так всегда на экране проектора.
await board.bringToFront()
await new Promise((resolve) => setTimeout(resolve, 1500))
/** Снимаем два замера: иначе не понять, идёт время или стоит на нуле. */
async function sample() {
return board.evaluate(() => {
const node = document.querySelector('audio')
if (!node) return null
return {
paused: node.paused,
time: node.currentTime,
duration: node.duration,
ready: node.readyState,
}
})
}
const audio = await sample()
console.log(
` табло: ${audio ? `paused=${audio.paused}, время=${audio.time.toFixed(2)}с, длительность=${Number.isFinite(audio.duration) ? audio.duration.toFixed(1) : '?'}с, ready=${audio.ready}` : 'нет элемента'}`,
)
await new Promise((resolve) => setTimeout(resolve, 1200))
const later = await sample()
console.log(` через секунду: время=${later?.time.toFixed(2)}с, paused=${later?.paused}`)
if (audio && later && Number.isFinite(audio.duration) && audio.duration > 0 && later.time <= audio.time) {
throw new Error('время не растёт — воспроизведение не идёт')
}
if (!audio) throw new Error('на табло нет элемента audio')
if (audio.paused) throw new Error('табло не играет — команда не дошла')
// Проверяем, что пульт сам НЕ создал свой audio.
const hostAudio = await host.evaluate(() => document.querySelectorAll('audio').length)
console.log(` аудиоэлементов на пульте: ${hostAudio}`)
if (hostAudio > 0) throw new Error('пульт всё ещё играет сам')
const afterPlay = await host.$eval('.remote-note', (node) => node.textContent?.replace(/\s+/g, ' ').trim())
console.log(` пульт видит: ${afterPlay}`)
if (!afterPlay?.includes('играет')) throw new Error(`пульт не узнал о воспроизведении: ${afterPlay}`)
console.log('4. пауза с пульта')
await host.bringToFront()
await host.evaluate(() => {
const button = Array.from(document.querySelectorAll('.media-remote button')).find((node) =>
node.textContent?.includes('Пауза'),
)
button?.click()
})
await board.bringToFront()
await new Promise((resolve) => setTimeout(resolve, 700))
const paused = await board.evaluate(() => document.querySelector('audio')?.paused)
console.log(` табло на паузе: ${paused}`)
if (!paused) throw new Error('пауза не дошла до табло')
if (problems.length > 0) {
console.error('\nОшибки на страницах:')
for (const problem of problems) console.error(` - ${problem}`)
process.exitCode = 1
} else {
console.log('\nOK: музыка играет на табло, пульт только управляет')
}
} finally {
player.disconnect()
await browser.close()
await fetch(`${BASE}/api/packs/apply?token=${TOKEN}&id=novy-god-2027`, { method: 'POST' })
rmSync(PACK_FILE, { force: true })
}