1 Commits

Author SHA1 Message Date
8408e12a2a Add HTTPChunkSize option (--http-chunk-size)
Switch to _test test package to make sure to test external API.
Also don't ignore download process wait error
2021-06-28 20:09:32 +02:00
5 changed files with 50 additions and 91 deletions

View File

@ -1,22 +1,17 @@
# bump: golang /GOLANG_VERSION=([\d.]+)/ docker:golang|^1 # bump: golang /GOLANG_VERSION=([\d.]+)/ docker:golang|^1
# bump: golang link "Release notes" https://golang.org/doc/devel/release.html # bump: golang link "Release notes" https://golang.org/doc/devel/release.html
ARG GOLANG_VERSION=1.20.5 ARG GOLANG_VERSION=1.16.5
# bump: yt-dlp /YT_DLP=([\d.-]+)/ https://github.com/yt-dlp/yt-dlp.git|/^\d/|sort # bump: youtube-dl /YDL_VERSION=([\d.]+)/ https://github.com/ytdl-org/youtube-dl.git|/^\d/|sort
# bump: yt-dlp link "Release notes" https://github.com/yt-dlp/yt-dlp/releases/tag/$LATEST # bump: youtube-dl link "Release notes" https://github.com/ytdl-org/youtube-dl/releases/tag/$LATEST
ARG YT_DLP=2023.06.21 ARG YDL_VERSION=2021.06.06
FROM golang:$GOLANG_VERSION AS base FROM golang:$GOLANG_VERSION
ARG YT_DLP ARG YDL_VERSION
RUN \ RUN \
apt-get update -q && \ curl -L -o /usr/local/bin/youtube-dl https://yt-dl.org/downloads/$YDL_VERSION/youtube-dl && \
apt-get install -y -q python-is-python3 && \ chmod a+x /usr/local/bin/youtube-dl
curl -L https://github.com/yt-dlp/yt-dlp/releases/download/$YT_DLP/yt-dlp -o /usr/local/bin/yt-dlp && \
chmod a+x /usr/local/bin/yt-dlp
FROM base AS dev
FROM base
WORKDIR /src WORKDIR /src
COPY go.* *.go ./ COPY go.* *.go ./
COPY cmd cmd COPY cmd cmd

View File

