-
Notifications
You must be signed in to change notification settings - Fork 6
/
dl.go
74 lines (58 loc) · 2.07 KB
/
dl.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
package main
import (
"context"
"fmt"
"io"
"time"
"github.com/wader/goutubedl"
)
const downloadAndConvertTimeout = 5 * time.Minute
type ConvertStartCallbackFunc func(ctx context.Context, videoCodecs, audioCodecs, convertActionsNeeded string)
type UpdateProgressPercentCallbackFunc func(progressStr string, progressPercent int)
type Downloader struct {
ConvertStartFunc ConvertStartCallbackFunc
UpdateProgressPercentFunc UpdateProgressPercentCallbackFunc
}
type goYouTubeDLLogger struct{}
func (l goYouTubeDLLogger) Print(v ...interface{}) {
fmt.Print(" yt-dlp dbg:")
fmt.Println(v...)
}
func (d *Downloader) downloadURL(dlCtx context.Context, url string) (rr *ReReadCloser, title string, err error) {
result, err := goutubedl.New(dlCtx, url, goutubedl.Options{
Type: goutubedl.TypeSingle,
DebugLog: goYouTubeDLLogger{},
// StderrFn: func(cmd *exec.Cmd) io.Writer { return io.Writer(os.Stdout) },
MergeOutputFormat: "mkv", // This handles VP9 properly. yt-dlp uses mp4 by default, which doesn't.
SortingFormat: "res:720", // Prefer videos no larger than 720p to keep their size small.
})
if err != nil {
return nil, "", fmt.Errorf("preparing download %q: %w", url, err)
}
dlResult, err := result.Download(dlCtx, "")
if err != nil {
return nil, "", fmt.Errorf("downloading %q: %w", url, err)
}
return NewReReadCloser(dlResult), result.Info.Title, nil
}
func (d *Downloader) DownloadAndConvertURL(ctx context.Context, url, format string) (r io.ReadCloser, outputFormat, title string, err error) {
rr, title, err := d.downloadURL(ctx, url)
if err != nil {
return nil, "", "", err
}
conv := Converter{
Format: format,
UpdateProgressPercentCallback: d.UpdateProgressPercentFunc,
}
if err := conv.Probe(rr); err != nil {
return nil, "", "", err
}
if d.ConvertStartFunc != nil {
d.ConvertStartFunc(ctx, conv.VideoCodecs, conv.AudioCodecs, conv.GetActionsNeeded())
}
r, outputFormat, err = conv.ConvertIfNeeded(ctx, rr)
if err != nil {
return nil, "", "", err
}
return r, outputFormat, title, nil
}