Страница импорта и звуковые эффекты из файлов
- метаданные пака (название, id, финал) читаются из самого CSV - страница /import/<токен>: перетащить таблицу, проверить, сохранить - пак применяется без перезапуска сервера, если партия не начата - звуки берутся из content/sfx/, иначе используется синтез - заголовок таблицы ищется по содержимому, а не по позиции
This commit is contained in:
1 parent
2f0263e59b
commit
ea2d5d905c
21 files changed
+1529
-88
No files matched your search
+16
-19
@@ -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)}`)
|
||||
|
||||
Reference in new issue
Block a user