Files
dancing-summarizer/parse.ts
Lukas Wölfer 5cb3df617a Fixed parsing
2025-05-06 10:41:47 +02:00

68 lines
2.3 KiB
TypeScript

import { VideoDescription } from "./main.ts";
export function parseTemplate(description: string): Record<string, string> {
const templateRegex = /{{(.*DanceWorkshopDescription.*)}}/s;
const match = description.match(templateRegex);
if (!match) {
throw new Error("Could not find template")
}
const propertyRegex = /\|\s*(?<key>[^|]*?)\s*=(?<value>[^|}]*)\s*$/gm
const properties = match[1].matchAll(propertyRegex).map(v => {
if (!v.groups) { throw new Error("Faulty regex") };
return ({ [v.groups['key'].trim()]: v.groups['value'].trim() })
})
return Object.assign({}, ...Array.from(properties))
}
export function parseSummary(description: string, name: string): VideoDescription {
const properties = parseTemplate(description)
const b: Partial<VideoDescription> = {};
if (Object.hasOwn(properties, 'teachers')) {
console.warn(`Page ${name} has old template usage [contains 'teachers' key]`)
const t = properties['teachers'].split('&').map(item => item.trim());
b.teachers = t
} else {
b.teachers = [properties['leader'], properties['follower']].filter(v => v !== undefined)
}
b.location = properties['location']
b.date = properties['date']
b.level = properties['level']
b.event = properties['event'] || b.location
function parseBlock(header: string, text: string): string {
const regex = new RegExp(`===\\s*${header}\\s*===\\s*(?<content>(^\\s*[:*]+.*$\\s+)+)`, "m")
const match = text.match(regex)
if (!match) {
throw new Error(`Could not find block ${header}`)
}
if (!match.groups) {
throw new Error("Faulty regex")
}
return match.groups['content']
}
if (!Object.hasOwn(properties, 'patterns')) {
console.warn(`Page ${name} has old template usage [no 'patterns' key]`)
b.patterns = parseBlock("Shown Patterns", description)
} else {
b.patterns = properties['patterns']
}
if (!Object.hasOwn(properties, 'notes')) {
console.warn(`Page ${name} has old template usage [no 'notes' key]`)
b.notes = parseBlock("Notes", description)
} else {
b.notes = properties['notes']
}
return (b as VideoDescription)
}