import { Config } from "./config.ts"; const ws = new WebSocket(Deno.args[0]) let config: Config = {} as unknown as Config const supported = [ "youtube-channel", "bilibili-channel", ] function key_to_url(key: string): [string, string] { const [kind, id] = key.split(":", 2) if (kind == "youtube-channel") return ["youtube", `https://youtube.com/channel/${id}`] if (kind == "bilibili-channel") return ["bilibili", `https://space.bilibili.com/${id}/upload/video`] throw new Error("unknown kind"); } function key_to_infokey(key: string): string { const [kind, id] = key.split(":", 2) return `${kind}-info:${id}` } async function flat_playlist(url: string, kind: string, data: { [key: string]: unknown }) { const flags = (data.flags as string[]) ?? [] if (!(flags instanceof Array)) throw new Error("flags is not an array"); const filter_parts = flags.map(e => config.ytdlp_flatten.filters[e]).join(" & ") const filter_args = flags.length ? ["--match-filter", filter_parts] : [] const o = await new Deno.Command("yt-dlp", { args: [ "--flat-playlist", "--print-json", ...filter_args, url ], stdout: "piped", stderr: "inherit", }).output() if (!o.success) throw new Error("yt-dlp failure code"); const otext = new TextDecoder().decode(o.stdout) for (const line of otext.split("\n")) { if (!line.length) continue const ob = JSON.parse(line) console.log(ob); const key = `${kind}:${ob.id}`; ws.send(JSON.stringify({ t: "metadata", key, data: { ...data, title: ob.title, subtitle: `by ${ob.playlist_uploader ?? data.output ?? "unknown"}; duration ${ob.duration_string}`, thumbnail: ob.thumbnails ? ob.thumbnails[0]?.url : null, // description: ob.description, } })) ws.send(JSON.stringify({ t: "enqueue", key })) } console.log("done"); } ws.onerror = () => console.error("ws error") ws.onclose = () => { console.error("ws closed") Deno.exit(1) } ws.onopen = () => { console.log("ws open"); ws.send(JSON.stringify({ t: "register", name: "yt-dlp playlist flattener", task_kinds: supported })) ws.send(JSON.stringify({ t: "accept" })) } ws.onmessage = async ev => { if (typeof ev.data != "string") return const p = JSON.parse(ev.data) if (p.t == "config") config = p.config if (p.t == "error") console.error(`error: ${p.message}`); if (p.t == "work") { const [outkind, url] = key_to_url(p.key) if (!p.data.output) throw new Error("no output"); await flat_playlist(url, outkind, p.data) ws.send(JSON.stringify({ t: "enqueue", key: key_to_infokey(p.key) })) ws.send(JSON.stringify({ t: "complete", key: p.key })) ws.send(JSON.stringify({ t: "save" })) ws.send(JSON.stringify({ t: "accept" })) } }