/
ytdl.go
87 lines (73 loc) · 2.05 KB
/
ytdl.go
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package ytdlwrapper
import (
"bufio"
"context"
"encoding/json"
"os/exec"
)
// A Wrapper for the youtube-dl binary
type Wrapper struct {
BinPath string
}
// Info returns information about the URL, like if it is
// a playlist or a single video.
func (wrapper *Wrapper) Info(ctx context.Context, url string) (*InfoOutput, error) {
output, err := exec.CommandContext(ctx, wrapper.BinPath, "-J", "--flat-playlist", "--no-playlist", url).Output()
if err != nil {
return nil, err
}
unknown := unknownInfo{}
err = json.Unmarshal(output, &unknown)
if err != nil {
return nil, err
}
infoOutput := InfoOutput{}
if unknown.Type == "playlist" {
err = json.Unmarshal(output, &infoOutput.Playlist)
infoOutput.IsPlaylist = true
} else {
err = json.Unmarshal(output, &infoOutput.Entry)
infoOutput.IsPlaylist = false
}
return &infoOutput, err
}
// Update youtube-dl
func (wrapper *Wrapper) Update(ctx context.Context) error {
_, err := exec.CommandContext(ctx, wrapper.BinPath, "-U").Output()
return err
}
// Download the given URL using youtube-dl
func (wrapper *Wrapper) Download(ctx context.Context, url string, args ...string) ([]byte, error) {
args = append(args, url)
return exec.CommandContext(ctx, wrapper.BinPath, args...).Output()
}
// DownloadWithProgress downloads the given URL using youtube-dl and provides progress updates
func (wrapper *Wrapper) DownloadWithProgress(ctx context.Context, callback func(*DownloadProgress), url string, args ...string) error {
args = append(args, "--newline", url)
cmd := exec.CommandContext(ctx, wrapper.BinPath, args...)
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
err = cmd.Start()
if err != nil {
return err
}
go func() {
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
rawProgress := scanner.Bytes()
parsedProgress := parseProgressLine(rawProgress)
if parsedProgress != nil {
callback(parsedProgress)
}
}
}()
return cmd.Wait()
}
// Make a default instance of the youtube-dl wrapper
func Make() *Wrapper {
return &Wrapper{
BinPath: "youtube-dl",
}
}