1
0
Fork 0
peertube/packages/core-utils/src/string/chapters.ts

36 lines
888 B
TypeScript
Raw Normal View History

2023-08-28 08:55:04 +00:00
import { timeToInt, timecodeRegexString } from '../common/date.js'
const timecodeRegex = new RegExp(`^(${timecodeRegexString})\\s`)
2023-11-29 13:11:57 +00:00
export function parseChapters (text: string, maxTitleLength: number) {
2023-08-28 08:55:04 +00:00
if (!text) return []
const lines = text.split(/\r?\n|\r|\n/g)
let foundChapters = false
const chapters: { timecode: number, title: string }[] = []
for (const line of lines) {
const matched = line.match(timecodeRegex)
if (!matched) {
// Stop chapters parsing
if (foundChapters) break
continue
}
foundChapters = true
const timecodeText = matched[1]
const timecode = timeToInt(timecodeText)
const title = line.replace(matched[0], '')
2023-11-29 13:11:57 +00:00
chapters.push({ timecode, title: title.slice(0, maxTitleLength) })
2023-08-28 08:55:04 +00:00
}
2023-11-29 13:11:57 +00:00
// Only consider chapters if there are more than one
if (chapters.length > 1) return chapters
return []
2023-08-28 08:55:04 +00:00
}