@ -1,15 +1,12 @@
## goutubedl ## goutubedl
Go wrapper for [youtube-dl](https://github.com/ytdl-org/youtube-dl) and [yt-dlp](https://github.com/yt-dlp/yt-dlp), currently tested and Go wrapper for [youtube-dl](https://github.com/ytdl-org/youtube-dl). API documentation can be found at [godoc.org](https://pkg.go.dev/github.com/wader/goutubedl?tab=doc).
developed using yt-dlp.
API documentation can be found at [godoc.org](https://pkg.go.dev/github.com/wader/goutubedl?tab=doc).
See [yt-dlp documentation](https://github.com/yt-dlp/yt-dlp) for how to See [youtube-dl documentation](https://github.com/ytdl-org/youtube-dl) for how to
install and what is recommended to install in addition to youtube-dl. install and what is recommended to install in addition to youtube-dl.
goutubedl default uses `PATH` to find youtube-dl but it can be configured with the `goutubedl.Path` goutubedl default uses `PATH` to find youtube-dl but it can be configured with the `goutubedl.Path`
variable. Default is currently `youtube-dl` for backwards compability. If your using yt-dlp you variable.
probably want to set it to `yt-dlp`.
Due to the nature and frequent updates of youtube-dl only the latest version Due to the nature and frequent updates of youtube-dl only the latest version
is tested. But it seems to work well with older versions also. is tested. But it seems to work well with older versions also.

View File

@ -15,23 +15,17 @@ var dumpFlag = flag.Bool("J", false, "Dump JSON")
var typeFlag = flag.String("t", "any", "Type") var typeFlag = flag.String("t", "any", "Type")
func main() { func main() {
goutubedl.Path = "yt-dlp"
log.SetFlags(0) log.SetFlags(0)
flag.Parse() flag.Parse()
optType := goutubedl.TypeFromString[*typeFlag] optType, _ := goutubedl.TypeFromString[*typeFlag]
result, err := goutubedl.New( result, err := goutubedl.New(context.Background(), flag.Arg(0), goutubedl.Options{Type: optType})
context.Background(),
flag.Arg(0),
goutubedl.Options{Type: optType, DebugLog: log.Default()},
)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
if *dumpFlag { if *dumpFlag {
_ = json.NewEncoder(os.Stdout).Encode(result.Info) json.NewEncoder(os.Stdout).Encode(result.Info)
return return
} }
@ -50,8 +44,6 @@ func main() {
log.Fatal(err) log.Fatal(err)
} }
defer f.Close() defer f.Close()
if _, err := io.Copy(f, dr); err != nil { io.Copy(f, dr)
log.Fatal(err)
}
dr.Close() dr.Close()
} }

View File

@ -202,14 +202,13 @@ var TypeFromString = map[string]Type{
// Options for New() // Options for New()
type Options struct { type Options struct {
Type Type Type Type
PlaylistStart uint // --playlist-start PlaylistStart uint // --playlist-start
PlaylistEnd uint // --playlist-end PlaylistEnd uint // --playlist-end
Downloader string // --downloader
DownloadThumbnail bool DownloadThumbnail bool
DownloadSubtitles bool DownloadSubtitles bool
ProxyUrl string // --proxy URL http://host:port or socks5://host:port
DebugLog Printer DebugLog Printer
StderrFn func(cmd *exec.Cmd) io.Writer // if not nil, function to get Writer for stderr StderrFn func(cmd *exec.Cmd) io.Writer // if not nil, function to get Writer for stderr
HTTPChunkSize uint // --http-chunk-size
HTTPClient *http.Client // Client for download thumbnail and subtitles (nil use http.DefaultClient) HTTPClient *http.Client // Client for download thumbnail and subtitles (nil use http.DefaultClient)
} }
@ -260,15 +259,6 @@ func infoFromURL(ctx context.Context, rawURL string, options Options) (info Info
"--batch-file", "-", "--batch-file", "-",
"-J", "-J",
) )
if options.ProxyUrl != "" {
cmd.Args = append(cmd.Args, "--proxy", options.ProxyUrl)
}
if options.Downloader != "" {
cmd.Args = append(cmd.Args, "--downloader", options.Downloader)
}
if options.Type == TypePlaylist { if options.Type == TypePlaylist {
cmd.Args = append(cmd.Args, "--yes-playlist") cmd.Args = append(cmd.Args, "--yes-playlist")
@ -465,13 +455,8 @@ func (result Result) Download(ctx context.Context, filter string) (*DownloadResu
if !result.Info.Direct { if !result.Info.Direct {
cmd.Args = append(cmd.Args, "-f", filter) cmd.Args = append(cmd.Args, "-f", filter)
} }
if result.Options.HTTPChunkSize != 0 {
if result.Options.ProxyUrl != "" { cmd.Args = append(cmd.Args, "--http-chunk-size", fmt.Sprintf("%d", result.Options.HTTPChunkSize))
cmd.Args = append(cmd.Args, "--proxy", result.Options.ProxyUrl)
}
if result.Options.Downloader != "" {
cmd.Args = append(cmd.Args, "--downloader", result.Options.Downloader)
} }
cmd.Dir = tempPath cmd.Dir = tempPath
@ -491,14 +476,16 @@ func (result Result) Download(ctx context.Context, filter string) (*DownloadResu
return nil, err return nil, err
} }
var waitErr error
go func() { go func() {
_ = cmd.Wait() waitErr = cmd.Wait()
w.Close() w.Close()
os.RemoveAll(tempPath) os.RemoveAll(tempPath)
close(dr.waitCh) close(dr.waitCh)
}() }()
return dr, nil return dr, waitErr
} }
func (dr *DownloadResult) Read(p []byte) (n int, err error) { func (dr *DownloadResult) Read(p []byte) (n int, err error) {

View File

@ -18,11 +18,6 @@ import (
"github.com/wader/osleaktest" "github.com/wader/osleaktest"
) )
func init() {
// we're using yt-dlp at the moment
goutubedl.Path = "yt-dlp"
}
const testVideoRawURL = "https://www.youtube.com/watch?v=C0DPdy98e4c" const testVideoRawURL = "https://www.youtube.com/watch?v=C0DPdy98e4c"
const playlistRawURL = "https://soundcloud.com/mattheis/sets/kindred-phenomena" const playlistRawURL = "https://soundcloud.com/mattheis/sets/kindred-phenomena"
const subtitlesTestVideoRawURL = "https://www.youtube.com/watch?v=QRS8MkLhQmM" const subtitlesTestVideoRawURL = "https://www.youtube.com/watch?v=QRS8MkLhQmM"
@ -63,15 +58,21 @@ func TestVersion(t *testing.T) {
} }
} }
func TestDownload(t *testing.T) { func testDownload(t *testing.T, rawURL string, optionsFn func(options *goutubedl.Options)) {
defer leakChecks(t)() defer leakChecks(t)()
stderrBuf := &bytes.Buffer{} stderrBuf := &bytes.Buffer{}
r, err := goutubedl.New(context.Background(), testVideoRawURL, goutubedl.Options{
options := goutubedl.Options{
StderrFn: func(cmd *exec.Cmd) io.Writer { StderrFn: func(cmd *exec.Cmd) io.Writer {
return stderrBuf return stderrBuf
}, },
}) }
if optionsFn != nil {
optionsFn(&options)
}
r, err := goutubedl.New(context.Background(), rawURL, options)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -90,8 +91,8 @@ func TestDownload(t *testing.T) {
t.Errorf("copy n not equal to download buffer: %d!=%d", n, downloadBuf.Len()) t.Errorf("copy n not equal to download buffer: %d!=%d", n, downloadBuf.Len())
} }
if n < 10000 { if n < 29000 {
t.Errorf("should have copied at least 10000 bytes: %d", n) t.Errorf("should have copied at least 29000 bytes: %d", n)
} }
if !strings.Contains(stderrBuf.String(), "Destination") { if !strings.Contains(stderrBuf.String(), "Destination") {
@ -99,6 +100,18 @@ func TestDownload(t *testing.T) {
} }
} }
func TestDownload(t *testing.T) {
defer leakChecks(t)()
testDownload(t, testVideoRawURL, nil)
}
func TestHTTPChunkSize(t *testing.T) {
defer leakChecks(t)()
testDownload(t, testVideoRawURL, func(options *goutubedl.Options) {
options.HTTPChunkSize = 1000000
})
}
func TestParseInfo(t *testing.T) { func TestParseInfo(t *testing.T) {
for _, c := range []struct { for _, c := range []struct {
url string url string
@ -187,14 +200,14 @@ func TestPlaylist(t *testing.T) {
} }
} }
func TestUnsupportedURL(t *testing.T) { func TestTestUnsupportedURL(t *testing.T) {
defer leaktest.Check(t)() defer leaktest.Check(t)()
_, ydlResultErr := goutubedl.New(context.Background(), "https://www.google.com", goutubedl.Options{}) _, ydlResultErr := goutubedl.New(context.Background(), "https://www.google.com", goutubedl.Options{})
if ydlResultErr == nil { if ydlResultErr == nil {
t.Errorf("expected unsupported url") t.Errorf("expected unsupported url")
} }
expectedErrPrefix := "Unsupported URL:" expectedErrPrefix := "Unsupported URL: https://www.google.com"
if ydlResultErr != nil && !strings.HasPrefix(ydlResultErr.Error(), expectedErrPrefix) { if ydlResultErr != nil && !strings.HasPrefix(ydlResultErr.Error(), expectedErrPrefix) {
t.Errorf("expected error prefix %q got %q", expectedErrPrefix, ydlResultErr.Error()) t.Errorf("expected error prefix %q got %q", expectedErrPrefix, ydlResultErr.Error())
@ -273,31 +286,6 @@ func TestErrorNotASingleEntry(t *testing.T) {
DownloadThumbnail: false, DownloadThumbnail: false,
}) })
if ydlResultErr != goutubedl.ErrNotASingleEntry { if ydlResultErr != goutubedl.ErrNotASingleEntry {
t.Fatalf("expected is single entry error, got %s", ydlResultErr) t.Errorf("expected is single entry error, got %s", ydlResultErr)
} }
} }
func TestOptionDownloader(t *testing.T) {
defer leakChecks(t)()
ydlResult, ydlResultErr := goutubedl.New(
context.Background(),
testVideoRawURL,
goutubedl.Options{
Downloader: "ffmpeg",
})
if ydlResultErr != nil {
t.Fatalf("failed to download: %s", ydlResultErr)
}
dr, err := ydlResult.Download(context.Background(), ydlResult.Info.Formats[0].FormatID)
if err != nil {
t.Fatal(err)
}
downloadBuf := &bytes.Buffer{}
_, err = io.Copy(downloadBuf, dr)
if err != nil {
t.Fatal(err)
}
dr.Close()
}