aboutsummaryrefslogtreecommitdiff
path: root/scripts/ytdlp_flatten.ts
blob: 6d246da15e64a12938da88e9860ec335d0a3bff6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { Config } from "./config.ts";

const ws = new WebSocket(Deno.args[0])
let config: Config = {} as unknown as Config

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}`]
    throw new Error("unknown kind");
}

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()
    const otext = new TextDecoder().decode(o.stdout)
    for (const line of otext.split("\n")) {
        if (!line.length) continue
        const ob = JSON.parse(line)
        const key = `${kind}:${ob.id}`;
        ws.send(JSON.stringify({
            t: "metadata",
            key,
            data: {
                ...data,
                title: ob.title,
                subtitle: `by ${ob.playlist_uploader}; duration ${ob.duration_string}`,
                thumbnail: ob.thumbnails[0]?.url,
                // 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: ["youtube-channel"] }))
    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: "complete", key: p.key }))
        ws.send(JSON.stringify({ t: "save" }))
        ws.send(JSON.stringify({ t: "accept" }))
    }
}