iptv/scripts/core/playlistParser.ts

61 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-09-22 04:17:22 +02:00
import { Collection, Storage } from '@freearhey/core'
2023-09-15 17:40:35 +02:00
import parser from 'iptv-playlist-parser'
2023-09-17 03:08:50 +02:00
import { Stream } from '../models'
import path from 'path'
import { STREAMS_DIR } from '../constants'
2023-09-15 17:40:35 +02:00
export class PlaylistParser {
storage: Storage
constructor({ storage }: { storage: Storage }) {
this.storage = storage
}
2023-09-17 03:08:50 +02:00
async parse(files: string[]): Promise<Collection> {
let streams = new Collection()
2023-09-22 05:22:47 +02:00
for (const filepath of files) {
2023-09-17 03:08:50 +02:00
const relativeFilepath = filepath.replace(path.normalize(STREAMS_DIR), '')
const _streams: Collection = await this.parseFile(relativeFilepath)
streams = streams.concat(_streams)
}
return streams
}
async parseFile(filepath: string): Promise<Collection> {
2023-09-15 17:40:35 +02:00
const streams = new Collection()
2023-09-22 04:17:22 +02:00
const content = await this.storage.load(filepath)
2023-09-15 17:40:35 +02:00
const parsed: parser.Playlist = parser.parse(content)
parsed.items.forEach((item: parser.PlaylistItem) => {
const { name, label, quality } = parseTitle(item.name)
const stream = new Stream({
channel: item.tvg.id,
name,
label,
quality,
filepath,
line: item.line,
url: item.url,
httpReferrer: item.http.referrer,
2023-11-01 03:38:07 +01:00
userAgent: item.http['user-agent'],
timeshift: item.tvg.shift
2023-09-15 17:40:35 +02:00
})
streams.add(stream)
})
2023-09-17 03:08:50 +02:00
return streams
2023-09-15 17:40:35 +02:00
}
}
function parseTitle(title: string): { name: string; label: string; quality: string } {
const [, label] = title.match(/ \[(.*)\]$/) || [null, '']
const [, quality] = title.match(/ \(([0-9]+p)\)/) || [null, '']
const name = title.replace(` (${quality})`, '').replace(` [${label}]`, '')
return { name, label, quality }
}