Phase 1: core bot

Link in, card, download, send, in private chats and groups.

- cmd/core with an embedded download worker
- Telegram front end on telego v1.13.0 (Bot API 10.4): link card with
  thumbnail and format buttons, one live status message, /dl /audio /thumb
  /info /queue /cancel, group support with requester-only buttons
- Database backed queue: paid and free lanes, leases with heartbeats, one
  automatic retry, cancel, queue position and wait estimate
- yt-dlp and ffprobe behind a Runner interface with classified, redacted
  errors mapped to friendly messages
- SQLite via modernc with goose migrations, portable schema
- Local file storage behind a Storage interface
- go-i18n with an English catalog, no literal text in handlers
- Free tier limits enforced before queueing and again on the real file
- Bot token and webhook secret are stripped from all log output
- Tests: URL parsing, job lifecycle, worker, yt-dlp wrapper, and end to end
  flows against a fake Bot API server; opt-in test with the real yt-dlp

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-18 07:33:32 +00:00
co-authored by Claude Fable 5.2
commit 3b361c17a1
63 changed files with 10715 additions and 0 deletions
+74
View File
@@ -0,0 +1,74 @@
package ytdlp
import (
"strings"
"github.com/noderunners/dlbot/internal/links"
)
type rule struct {
code Code
retryable bool
needles []string
}
// rules are checked in order, so specific causes come before generic ones.
// Needles are matched against lowercased yt-dlp output.
var rules = []rule{
{CodeUnsupported, false, []string{"unsupported url", "is not a valid url", "no suitable extractor"}},
{CodeSiteBlocked, false, []string{"confirm you’re not a bot", "confirm you're not a bot", "captcha", "cloudflare"}},
{CodeDRM, false, []string{"drm protected", "drm-protected", "is drm"}},
{CodeGeoBlocked, false, []string{"not available in your country", "geo-restricted", "geo restricted", "blocked in your country", "not available from your location", "georestricted"}},
{CodeLive, false, []string{"live event will begin", "premieres in", "this live event", "is not currently live", "live stream"}},
{CodePrivate, false, []string{"private video", "video is private", "is private", "members-only", "members only", "join this channel", "requires payment", "subscriber-only", "only available to", "premium"}},
{CodeLoginRequired, false, []string{"login required", "log in", "logged-in", "logged in", "sign in", "--cookies", "account credentials", "authentication", "age-restricted", "confirm your age", "inappropriate for some users"}},
{CodeNotFound, false, []string{"video unavailable", "has been removed", "no longer available", "http error 404", "http error 410", "not found", "does not exist", "been deleted", "account has been terminated"}},
{CodeRateLimited, true, []string{"http error 429", "too many requests", "rate-limit", "rate limit"}},
{CodeNoSubtitles, false, []string{"no subtitles for the requested languages"}},
{CodeNoMedia, false, []string{"requested format is not available", "no video formats found", "unable to obtain file audio codec", "no formats found"}},
{CodeTooLarge, false, []string{"larger than max-filesize"}},
{CodeInternal, true, []string{"no space left on device", "permission denied", "read-only file system"}},
{CodeProcessing, false, []string{"postprocessing", "ffmpeg", "ffprobe", "conversion failed"}},
{CodeNetwork, true, []string{"timed out", "timeout", "connection reset", "connection refused", "connection aborted", "name resolution", "getaddrinfo", "http error 5", "incompleteread", "unable to download", "network is unreachable", "remote end closed", "ssl"}},
}
// Classify maps raw yt-dlp output to a failure class. The raw text is
// redacted so it is safe for owner logs.
func Classify(raw string) *Error {
e := &Error{Code: CodeUnknown, Retryable: true, Raw: sanitize(raw)}
low := strings.ToLower(raw)
for _, r := range rules {
for _, n := range r.needles {
if strings.Contains(low, n) {
e.Code = r.code
e.Retryable = r.retryable
return e
}
}
}
return e
}
// sanitize keeps the error lines of the output, redacts URLs and bounds the
// length.
func sanitize(raw string) string {
var keep []string
for _, line := range strings.Split(raw, "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "ERROR") {
keep = append(keep, line)
}
}
out := strings.Join(keep, " | ")
if out == "" {
out = strings.TrimSpace(raw)
if len(out) > 600 {
out = out[len(out)-600:]
}
}
out = links.RedactText(out)
if len(out) > 1000 {
out = out[:1000]
}
return out
}
+155
View File
@@ -0,0 +1,155 @@
package ytdlp
import (
"sort"
"github.com/noderunners/dlbot/internal/media"
)
func (f Format) size(duration Float) int64 {
switch {
case f.Filesize > 0:
return int64(f.Filesize)
case f.FilesizeAprx > 0:
return int64(f.FilesizeAprx)
case f.TBR > 0 && duration > 0:
return int64(float64(f.TBR) * 1000 / 8 * float64(duration))
}
return 0
}
func (f Format) hasVideo() bool { return f.VCodec != "none" && f.Ext != "mhtml" }
func (f Format) hasAudio() bool { return f.ACodec != "none" }
func (f Format) audioOnly() bool {
return f.VCodec == "none" && f.ACodec != "none" && f.ACodec != ""
}
func isH264(codec string) bool {
return len(codec) >= 4 && (codec[:4] == "avc1" || codec[:4] == "h264")
}
// MaxHeight returns the tallest video format, or 0 when heights are unknown.
func (i *Info) MaxHeight() int {
h := int(i.Height)
for _, f := range i.Formats {
if f.hasVideo() && int(f.Height) > h {
h = int(f.Height)
}
}
return h
}
// HasAudio reports whether an audio track is likely. Unknown counts as yes
// so that we do not hide the audio buttons on sites with sparse metadata.
func (i *Info) HasAudio() bool {
if len(i.Formats) == 0 {
return true
}
for _, f := range i.Formats {
if f.hasAudio() {
return true
}
}
return false
}
// SubtitleLangs returns the available subtitle languages, manual ones
// first, then automatic captions, each group sorted.
func (i *Info) SubtitleLangs() (manual, auto []string) {
for l := range i.Subtitles {
if l != "live_chat" {
manual = append(manual, l)
}
}
for l := range i.AutomaticCaptions {
if _, dup := i.Subtitles[l]; !dup {
auto = append(auto, l)
}
}
sort.Strings(manual)
sort.Strings(auto)
return manual, auto
}
// EstimateSize guesses the output size of a profile in bytes from the
// format list. It returns 0 when the metadata is not good enough to guess.
// The estimate mirrors the selection in profileArgs: prefer h264 and the
// tallest format under the height cap, plus the best audio track when the
// video format carries none.
func (i *Info) EstimateSize(p media.Profile) int64 {
switch p.Kind() {
case media.KindThumb, media.KindSubs:
return 0
case media.KindAudio:
if a := i.bestAudio(); a != nil {
return a.size(i.Duration)
}
return 0
}
v := i.pickVideo(p.Height())
if v == nil {
if i.Filesize > 0 {
return int64(i.Filesize)
}
return int64(i.FilesizeAprx)
}
total := v.size(i.Duration)
if total == 0 {
return 0
}
if !v.hasAudio() {
if a := i.bestAudio(); a != nil {
total += a.size(i.Duration)
}
}
return total
}
func (i *Info) pickVideo(maxHeight int) *Format {
var best *Format
better := func(a, b *Format) bool { // is a better than b
if isH264(a.VCodec) != isH264(b.VCodec) {
return isH264(a.VCodec)
}
if a.Height != b.Height {
return a.Height > b.Height
}
return a.size(i.Duration) > b.size(i.Duration)
}
for idx := range i.Formats {
f := &i.Formats[idx]
if !f.hasVideo() {
continue
}
if maxHeight > 0 && int(f.Height) > maxHeight {
continue
}
if best == nil || better(f, best) {
best = f
}
}
if best == nil && maxHeight > 0 {
// Nothing under the cap: yt-dlp falls back to the smallest above it.
for idx := range i.Formats {
f := &i.Formats[idx]
if f.hasVideo() && (best == nil || f.Height < best.Height) {
best = f
}
}
}
return best
}
func (i *Info) bestAudio() *Format {
var best *Format
for idx := range i.Formats {
f := &i.Formats[idx]
if !f.audioOnly() {
continue
}
if best == nil || f.size(i.Duration) > best.size(i.Duration) {
best = f
}
}
return best
}
+463
View File
@@ -0,0 +1,463 @@
package ytdlp
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/noderunners/dlbot/internal/media"
)
// Exec runs the real yt-dlp and ffprobe binaries.
type Exec struct {
// Path of the yt-dlp binary. Defaults to "yt-dlp".
Path string
// FfmpegPath is passed to yt-dlp as --ffmpeg-location when it is not the
// plain "ffmpeg" found on PATH. ffprobe is expected next to it.
FfmpegPath string
// ProbeTimeout bounds a metadata lookup. Defaults to 45 seconds.
ProbeTimeout time.Duration
// DownloadTimeout bounds one download. Defaults to 30 minutes.
DownloadTimeout time.Duration
// ExtraArgs are appended to every yt-dlp call, for example a proxy.
ExtraArgs []string
}
var _ Runner = (*Exec)(nil)
func (e *Exec) bin() string {
if e.Path == "" {
return "yt-dlp"
}
return e.Path
}
func (e *Exec) ffprobeBin() string {
if e.FfmpegPath == "" || e.FfmpegPath == "ffmpeg" {
return "ffprobe"
}
return filepath.Join(filepath.Dir(e.FfmpegPath), "ffprobe")
}
func (e *Exec) baseArgs() []string {
args := []string{"--ignore-config", "--no-warnings", "--no-playlist", "--color", "never",
"--socket-timeout", "30"}
if e.FfmpegPath != "" && e.FfmpegPath != "ffmpeg" {
args = append(args, "--ffmpeg-location", e.FfmpegPath)
}
return append(args, e.ExtraArgs...)
}
// Version returns the yt-dlp version string.
func (e *Exec) Version(ctx context.Context) (string, error) {
ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
out, err := exec.CommandContext(ctx, e.bin(), "--version").Output()
if err != nil {
return "", fmt.Errorf("ytdlp: version: %w", err)
}
return strings.TrimSpace(string(out)), nil
}
// Probe implements Runner. It asks for one JSON document, which is either a
// single video or a flat playlist listing.
func (e *Exec) Probe(ctx context.Context, url string) (*Info, error) {
timeout := e.ProbeTimeout
if timeout <= 0 {
timeout = 45 * time.Second
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
args := append(e.baseArgs(), "--flat-playlist", "-J", "--", url)
cmd := exec.CommandContext(ctx, e.bin(), args...)
setProcAttrs(cmd)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if ctxErr := ctx.Err(); ctxErr != nil {
if errors.Is(ctxErr, context.DeadlineExceeded) {
return nil, &Error{Code: CodeTimeout, Retryable: true, Raw: "probe timed out"}
}
return nil, &Error{Code: CodeCancelled, Raw: "probe cancelled"}
}
if err != nil {
var ee *exec.ExitError
if !errors.As(err, &ee) {
return nil, &Error{Code: CodeInternal, Retryable: true, Raw: "cannot run yt-dlp: " + err.Error()}
}
return nil, Classify(stderr.String())
}
var info Info
if err := json.Unmarshal(bytes.TrimSpace(stdout.Bytes()), &info); err != nil {
return nil, &Error{Code: CodeUnknown, Retryable: true, Raw: "bad metadata json: " + err.Error()}
}
if info.Type == "" {
info.Type = "video"
}
return &info, nil
}
const (
progressTemplate = "download:DLP|%(progress.status)s|%(progress.downloaded_bytes)s|%(progress.total_bytes)s|%(progress.total_bytes_estimate)s"
infoTemplate = "pre_process:INFO|%(.{id,title,duration,extractor,extractor_key,uploader,is_live,live_status})j"
resultTemplate = "after_move:RESULT|%(.{width,height,duration,ext,filepath})j"
)
// profileArgs returns the yt-dlp flags that select and shape one profile.
// Video prefers h264 with AAC in an mp4 container because that is what
// Telegram clients can stream inline.
func profileArgs(p media.Profile) []string {
switch p.Kind() {
case media.KindAudio:
if p == media.M4A {
return []string{"-f", "ba[ext=m4a]/ba/b", "-x", "--audio-format", "m4a"}
}
return []string{"-f", "ba/b", "-x", "--audio-format", "mp3", "--audio-quality", "192K"}
case media.KindThumb:
return []string{"--skip-download", "--write-thumbnail", "--convert-thumbnails", "jpg"}
case media.KindSubs:
return []string{"--skip-download", "--write-subs", "--write-auto-subs",
"--sub-langs", p.SubLang(), "--convert-subs", "srt"}
}
sort := "vcodec:h264,res,acodec:m4a"
if h := p.Height(); h > 0 {
sort = "vcodec:h264,res:" + strconv.Itoa(h) + ",acodec:m4a"
}
return []string{"-S", sort, "-f", "bv*+ba/b", "--merge-output-format", "mp4/mkv"}
}
// DownloadArgs builds the full argument list for a download. It is exported
// for tests and for the operations docs.
func (e *Exec) DownloadArgs(req DownloadRequest) []string {
args := e.baseArgs()
args = append(args,
"--newline", "--no-mtime", "--progress", "--progress-delta", "1",
"--retries", "3", "--fragment-retries", "5",
"--progress-template", progressTemplate,
"--print", infoTemplate,
"--print", resultTemplate,
"--no-simulate",
"-P", req.Dir, "-o", "media.%(ext)s",
)
filter := "!is_live"
if req.MaxDuration > 0 {
filter += " & duration<=?" + strconv.Itoa(int(req.MaxDuration.Seconds()))
}
args = append(args, "--match-filters", filter)
if req.MaxSize > 0 && req.Profile.Kind() != media.KindThumb && req.Profile.Kind() != media.KindSubs {
args = append(args, "--max-filesize", strconv.FormatInt(req.MaxSize, 10))
}
args = append(args, profileArgs(req.Profile)...)
return append(args, "--", req.URL)
}
type preInfo struct {
ID string `json:"id"`
Title string `json:"title"`
Duration Float `json:"duration"`
Extractor string `json:"extractor"`
Uploader string `json:"uploader"`
IsLive bool `json:"is_live"`
LiveStatus string `json:"live_status"`
}
type postInfo struct {
Width Int `json:"width"`
Height Int `json:"height"`
Duration Float `json:"duration"`
Ext string `json:"ext"`
Filepath string `json:"filepath"`
}
// Download implements Runner.
func (e *Exec) Download(ctx context.Context, req DownloadRequest, onProgress func(Progress)) (*Result, error) {
timeout := e.DownloadTimeout
if timeout <= 0 {
timeout = 30 * time.Minute
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
if err := os.MkdirAll(req.Dir, 0o750); err != nil {
return nil, &Error{Code: CodeInternal, Retryable: true, Raw: err.Error()}
}
cmd := exec.CommandContext(ctx, e.bin(), e.DownloadArgs(req)...)
setProcAttrs(cmd)
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, &Error{Code: CodeInternal, Retryable: true, Raw: err.Error()}
}
var stderr tailBuffer
cmd.Stderr = &stderr
if err := cmd.Start(); err != nil {
return nil, &Error{Code: CodeInternal, Retryable: true, Raw: "cannot run yt-dlp: " + err.Error()}
}
var (
pre preInfo
post postInfo
outLines tailBuffer
)
sc := bufio.NewScanner(stdout)
sc.Buffer(make([]byte, 64*1024), 1024*1024)
for sc.Scan() {
line := sc.Text()
switch {
case strings.HasPrefix(line, "DLP|"):
if onProgress != nil {
if p, ok := parseProgress(line); ok {
onProgress(p)
}
}
case strings.HasPrefix(line, "INFO|"):
_ = json.Unmarshal([]byte(line[5:]), &pre)
case strings.HasPrefix(line, "RESULT|"):
_ = json.Unmarshal([]byte(line[7:]), &post)
default:
if onProgress != nil && isPostprocessLine(line) {
onProgress(Progress{Stage: StageProcessing})
}
_, _ = outLines.Write([]byte(line + "\n"))
}
}
waitErr := cmd.Wait()
if ctxErr := ctx.Err(); ctxErr != nil {
if errors.Is(ctxErr, context.DeadlineExceeded) {
return nil, &Error{Code: CodeTimeout, Retryable: true, Raw: "download timed out"}
}
return nil, &Error{Code: CodeCancelled, Raw: "download cancelled"}
}
raw := stderr.String() + "\n" + outLines.String()
if waitErr != nil {
return nil, Classify(raw)
}
path := post.Filepath
if path == "" || !fileExists(path) {
path = findOutput(req.Dir)
}
if path == "" {
// yt-dlp exits 0 when a filter or the size cap skipped the item.
return nil, noFileError(req, pre, raw)
}
st, err := os.Stat(path)
if err != nil {
return nil, &Error{Code: CodeInternal, Retryable: true, Raw: err.Error()}
}
res := &Result{
Path: path,
Size: st.Size(),
Ext: strings.TrimPrefix(filepath.Ext(path), "."),
ID: pre.ID,
Title: pre.Title,
Uploader: pre.Uploader,
Extractor: pre.Extractor,
Duration: float64(pre.Duration),
Width: int(post.Width),
Height: int(post.Height),
}
if post.Duration > 0 {
res.Duration = float64(post.Duration)
}
if k := req.Profile.Kind(); k == media.KindVideo || k == media.KindAudio {
if fp, err := e.ffprobe(ctx, path); err == nil {
if fp.duration > 0 {
res.Duration = fp.duration
}
if k == media.KindVideo && fp.width > 0 {
res.Width, res.Height = fp.width, fp.height
}
}
}
if req.MaxSize > 0 && res.Size > req.MaxSize {
return nil, &Error{Code: CodeTooLarge, Raw: fmt.Sprintf("output is %d bytes, cap is %d", res.Size, req.MaxSize)}
}
if req.MaxDuration > 0 && res.Duration > req.MaxDuration.Seconds()+1 {
return nil, &Error{Code: CodeTooLong, Raw: fmt.Sprintf("output is %.0f seconds, cap is %.0f", res.Duration, req.MaxDuration.Seconds())}
}
return res, nil
}
func noFileError(req DownloadRequest, pre preInfo, raw string) *Error {
low := strings.ToLower(raw)
switch {
case pre.IsLive || pre.LiveStatus == "is_live" || pre.LiveStatus == "is_upcoming":
return &Error{Code: CodeLive, Raw: "live stream skipped"}
case req.MaxDuration > 0 && float64(pre.Duration) > req.MaxDuration.Seconds():
return &Error{Code: CodeTooLong, Raw: fmt.Sprintf("duration %.0f over cap", float64(pre.Duration))}
case strings.Contains(low, "larger than max-filesize"):
return &Error{Code: CodeTooLarge, Raw: "file larger than cap"}
case strings.Contains(low, "no subtitles") || req.Profile.Kind() == media.KindSubs:
return &Error{Code: CodeNoSubtitles, Raw: "no subtitles for " + req.Profile.SubLang()}
case req.Profile.Kind() == media.KindThumb:
return &Error{Code: CodeNoMedia, Raw: "no thumbnail"}
}
e := Classify(raw)
if e.Code == CodeUnknown {
e.Raw = "yt-dlp produced no file: " + e.Raw
}
return e
}
func parseProgress(line string) (Progress, bool) {
parts := strings.Split(line, "|")
if len(parts) < 5 {
return Progress{}, false
}
p := Progress{Stage: StageDownloading}
p.Downloaded = atoi64(parts[2])
p.Total = atoi64(parts[3])
if p.Total == 0 {
p.Total = atoi64(parts[4])
}
if parts[1] == "finished" {
p.Stage = StageProcessing
}
return p, true
}
func atoi64(s string) int64 {
if s == "" || s == "NA" || s == "None" {
return 0
}
if n, err := strconv.ParseInt(s, 10, 64); err == nil {
return n
}
if f, err := strconv.ParseFloat(s, 64); err == nil {
return int64(f)
}
return 0
}
func isPostprocessLine(line string) bool {
for _, p := range []string{"[Merger]", "[ExtractAudio]", "[VideoRemuxer]", "[VideoConvertor]", "[ThumbnailsConvertor]", "[SubtitlesConvertor]", "[Fixup"} {
if strings.HasPrefix(line, p) {
return true
}
}
return false
}
func fileExists(p string) bool {
st, err := os.Stat(p)
return err == nil && st.Mode().IsRegular()
}
// findOutput returns the largest finished file in dir, ignoring yt-dlp
// leftovers. Used for profiles that never reach the after_move stage.
func findOutput(dir string) string {
entries, err := os.ReadDir(dir)
if err != nil {
return ""
}
var best string
var bestSize int64 = -1
for _, en := range entries {
if en.IsDir() {
continue
}
name := en.Name()
if strings.HasSuffix(name, ".part") || strings.HasSuffix(name, ".ytdl") ||
strings.HasSuffix(name, ".json") || strings.HasSuffix(name, ".temp") ||
strings.Contains(name, ".part-") {
continue
}
fi, err := en.Info()
if err != nil || fi.Size() == 0 {
continue
}
if fi.Size() > bestSize {
best, bestSize = filepath.Join(dir, name), fi.Size()
}
}
return best
}
type probed struct {
duration float64
width, height int
}
func (e *Exec) ffprobe(ctx context.Context, path string) (probed, error) {
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
out, err := exec.CommandContext(ctx, e.ffprobeBin(), "-v", "error",
"-show_entries", "format=duration:stream=codec_type,width,height",
"-of", "json", path).Output()
if err != nil {
return probed{}, err
}
var doc struct {
Streams []struct {
CodecType string `json:"codec_type"`
Width int `json:"width"`
Height int `json:"height"`
} `json:"streams"`
Format struct {
Duration string `json:"duration"`
} `json:"format"`
}
if err := json.Unmarshal(out, &doc); err != nil {
return probed{}, err
}
var p probed
p.duration, _ = strconv.ParseFloat(doc.Format.Duration, 64)
for _, s := range doc.Streams {
if s.CodecType == "video" && s.Width > 0 {
p.width, p.height = s.Width, s.Height
break
}
}
return p, nil
}
// setProcAttrs puts the child in its own process group so that cancelling
// also stops the ffmpeg processes yt-dlp starts.
func setProcAttrs(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Cancel = func() error {
if cmd.Process == nil {
return nil
}
return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
}
cmd.WaitDelay = 5 * time.Second
}
// tailBuffer keeps the last 16 KiB written to it.
type tailBuffer struct {
mu sync.Mutex
buf []byte
}
const tailMax = 16 * 1024
func (t *tailBuffer) Write(p []byte) (int, error) {
t.mu.Lock()
defer t.mu.Unlock()
t.buf = append(t.buf, p...)
if len(t.buf) > tailMax {
t.buf = t.buf[len(t.buf)-tailMax:]
}
return len(p), nil
}
func (t *tailBuffer) String() string {
t.mu.Lock()
defer t.mu.Unlock()
return string(t.buf)
}
+321
View File
@@ -0,0 +1,321 @@
package ytdlp
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/noderunners/dlbot/internal/media"
)
// fakeExec returns an Exec that runs the shell stand-in for yt-dlp.
func fakeExec(t *testing.T, mode string, env ...string) *Exec {
t.Helper()
script, err := filepath.Abs("testdata/fake-yt-dlp.sh")
if err != nil {
t.Fatal(err)
}
if err := os.Chmod(script, 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("FAKE_MODE", mode)
for _, kv := range env {
k, v, _ := strings.Cut(kv, "=")
t.Setenv(k, v)
}
return &Exec{Path: script, ProbeTimeout: 5 * time.Second, DownloadTimeout: 5 * time.Second}
}
func TestExecProbeParsesLooseJSON(t *testing.T) {
e := fakeExec(t, "ok")
info, err := e.Probe(context.Background(), "https://example.com/watch?v=abc")
if err != nil {
t.Fatal(err)
}
if info.ID != "abc" || info.Title != "Fake Title" || info.Extractor != "youtube" || info.Type != "video" {
t.Fatalf("info = %+v", info)
}
if info.Duration != 61.4 || info.FilesizeAprx != 1234 || info.Filesize != 0 {
t.Fatalf("loose numbers: duration=%v approx=%v size=%v", info.Duration, info.FilesizeAprx, info.Filesize)
}
if len(info.Formats) != 2 || info.Formats[1].Width != 1280 || info.Formats[1].FilesizeAprx != 9000000 {
t.Fatalf("formats = %+v", info.Formats)
}
if info.MaxHeight() != 720 || !info.HasAudio() || info.IsPlaylist() || info.Live() {
t.Fatalf("derived facts wrong: height=%d", info.MaxHeight())
}
manual, auto := info.SubtitleLangs()
if len(manual) != 1 || manual[0] != "en" || len(auto) != 1 || auto[0] != "es" {
t.Fatalf("subtitle langs: manual=%v auto=%v", manual, auto)
}
// 720p video (9000000) plus the audio track (1000000).
if got := info.EstimateSize(media.P720); got != 10000000 {
t.Fatalf("EstimateSize(720) = %d", got)
}
if got := info.EstimateSize(media.MP3); got != 1000000 {
t.Fatalf("EstimateSize(mp3) = %d", got)
}
}
func TestExecProbePlaylist(t *testing.T) {
e := fakeExec(t, "playlist")
info, err := e.Probe(context.Background(), "https://example.com/list")
if err != nil {
t.Fatal(err)
}
if !info.IsPlaylist() || len(info.Entries) != 2 || info.Entries[1].URL != "https://example.com/b" {
t.Fatalf("playlist info = %+v", info)
}
}
func TestExecProbeErrors(t *testing.T) {
tests := []struct {
mode string
want Code
retryable bool
}{
{"error_private", CodePrivate, false},
{"error_bot", CodeSiteBlocked, false},
{"error_with_secret", CodeNetwork, true},
}
for _, tc := range tests {
t.Run(tc.mode, func(t *testing.T) {
e := fakeExec(t, tc.mode)
_, err := e.Probe(context.Background(), "https://example.com/x")
var ye *Error
if !errors.As(err, &ye) {
t.Fatalf("error = %v, want *Error", err)
}
if ye.Code != tc.want || ye.Retryable != tc.retryable {
t.Fatalf("got %s retryable=%v, want %s retryable=%v", ye.Code, ye.Retryable, tc.want, tc.retryable)
}
if strings.Contains(ye.Raw, "TOPSECRET") {
t.Fatalf("raw error leaks a credential: %q", ye.Raw)
}
})
}
}
func TestExecProbeTimeout(t *testing.T) {
e := fakeExec(t, "hang")
e.ProbeTimeout = 200 * time.Millisecond
start := time.Now()
_, err := e.Probe(context.Background(), "https://example.com/x")
if CodeOf(err) != CodeTimeout {
t.Fatalf("error = %v, want timeout", err)
}
if time.Since(start) > 4*time.Second {
t.Fatal("the hung process was not killed promptly")
}
}
func TestExecDownload(t *testing.T) {
argsFile := filepath.Join(t.TempDir(), "args")
e := fakeExec(t, "ok", "FAKE_ARGS_FILE="+argsFile)
dir := filepath.Join(t.TempDir(), "job")
var seen []Progress
res, err := e.Download(context.Background(), DownloadRequest{
URL: "https://example.com/watch?v=abc", Profile: media.P720, Dir: dir,
MaxSize: 50 << 20, MaxDuration: 10 * time.Minute,
}, func(p Progress) { seen = append(seen, p) })
if err != nil {
t.Fatal(err)
}
if res.Path != filepath.Join(dir, "media.mp4") || res.Size != 4000 || res.Ext != "mp4" {
t.Fatalf("result = %+v", res)
}
if res.ID != "abc" || res.Title != "Fake Title" || res.Extractor != "youtube" || res.Uploader != "Someone" {
t.Fatalf("metadata = %+v", res)
}
if res.Width != 1280 || res.Height != 720 || res.Duration != 61.4 {
t.Fatalf("dimensions = %+v", res)
}
if len(seen) < 3 {
t.Fatalf("progress callbacks = %+v", seen)
}
if seen[0].Downloaded != 1000 || seen[0].Total != 4000 || seen[0].Stage != StageDownloading {
t.Fatalf("first progress = %+v", seen[0])
}
// total_bytes was NA on the second line, so the estimate is used.
if seen[1].Total != 4000 {
t.Fatalf("second progress = %+v", seen[1])
}
if last := seen[len(seen)-1]; last.Stage != StageProcessing {
t.Fatalf("last progress = %+v, want processing", last)
}
raw, err := os.ReadFile(argsFile)
if err != nil {
t.Fatal(err)
}
args := strings.Split(strings.TrimSpace(string(raw)), "\n")
mustHave := func(flag, value string) {
t.Helper()
for i, a := range args {
if a == flag && (value == "" || (i+1 < len(args) && args[i+1] == value)) {
return
}
}
t.Errorf("args lack %s %s\n%v", flag, value, args)
}
mustHave("--ignore-config", "")
mustHave("--no-playlist", "")
mustHave("--max-filesize", "52428800")
mustHave("--match-filters", "!is_live & duration<=?600")
mustHave("-S", "vcodec:h264,res:720,acodec:m4a")
mustHave("--merge-output-format", "mp4/mkv")
mustHave("-P", dir)
if args[len(args)-2] != "--" || args[len(args)-1] != "https://example.com/watch?v=abc" {
t.Errorf("the URL must come last after --, got %v", args[len(args)-2:])
}
}
func TestExecDownloadNoFileOutcomes(t *testing.T) {
tests := []struct {
name string
mode string
env []string
profile media.Profile
maxDur time.Duration
want Code
}{
{"filter rejected a long video", "filtered", nil, media.Best, 30 * time.Second, CodeTooLong},
{"filter rejected a live stream", "filtered", []string{"FAKE_IS_LIVE=true"}, media.Best, 0, CodeLive},
{"size cap hit during download", "max_filesize", nil, media.Best, 0, CodeTooLarge},
{"no subtitles", "no_subs", nil, media.Subs("en"), 0, CodeNoSubtitles},
{"private video", "error_private", nil, media.Best, 0, CodePrivate},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
e := fakeExec(t, tc.mode, tc.env...)
_, err := e.Download(context.Background(), DownloadRequest{
URL: "https://example.com/x", Profile: tc.profile, Dir: t.TempDir(), MaxDuration: tc.maxDur,
}, nil)
if got := CodeOf(err); got != tc.want {
t.Fatalf("code = %s (%v), want %s", got, err, tc.want)
}
})
}
}
func TestExecDownloadEnforcesCapOnRealFile(t *testing.T) {
// The metadata promised nothing, the file turned out too big.
e := fakeExec(t, "ok", "FAKE_SIZE=5000")
_, err := e.Download(context.Background(), DownloadRequest{
URL: "https://example.com/x", Profile: media.Best, Dir: t.TempDir(), MaxSize: 4999,
}, nil)
if CodeOf(err) != CodeTooLarge {
t.Fatalf("error = %v, want too_large", err)
}
}
func TestExecDownloadThumbFindsFile(t *testing.T) {
e := fakeExec(t, "thumb")
dir := t.TempDir()
res, err := e.Download(context.Background(), DownloadRequest{
URL: "https://example.com/x", Profile: media.Thumb, Dir: dir,
}, nil)
if err != nil {
t.Fatal(err)
}
if res.Ext != "jpg" || res.Size != 300 {
t.Fatalf("result = %+v", res)
}
}
func TestExecDownloadCancel(t *testing.T) {
e := fakeExec(t, "hang")
ctx, cancel := context.WithCancel(context.Background())
go func() {
time.Sleep(150 * time.Millisecond)
cancel()
}()
start := time.Now()
_, err := e.Download(ctx, DownloadRequest{URL: "https://example.com/x", Profile: media.Best, Dir: t.TempDir()}, nil)
if CodeOf(err) != CodeCancelled {
t.Fatalf("error = %v, want cancelled", err)
}
if time.Since(start) > 4*time.Second {
t.Fatal("cancel did not stop the process promptly")
}
}
func TestProfileArgs(t *testing.T) {
join := func(p media.Profile) string { return strings.Join(profileArgs(p), " ") }
tests := map[media.Profile]string{
media.Best: "-S vcodec:h264,res,acodec:m4a -f bv*+ba/b --merge-output-format mp4/mkv",
media.P480: "-S vcodec:h264,res:480,acodec:m4a -f bv*+ba/b --merge-output-format mp4/mkv",
media.MP3: "-f ba/b -x --audio-format mp3 --audio-quality 192K",
media.M4A: "-f ba[ext=m4a]/ba/b -x --audio-format m4a",
media.Thumb: "--skip-download --write-thumbnail --convert-thumbnails jpg",
media.Subs("es"): "--skip-download --write-subs --write-auto-subs --sub-langs es --convert-subs srt",
}
for p, want := range tests {
if got := join(p); got != want {
t.Errorf("profileArgs(%s) = %q, want %q", p, got, want)
}
}
}
func TestClassify(t *testing.T) {
tests := []struct {
raw string
want Code
retryable bool
}{
{"ERROR: Unsupported URL: https://example.com/", CodeUnsupported, false},
{"ERROR: [youtube] x: Sign in to confirm you’re not a bot. Use --cookies", CodeSiteBlocked, false},
{"ERROR: [youtube] x: Private video. Sign in if you've been granted access", CodePrivate, false},
{"ERROR: [vimeo] 1: The web client only works when logged-in. Use --cookies", CodeLoginRequired, false},
{"ERROR: [youtube] x: Sign in to confirm your age. This video may be inappropriate for some users.", CodeLoginRequired, false},
{"ERROR: [youtube] x: Video unavailable. This video is not available in your country", CodeGeoBlocked, false},
{"ERROR: [generic] x: Unable to download webpage: HTTP Error 404: Not Found", CodeNotFound, false},
{"ERROR: [youtube] x: Video unavailable. This video has been removed by the uploader", CodeNotFound, false},
{"ERROR: unable to download video data: HTTP Error 429: Too Many Requests", CodeRateLimited, true},
{"ERROR: [youtube] x: This live event will begin in 3 hours.", CodeLive, false},
{"ERROR: [x] 1: This video is DRM protected", CodeDRM, false},
{"ERROR: [youtube] x: Requested format is not available. Use --list-formats", CodeNoMedia, false},
{"ERROR: Postprocessing: WARNING: unable to obtain file audio codec with ffprobe", CodeNoMedia, false},
{"ERROR: Postprocessing: Conversion failed!", CodeProcessing, false},
{"ERROR: unable to download video data: The read operation timed out", CodeNetwork, true},
{"ERROR: unable to write data: [Errno 28] No space left on device", CodeInternal, true},
{"ERROR: something nobody has seen before", CodeUnknown, true},
}
for _, tc := range tests {
got := Classify(tc.raw)
if got.Code != tc.want || got.Retryable != tc.retryable {
t.Errorf("Classify(%q) = %s retryable=%v, want %s retryable=%v", tc.raw, got.Code, got.Retryable, tc.want, tc.retryable)
}
}
}
func TestEstimateSizeEdgeCases(t *testing.T) {
// Sparse metadata, as archive.org returns it: no codecs, sizes known.
sparse := &Info{Duration: 596, Formats: []Format{
{FormatID: "0", Ext: "ogv", Height: 300, Filesize: 46 << 20},
{FormatID: "1", Ext: "mp4", Height: 360, Filesize: 61 << 20},
{FormatID: "2", Ext: "avi", Height: 720, Filesize: 332 << 20},
}}
if got := sparse.EstimateSize(media.Best); got != 332<<20 {
t.Errorf("best = %d", got)
}
if got := sparse.EstimateSize(media.P480); got != 61<<20 {
t.Errorf("480 = %d, want the 360p file", got)
}
// Bitrate fallback: 1000 kbit/s for 80 seconds is 10 MB.
rate := &Info{Duration: 80, Formats: []Format{{Ext: "mp4", VCodec: "avc1", ACodec: "mp4a", Height: 720, TBR: 1000}}}
if got := rate.EstimateSize(media.Best); got != 10_000_000 {
t.Errorf("bitrate estimate = %d", got)
}
// Nothing to go on.
if got := (&Info{}).EstimateSize(media.Best); got != 0 {
t.Errorf("empty info = %d, want 0", got)
}
if got := sparse.EstimateSize(media.Thumb); got != 0 {
t.Errorf("thumb = %d, want 0", got)
}
}
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env bash
# A stand-in for yt-dlp used by exec_test.go. It prints the same line
# formats as the real tool. FAKE_MODE selects the scenario.
set -u
args=("$@")
dir=""
is_probe=0
url="${args[$((${#args[@]} - 1))]}"
for ((i = 0; i < ${#args[@]}; i++)); do
case "${args[$i]}" in
-P) dir="${args[$((i + 1))]}" ;;
-J) is_probe=1 ;;
--version) echo "2026.01.01"; exit 0 ;;
esac
done
if [[ -n "${FAKE_ARGS_FILE:-}" ]]; then
printf '%s\n' "${args[@]}" > "$FAKE_ARGS_FILE"
fi
case "${FAKE_MODE:-ok}" in
error_private)
echo "ERROR: [youtube] abc: Private video. Sign in if you've been granted access to this video" >&2
exit 1 ;;
error_bot)
echo "ERROR: [youtube] abc: Sign in to confirm you’re not a bot. Use --cookies-from-browser or --cookies" >&2
exit 1 ;;
error_with_secret)
echo "ERROR: unable to download video data from https://cdn.example.com/v.mp4?token=TOPSECRET&id=1: HTTP Error 503" >&2
exit 1 ;;
hang)
sleep 30
exit 0 ;;
esac
if [[ $is_probe -eq 1 ]]; then
case "${FAKE_MODE:-ok}" in
playlist)
echo '{"_type": "playlist", "id": "PL1", "title": "A List", "entries": [{"id": "a", "title": "One", "url": "https://example.com/a"}, {"id": "b", "title": "Two", "url": "https://example.com/b"}]}' ;;
*)
# Numbers are deliberately loose: a float size, a null and a quoted one.
echo '{"id": "abc", "title": "Fake Title", "extractor": "youtube", "extractor_key": "Youtube", "webpage_url": "'"$url"'", "duration": 61.4, "thumbnail": "https://img.example.com/t.jpg", "uploader": "Someone", "is_live": false, "filesize": null, "filesize_approx": 1234.56, "formats": [{"format_id": "a", "ext": "m4a", "vcodec": "none", "acodec": "mp4a.40.2", "filesize": 1000000}, {"format_id": "v", "ext": "mp4", "vcodec": "avc1.64001F", "acodec": "none", "height": 720, "width": "1280", "filesize": null, "filesize_approx": 9000000.7, "tbr": 1200.5}], "subtitles": {"en": [{"ext": "vtt"}], "live_chat": [{"ext": "json"}]}, "automatic_captions": {"es": [{"ext": "vtt"}], "en": [{"ext": "vtt"}]}}' ;;
esac
exit 0
fi
echo 'INFO|{"id": "abc", "title": "Fake Title", "duration": 61.4, "extractor": "youtube", "extractor_key": "Youtube", "uploader": "Someone", "is_live": '"${FAKE_IS_LIVE:-false}"'}'
case "${FAKE_MODE:-ok}" in
filtered)
# yt-dlp exits 0 without a file when --match-filters rejects the item.
exit 0 ;;
max_filesize)
echo "[download] File is larger than max-filesize (99999999 bytes > 1000 bytes). Aborting."
exit 0 ;;
no_subs)
echo "[info] There are no subtitles for the requested languages"
exit 0 ;;
thumb)
head -c 300 /dev/zero > "$dir/media.jpg"
exit 0 ;;
esac
echo "[download] Destination: $dir/media.mp4"
echo "DLP|downloading|1000|4000|NA"
echo "DLP|downloading|4000|NA|4000.0"
echo "DLP|finished|4000|4000|NA"
echo "[Merger] Merging formats into \"$dir/media.mp4\""
head -c "${FAKE_SIZE:-4000}" /dev/zero > "$dir/media.mp4"
# Leftovers that must never be picked as the result.
head -c 9000 /dev/zero > "$dir/media.f137.mp4.part"
echo 'RESULT|{"width": 1280, "height": 720, "duration": 61.4, "ext": "mp4", "filepath": "'"$dir/media.mp4"'"}'
exit 0
+222
View File
@@ -0,0 +1,222 @@
// Package ytdlp wraps the yt-dlp and ffprobe executables behind an interface
// so the rest of the bot can be tested without them.
package ytdlp
import (
"context"
"errors"
"strconv"
"strings"
"time"
"github.com/noderunners/dlbot/internal/media"
)
// Runner looks up metadata and downloads media.
type Runner interface {
// Probe returns metadata for a URL without downloading it.
Probe(ctx context.Context, url string) (*Info, error)
// Download fetches one profile of a URL into req.Dir. onProgress may be
// nil. Failures are returned as *Error.
Download(ctx context.Context, req DownloadRequest, onProgress func(Progress)) (*Result, error)
}
// Info is the subset of the yt-dlp info JSON the bot uses.
type Info struct {
Type string `json:"_type"`
ID string `json:"id"`
Title string `json:"title"`
Extractor string `json:"extractor"`
ExtractorKey string `json:"extractor_key"`
WebpageURL string `json:"webpage_url"`
Thumbnail string `json:"thumbnail"`
Uploader string `json:"uploader"`
Ext string `json:"ext"`
Duration Float `json:"duration"`
Filesize Int `json:"filesize"`
FilesizeAprx Int `json:"filesize_approx"`
Width Int `json:"width"`
Height Int `json:"height"`
IsLive bool `json:"is_live"`
LiveStatus string `json:"live_status"`
Availability string `json:"availability"`
Formats []Format `json:"formats"`
Subtitles map[string][]SubTrack `json:"subtitles"`
AutomaticCaptions map[string][]SubTrack `json:"automatic_captions"`
Entries []Entry `json:"entries"`
}
// Format is one downloadable format of a video.
type Format struct {
FormatID string `json:"format_id"`
FormatNote string `json:"format_note"`
Ext string `json:"ext"`
VCodec string `json:"vcodec"`
ACodec string `json:"acodec"`
Protocol string `json:"protocol"`
Width Int `json:"width"`
Height Int `json:"height"`
Filesize Int `json:"filesize"`
FilesizeAprx Int `json:"filesize_approx"`
TBR Float `json:"tbr"`
}
// SubTrack is one subtitle file variant.
type SubTrack struct {
Ext string `json:"ext"`
Name string `json:"name"`
}
// Entry is one item of a playlist in a flat listing.
type Entry struct {
ID string `json:"id"`
Title string `json:"title"`
URL string `json:"url"`
Duration Float `json:"duration"`
}
// IsPlaylist reports whether the URL resolved to a list of items.
func (i *Info) IsPlaylist() bool { return i.Type == "playlist" || i.Type == "multi_video" }
// Live reports whether the item is a running or upcoming live stream.
func (i *Info) Live() bool {
return i.IsLive || i.LiveStatus == "is_live" || i.LiveStatus == "is_upcoming"
}
// DownloadRequest describes one download.
type DownloadRequest struct {
URL string
Profile media.Profile
// Dir is an empty directory owned by this download.
Dir string
// MaxSize in bytes, 0 for no cap.
MaxSize int64
// MaxDuration, 0 for no cap.
MaxDuration time.Duration
}
// Progress is a snapshot of a running download.
type Progress struct {
Stage string // downloading or processing
Downloaded int64
Total int64 // 0 when unknown
}
// The progress stages.
const (
StageDownloading = "downloading"
StageProcessing = "processing"
StageUploading = "uploading"
)
// Result describes a finished download.
type Result struct {
Path string
Size int64
Ext string
ID string
Title string
Uploader string
Extractor string
Duration float64
Width int
Height int
}
// Code is a stable, user-presentable failure class. Each code has a
// matching "error.<code>" message in the catalogs.
type Code string
// The failure classes.
const (
CodeUnsupported Code = "unsupported_url"
CodeNotFound Code = "not_found"
CodePrivate Code = "private"
CodeLoginRequired Code = "login_required"
CodeGeoBlocked Code = "geo_blocked"
CodeSiteBlocked Code = "site_blocked"
CodeRateLimited Code = "rate_limited"
CodeLive Code = "live_stream"
CodeDRM Code = "drm"
CodeTooLarge Code = "too_large"
CodeTooLong Code = "too_long"
CodeNoMedia Code = "no_media"
CodeNoSubtitles Code = "no_subtitles"
CodeNetwork Code = "network"
CodeTimeout Code = "timeout"
CodeProcessing Code = "processing_failed"
CodeCancelled Code = "cancelled"
CodeWorkerLost Code = "worker_lost"
CodeInternal Code = "internal"
CodeUnknown Code = "unknown"
)
// KnownCodes lists every code, for catalog completeness checks.
var KnownCodes = []Code{
CodeUnsupported, CodeNotFound, CodePrivate, CodeLoginRequired, CodeGeoBlocked,
CodeSiteBlocked, CodeRateLimited, CodeLive, CodeDRM, CodeTooLarge, CodeTooLong,
CodeNoMedia, CodeNoSubtitles, CodeNetwork, CodeTimeout, CodeProcessing,
CodeCancelled, CodeWorkerLost, CodeInternal, CodeUnknown,
}
// Error is a classified yt-dlp failure. Raw is for owner logs only and must
// never be shown to users.
type Error struct {
Code Code
Retryable bool
Raw string
}
func (e *Error) Error() string { return "ytdlp: " + string(e.Code) + ": " + e.Raw }
// CodeOf extracts the failure class from any error.
func CodeOf(err error) Code {
var e *Error
switch {
case errors.As(err, &e):
return e.Code
case errors.Is(err, context.Canceled):
return CodeCancelled
case errors.Is(err, context.DeadlineExceeded):
return CodeTimeout
}
return CodeUnknown
}
// Int is an integer that tolerates the loose numbers in yt-dlp JSON: null,
// floats such as 1234.5 and quoted numbers all decode without error.
type Int int64
// UnmarshalJSON implements json.Unmarshaler.
func (i *Int) UnmarshalJSON(b []byte) error {
f, ok := looseNumber(b)
if ok {
*i = Int(f)
}
return nil
}
// Float is the floating point counterpart of Int.
type Float float64
// UnmarshalJSON implements json.Unmarshaler.
func (f *Float) UnmarshalJSON(b []byte) error {
v, ok := looseNumber(b)
if ok {
*f = Float(v)
}
return nil
}
func looseNumber(b []byte) (float64, bool) {
s := strings.Trim(strings.TrimSpace(string(b)), `"`)
if s == "" || s == "null" {
return 0, false
}
v, err := strconv.ParseFloat(s, 64)
if err != nil || v != v {
return 0, false
}
return v, true
}
+158
View File
@@ -0,0 +1,158 @@
// Package ytdlptest provides a scriptable ytdlp.Runner for tests.
package ytdlptest
import (
"context"
"os"
"path/filepath"
"sync"
"time"
"github.com/noderunners/dlbot/internal/media"
"github.com/noderunners/dlbot/internal/ytdlp"
)
// Fake is an in-memory ytdlp.Runner. The zero value answers every URL with
// a small default video.
type Fake struct {
mu sync.Mutex
// Infos maps a URL to the metadata Probe returns.
Infos map[string]*ytdlp.Info
// ProbeErrs maps a URL to the error Probe returns.
ProbeErrs map[string]error
// DownloadErrs is consumed one error per Download call, per URL. A nil
// entry means success. This is how tests script "fail once, then work".
DownloadErrs map[string][]error
// FileSize is the size of produced files. Defaults to 1024 bytes.
FileSize int
// Delay is how long a download takes. It stops early on cancel.
Delay time.Duration
// Block, when set, makes downloads wait until the channel is closed.
Block chan struct{}
probes []string
downloads []ytdlp.DownloadRequest
}
var _ ytdlp.Runner = (*Fake)(nil)
// DefaultInfo is the metadata returned for URLs without an explicit entry.
func DefaultInfo(url string) *ytdlp.Info {
return &ytdlp.Info{
Type: "video",
ID: "vid123",
Title: "Test Video",
Extractor: "fake",
WebpageURL: url,
Uploader: "Tester",
Duration: 60,
Thumbnail: "https://img.example.com/t.jpg",
Formats: []ytdlp.Format{
{FormatID: "a", Ext: "m4a", VCodec: "none", ACodec: "mp4a", Filesize: 1 << 20},
{FormatID: "v480", Ext: "mp4", VCodec: "avc1", ACodec: "none", Height: 480, Filesize: 4 << 20},
{FormatID: "v720", Ext: "mp4", VCodec: "avc1", ACodec: "none", Height: 720, Filesize: 9 << 20},
},
}
}
// Probe implements ytdlp.Runner.
func (f *Fake) Probe(_ context.Context, url string) (*ytdlp.Info, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.probes = append(f.probes, url)
if err := f.ProbeErrs[url]; err != nil {
return nil, err
}
if info := f.Infos[url]; info != nil {
cp := *info
return &cp, nil
}
return DefaultInfo(url), nil
}
// Download implements ytdlp.Runner.
func (f *Fake) Download(ctx context.Context, req ytdlp.DownloadRequest, onProgress func(ytdlp.Progress)) (*ytdlp.Result, error) {
f.mu.Lock()
f.downloads = append(f.downloads, req)
var scripted error
if q := f.DownloadErrs[req.URL]; len(q) > 0 {
scripted = q[0]
f.DownloadErrs[req.URL] = q[1:]
}
size := f.FileSize
if size == 0 {
size = 1024
}
delay, block := f.Delay, f.Block
info := f.Infos[req.URL]
f.mu.Unlock()
if onProgress != nil {
onProgress(ytdlp.Progress{Stage: ytdlp.StageDownloading, Downloaded: int64(size / 2), Total: int64(size)})
}
if block != nil {
select {
case <-block:
case <-ctx.Done():
return nil, &ytdlp.Error{Code: ytdlp.CodeCancelled, Raw: "cancelled"}
}
}
if delay > 0 {
select {
case <-time.After(delay):
case <-ctx.Done():
return nil, &ytdlp.Error{Code: ytdlp.CodeCancelled, Raw: "cancelled"}
}
}
if scripted != nil {
return nil, scripted
}
if req.MaxSize > 0 && int64(size) > req.MaxSize {
return nil, &ytdlp.Error{Code: ytdlp.CodeTooLarge, Raw: "too large"}
}
ext := "mp4"
switch req.Profile.Kind() {
case media.KindAudio:
ext = string(req.Profile)
case media.KindThumb:
ext = "jpg"
case media.KindSubs:
ext = "srt"
}
if err := os.MkdirAll(req.Dir, 0o750); err != nil {
return nil, err
}
path := filepath.Join(req.Dir, "media."+ext)
if err := os.WriteFile(path, make([]byte, size), 0o640); err != nil {
return nil, err
}
if info == nil {
info = DefaultInfo(req.URL)
}
res := &ytdlp.Result{
Path: path, Size: int64(size), Ext: ext,
ID: info.ID, Title: info.Title, Uploader: info.Uploader, Extractor: info.Extractor,
Duration: float64(info.Duration),
}
if req.Profile.Kind() == media.KindVideo {
res.Width, res.Height = 1280, 720
}
if onProgress != nil {
onProgress(ytdlp.Progress{Stage: ytdlp.StageProcessing})
}
return res, nil
}
// Probes returns the URLs probed so far.
func (f *Fake) Probes() []string {
f.mu.Lock()
defer f.mu.Unlock()
return append([]string(nil), f.probes...)
}
// Downloads returns the download requests seen so far.
func (f *Fake) Downloads() []ytdlp.DownloadRequest {
f.mu.Lock()
defer f.mu.Unlock()
return append([]ytdlp.DownloadRequest(nil), f.downloads...)
}