Files
StreamPlaylistArchive/scripts/clean.ts
2025-08-03 16:42:23 -05:00

87 lines
2.5 KiB
TypeScript

/*
* this is a deno script to clean up the m3u8 files from the music player
*
*/
import { opendir, readFile, writeFile } from 'node:fs/promises';
import * as path from "jsr:@std/path";
import { Dirent } from 'node:fs';
/**
* longEnough will be true if splitting the line gave 3+ sections, and false if it's too short
*
* @param cleanLine
* @returns [cleanLine, longEnough]
*/
function replaceLineDashes(cleanLine: string): [string, boolean] {
const spl = cleanLine.split(' - ')
if (spl.length < 3) {
return [spl.join(' // '), false]
}
const [spl1, spl2, ...splRemain] = spl
const spl3 = splRemain.join(' - ')
return [[spl1, spl2, spl3].join(' // '), true]
}
// loop through every line of the file and clean up each line
function cleanFile(dirent: Dirent, content: string): string {
const lines = content.split('\n')
const cleanLines: string[] = []
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim()
if (!line || line.startsWith("#")) {
continue
}
const ext = path.extname(line)
const name = path.basename(line, ext)
let cleanLine = name
.replace(/ - Single/g, '')
.replace(/- \d+ -/g, '-')
const [updatedCleanLine, longEnough] = replaceLineDashes(cleanLine)
cleanLine = updatedCleanLine
if (!longEnough) {
cleanLine = `BAD LINE --- ${cleanLine}`
const fileName = path.basename(dirent.name)
console.log(`Bad Line found in ${fileName} on line ${i+1}: \t${line}`)
}
cleanLines.push(cleanLine)
}
return cleanLines.join('\n') + '\n'
}
// get details from the file, ensure it's a playlist file, then store the updated file contents to a txt file
async function processFile(dirent: Dirent) {
if (dirent.isFile()) {
const ext = path.extname(dirent.name)
const name = path.basename(dirent.name, ext)
const dirname = path.dirname(dirent.name)
const newPath = path.join(dirname, `${name}.txt`)
if (ext.toUpperCase() === ".M3U8") {
const fileContent = await readFile(dirent.name)
const cleanContent = cleanFile(dirent, fileContent.toString())
await writeFile(newPath, cleanContent)
}
}
}
// loop through every file in the current directory
try {
const dir = await opendir('./');
for await (const dirent of dir) {
await processFile(dirent)
}
} catch (err) {
console.error(err)
}