package app_test import ( "context" "errors" "fmt" "os" "path/filepath" "strings" "sync/atomic" "testing" "time" "github.com/noderunners/dlbot/internal/cache" "github.com/noderunners/dlbot/internal/config" "github.com/noderunners/dlbot/internal/db" "github.com/noderunners/dlbot/internal/media" "github.com/noderunners/dlbot/internal/tg/fakeserver" "github.com/noderunners/dlbot/internal/ytdlp" "github.com/noderunners/dlbot/internal/ytdlp/ytdlptest" ) const carol = int64(44) // fakeTranscoder stands in for ffmpeg. type fakeTranscoder struct { calls atomic.Int32 fail atomic.Bool } func (f *fakeTranscoder) Derive(_ context.Context, src, dir string, profile media.Profile) (*ytdlp.Result, error) { f.calls.Add(1) if f.fail.Load() { return nil, &ytdlp.Error{Code: ytdlp.CodeProcessing, Raw: "ffmpeg: boom"} } if _, err := os.Stat(src); err != nil { return nil, &ytdlp.Error{Code: ytdlp.CodeProcessing, Raw: "source missing"} } if err := os.MkdirAll(dir, 0o750); err != nil { return nil, err } ext := "mp4" if profile.Kind() == media.KindAudio { ext = string(profile) } out := filepath.Join(dir, "media."+ext) if err := os.WriteFile(out, make([]byte, 500), 0o640); err != nil { return nil, err } res := &ytdlp.Result{Path: out, Size: 500, Ext: ext, Duration: 60} if h := profile.Height(); h > 0 { res.Width, res.Height = h*16/9, h } return res, nil } func uploaded(c fakeserver.Call, field string) bool { _, ok := c.Files[field] return ok } func (h *harness) entry(url string, profile string) *db.CacheEntry { h.t.Helper() info := h.fake.Infos[url] if info == nil { info = ytdlptest.DefaultInfo(url) } ext, id := cache.Canonical(info.Extractor, info.ID, url) e, err := h.app.Store.GetCacheEntry(context.Background(), fakeserver.BotID, ext, id, profile) if errors.Is(err, db.ErrNotFound) { return nil } if err != nil { h.t.Fatal(err) } return e } // fetch has a user get the best profile of a link and waits for the file. func (h *harness) fetch(user int64, url string) fakeserver.Call { h.t.Helper() card := h.card(user, user, url) seq := h.press(user, user, card, "dl:") video := h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == user && !c.Failed }) h.wait(seq, edits, func(c fakeserver.Call) bool { return c.ChatID() == user && strings.Contains(c.Text(), "Done") }) return video } func (h *harness) usage(user int64) db.Usage { h.t.Helper() u, err := h.app.Service.Usage(context.Background(), user) if err != nil { h.t.Fatal(err) } return u } func TestCacheHitResendsByFileIDWithoutDownloading(t *testing.T) { // Two different URLs of the same video share one cache entry. watch, short := "https://example.com/watch?v=same", "https://example.com/s/same" same := func(url string) *ytdlp.Info { i := ytdlptest.DefaultInfo(url) i.ID = "same-video" return i } h := start(t, &ytdlptest.Fake{Infos: map[string]*ytdlp.Info{watch: same(watch), short: same(short)}}, nil) first := h.fetch(alice, watch) if !uploaded(first, "video") { t.Fatal("the first delivery must upload the file") } e := h.entry(watch, "best") if e == nil || e.TgFileID == "" || e.StorageKey == "" || e.Size != 1024 || e.Title != "Test Video" { t.Fatalf("cache entry after the first download = %+v", e) } second := h.fetch(bob, short) if uploaded(second, "video") || second.Params["video"] != e.TgFileID { t.Fatalf("the second delivery must resend by file_id %q, got video=%q files=%v", e.TgFileID, second.Params["video"], second.Files) } if n := len(h.fake.Downloads()); n != 1 { t.Fatalf("yt-dlp ran %d times, want 1", n) } if got := h.entry(watch, "best"); got.Hits != 1 { t.Fatalf("hits = %d, want 1", got.Hits) } if st := h.app.Cache.Stats(); st.Hits != 1 || st.Misses != 1 || st.BytesSaved != 1024 { t.Fatalf("stats = %+v", st) } done := h.waitJobs(db.JobDone, 2) if done[0].CacheHit == done[1].CacheHit { t.Fatal("want one worker job and one cache hit job") } // The stored copy belongs to the cache and survives the cache hit job. if n := h.storedFiles(); n != 1 { t.Fatalf("stored files = %d, want 1", n) } } func TestMetadataIsRememberedBetweenRequests(t *testing.T) { h := start(t, nil, nil) h.card(alice, alice, link) h.card(bob, bob, link) if n := len(h.fake.Probes()); n != 1 { t.Fatalf("the link was probed %d times, want 1", n) } } // --- acceptance: a cache hit still enforces free limits and quota ----------- // noSizeInfo is a video whose metadata promises nothing about its size, // which is common. Only the real file tells. func noSizeInfo(id string, seconds float64) *ytdlp.Info { return &ytdlp.Info{Type: "video", ID: id, Title: "Clip " + id, Extractor: "fake", Duration: ytdlp.Float(seconds)} } func TestCacheHitEnforcesSizeLimit(t *testing.T) { h := startMoney(t, &ytdlptest.Fake{FileSize: 3 << 20, Infos: map[string]*ytdlp.Info{link: noSizeInfo("sz", 30)}}, func(c *config.Config) { c.Limits.Free.MaxSizeMB = 2 }) if _, err := h.app.Billing.GrantPass(context.Background(), h.wallet(alice).ID, "day", "test"); err != nil { t.Fatal(err) } h.fetch(alice, link) // a pass holder puts the 3 MB file in the cache if e := h.entry(link, "best"); e == nil || e.Size != 3<<20 { t.Fatalf("cache entry = %+v", e) } // Bob is on the free tier with a 2 MB cap. The file is right there in // the cache, and he still must not get it. card := h.card(bob, bob, link) seq := h.press(bob, bob, card, "dl:") offer := h.wait(seq, "sendMessage", textHas("larger than your limit of 2.0 MB")) if !strings.Contains(offer.Text(), "You can lift the limit") { t.Fatalf("offer = %q", offer.Text()) } h.never(seq, "sendVideo|sendDocument", func(c fakeserver.Call) bool { return c.ChatID() == bob }) if u := h.usage(bob); u.Downloads != 0 || u.Bytes != 0 { t.Fatalf("a refused cache hit used quota: %+v", u) } if n := len(h.deliveriesOf(bob, db.DeliverySent)) + len(h.deliveriesOf(bob, db.DeliveryPending)); n != 0 { t.Fatalf("bob has %d deliveries", n) } if n := len(h.fake.Downloads()); n != 1 { t.Fatalf("downloads = %d", n) } // With a pass of his own he gets it, from the cache. if _, err := h.app.Billing.GrantPass(context.Background(), h.wallet(bob).ID, "day", "test"); err != nil { t.Fatal(err) } card = h.card(bob, bob, link) seq = h.press(bob, bob, card, "dl:") video := h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == bob }) if uploaded(video, "video") || len(h.fake.Downloads()) != 1 { t.Fatal("bob's download should have been a cache hit") } } func TestCacheHitEnforcesDurationLimit(t *testing.T) { // The metadata gives no duration; the cached file is 20 minutes long. h := startMoney(t, &ytdlptest.Fake{Infos: map[string]*ytdlp.Info{link: noSizeInfo("dur", 0)}}, nil) if _, err := h.app.Billing.GrantPass(context.Background(), h.wallet(alice).ID, "day", "test"); err != nil { t.Fatal(err) } h.fetch(alice, link) // Record the real duration the way a worker with ffprobe would have. if _, err := h.app.DB.SQL.Exec(`UPDATE cache_entries SET duration = 1200`); err != nil { t.Fatal(err) } card := h.card(bob, bob, link) seq := h.press(bob, bob, card, "dl:") h.wait(seq, "sendMessage", textHas("longer than your limit of 10 minutes")) h.never(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == bob }) } func TestCacheHitCountsAgainstAndIsStoppedByTheDailyQuota(t *testing.T) { other := "https://example.com/other" h := start(t, nil, func(c *config.Config) { c.Limits.Free.DailyDownloads = 1 }) h.fetch(alice, link) // alice fills the cache and uses her one download // A cache hit is a download like any other: it counts. h.fetch(bob, link) if u := h.usage(bob); u.Downloads != 1 || u.Bytes != 1024 { t.Fatalf("usage after a cache hit = %+v, want 1 download and its bytes", u) } // Bob's quota is used up. The cached file is refused like a fresh one. card := h.card(bob, bob, link) seq := h.press(bob, bob, card, "dl:") alert := h.wait(seq, "answerCallbackQuery", nil) if !strings.Contains(alert.Params["text"], "You used your 1 download for today") { t.Fatalf("alert = %q", alert.Params["text"]) } h.never(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == bob }) // And the other way round: carol spends her quota on a fresh download // and is then refused the cached one. h.fetch(carol, other) card = h.card(carol, carol, link) seq = h.press(carol, carol, card, "dl:") alert = h.wait(seq, "answerCallbackQuery", nil) if !strings.Contains(alert.Params["text"], "You used your 1 download for today") { t.Fatalf("alert = %q", alert.Params["text"]) } if n := len(h.fake.Downloads()); n != 2 { t.Fatalf("downloads = %d, want 2", n) } } func TestCacheHitRespectsActiveJobLimitAndChargesCredits(t *testing.T) { slow := "https://example.com/slow" block := make(chan struct{}) fake := &ytdlptest.Fake{} h := startMoney(t, fake, nil) h.fetch(alice, link) // Bob has one download running, which is all the free tier allows. fake.Block = block card := h.card(bob, bob, slow) h.press(bob, bob, card, "dl:") h.waitJobs(db.JobRunning, 1) cached := h.card(bob, bob, link) seq := h.press(bob, bob, cached, "dl:") // Payments are on, so the refusal comes with the offer to upgrade. h.wait(seq, "sendMessage", textHas("already have 1 download running")) h.never(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == bob }) close(block) h.waitJobs(db.JobRunning, 0) // Carol pays with credits. A cache hit costs what a download costs. h.grant(carol, 120) h.fetch(carol, link) if got := h.balance(carol); got != 70 { t.Fatalf("balance after a cache hit = %d, want 70", got) } sent := h.waitSent(carol, 1) if sent[0].Source != "own_credits" || sent[0].ChargeSats != 50 { t.Fatalf("delivery = %+v", sent[0]) } } // --- acceptance: two requesters share one download ------------------------- func TestTwoRequestersShareOneDownload(t *testing.T) { block := make(chan struct{}) h := start(t, &ytdlptest.Fake{Block: block, FileSize: 2048}, nil) cardA := h.card(alice, alice, link) seqA := h.press(alice, alice, cardA, "dl:") h.waitJobs(db.JobRunning, 1) // Bob asks for the same video, in a group, while it is downloading. cardB := h.card(group, bob, "/dl "+link) seqB := h.press(group, bob, cardB, "dl:") h.wait(seqB, edits, func(c fakeserver.Call) bool { return c.ChatID() == group && strings.Contains(c.Text(), "Downloading") }) if n := len(h.jobs(db.JobRunning)) + len(h.jobs(db.JobQueued)); n != 1 { t.Fatalf("%d jobs for one video, want 1", n) } job := h.jobs(db.JobRunning)[0] dels, _ := h.app.Store.DeliveriesForJob(context.Background(), job.ID, db.DeliveryPending) if len(dels) != 2 { t.Fatalf("the job has %d requesters, want 2", len(dels)) } close(block) // Everyone is notified on completion: both get the file. toAlice := h.wait(seqA, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == alice }) toGroup := h.wait(seqA, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == group }) h.wait(seqA, edits, func(c fakeserver.Call) bool { return c.ChatID() == alice && strings.Contains(c.Text(), "Done") }) h.wait(seqA, edits, func(c fakeserver.Call) bool { return c.ChatID() == group && strings.Contains(c.Text(), "Done") }) // The file went over the wire once; the second requester got the // file_id of the first upload. ups := 0 for _, c := range []fakeserver.Call{toAlice, toGroup} { if uploaded(c, "video") { ups++ } } if ups != 1 { t.Fatalf("the file was uploaded %d times, want 1", ups) } if n := len(h.fake.Downloads()); n != 1 { t.Fatalf("yt-dlp ran %d times, want 1", n) } // Both paid their dues: each used one download of their quota. if a, b := h.usage(alice), h.usage(bob); a.Downloads != 1 || b.Downloads != 1 { t.Fatalf("usage alice=%+v bob=%+v", a, b) } h.waitJobs(db.JobDone, 1) } func TestOneRequesterCancellingDoesNotStopTheOther(t *testing.T) { block := make(chan struct{}) h := start(t, &ytdlptest.Fake{Block: block}, nil) cardA := h.card(alice, alice, link) seqA := h.press(alice, alice, cardA, "dl:") statusA := h.wait(seqA, edits, textHas("Downloading")) cardB := h.card(bob, bob, link) seqB := h.press(bob, bob, cardB, "dl:") h.wait(seqB, edits, func(c fakeserver.Call) bool { return c.ChatID() == bob && strings.Contains(c.Text(), "Downloading") }) seq := h.press(alice, alice, statusA, "jc:") h.wait(seq, edits, func(c fakeserver.Call) bool { return c.ChatID() == alice && strings.Contains(c.Text(), "Cancelled") }) if len(h.jobs(db.JobRunning)) != 1 { t.Fatal("the job must keep running for bob") } close(block) h.wait(seqB, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == bob }) h.never(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == alice }) if u := h.usage(alice); u.Downloads != 0 { t.Fatalf("alice cancelled and should have her quota back: %+v", u) } } func TestSharedJobKeepsEachRequestersOwnCap(t *testing.T) { block := make(chan struct{}) h := startMoney(t, &ytdlptest.Fake{Block: block, FileSize: 3 << 20, Infos: map[string]*ytdlp.Info{link: noSizeInfo("cap", 30)}}, func(c *config.Config) { c.Limits.Free.MaxSizeMB = 2 }) if _, err := h.app.Billing.GrantPass(context.Background(), h.wallet(alice).ID, "day", "test"); err != nil { t.Fatal(err) } // Alice (pass, no size worry) starts the download. Bob (free, 2 MB // cap) joins it. Nobody knows the size yet. cardA := h.card(alice, alice, link) seqA := h.press(alice, alice, cardA, "dl:") h.waitJobs(db.JobRunning, 1) cardB := h.card(bob, bob, link) seqB := h.press(bob, bob, cardB, "dl:") h.wait(seqB, edits, func(c fakeserver.Call) bool { return c.ChatID() == bob && strings.Contains(c.Text(), "Downloading") }) if n := len(h.jobs(db.JobRunning)); n != 1 { t.Fatalf("jobs = %d, want one shared job", n) } close(block) // The file turns out to be 3 MB. Alice gets it, Bob does not. h.wait(seqA, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == alice }) h.wait(seqB, edits, func(c fakeserver.Call) bool { return c.ChatID() == bob && strings.Contains(c.Text(), "larger than your limit") }) h.never(seqB, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == bob }) if u := h.usage(bob); u.Downloads != 0 { t.Fatalf("bob got nothing and should have his quota back: %+v", u) } } func TestPaidRequesterLiftsAQueuedSharedJob(t *testing.T) { block := make(chan struct{}) defer close(block) h := startMoney(t, &ytdlptest.Fake{Block: block}, func(c *config.Config) { c.Worker.Concurrency = 1 }) busy := h.card(carol, carol, "https://example.com/busy") h.press(carol, carol, busy, "dl:") h.waitJobs(db.JobRunning, 1) // Bob (free) queues the video. Alice (pass) asks for the same one. cardB := h.card(bob, bob, link) h.press(bob, bob, cardB, "dl:") h.waitJobs(db.JobQueued, 1) if _, err := h.app.Billing.GrantPass(context.Background(), h.wallet(alice).ID, "day", "test"); err != nil { t.Fatal(err) } cardA := h.card(alice, alice, link) seq := h.press(alice, alice, cardA, "dl:") h.wait(seq, edits, func(c fakeserver.Call) bool { return c.ChatID() == alice && strings.Contains(c.Text(), "In the queue") }) q := h.jobs(db.JobQueued) if len(q) != 1 { t.Fatalf("queued jobs = %d, want the one shared job", len(q)) } // The shared job now runs under the looser caps and in the paid lane, // which also speeds it up for bob. if q[0].Lane != db.LanePaid || q[0].MaxSize != 2000<<20 { t.Fatalf("shared job lane=%s max_size=%d", q[0].Lane, q[0].MaxSize) } } // --- acceptance: an invalid file_id falls back correctly -------------------- func TestInvalidFileIDFallsBackToTheStoredCopy(t *testing.T) { h := start(t, &ytdlptest.Fake{FileSize: 4096}, nil) h.fetch(alice, link) old := h.entry(link, "best").TgFileID // Telegram stops accepting the cached file_id. h.srv.FailNext("sendVideo", 400, "Bad Request: wrong file identifier/HTTP URL specified") card := h.card(bob, bob, link) seq := h.press(bob, bob, card, "dl:") // First try: by file_id, refused. h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.Failed && c.Params["video"] == old }) // Second try: the stored copy is uploaded again. healed := h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return !c.Failed && c.ChatID() == bob }) if !uploaded(healed, "video") || healed.Files["video"].Size != 4096 { t.Fatalf("the fallback must upload the stored copy: %+v %+v", healed.Params, healed.Files) } h.wait(seq, edits, func(c fakeserver.Call) bool { return c.ChatID() == bob && strings.Contains(c.Text(), "Done") }) if n := len(h.fake.Downloads()); n != 1 { t.Fatalf("yt-dlp ran %d times; the stored copy should have been enough", n) } // The entry is updated with the new file_id. e := h.entry(link, "best") if e.TgFileID == "" || e.TgFileID == old || e.StorageKey == "" { t.Fatalf("entry after healing = %+v (old file_id %q)", e, old) } // The next requester is served by the new file_id, without an upload. next := h.fetch(carol, link) if uploaded(next, "video") || next.Params["video"] != e.TgFileID { t.Fatalf("the healed entry was not used: video=%q", next.Params["video"]) } if u := h.usage(bob); u.Downloads != 1 { t.Fatalf("bob was counted %d times for one file", u.Downloads) } } func TestInvalidFileIDWithoutStoredCopyDownloadsAgain(t *testing.T) { h := startMoney(t, &ytdlptest.Fake{FileSize: 4096}, nil) h.grant(bob, 100) h.fetch(alice, link) old := h.entry(link, "best") // The stored copy is gone (evicted, or lost with a disk) and the // file_id stops working too. if err := h.app.Storage.Delete(context.Background(), old.StorageKey); err != nil { t.Fatal(err) } h.srv.FailNext("sendVideo", 400, "Bad Request: wrong file identifier/HTTP URL specified") card := h.card(bob, bob, link) seq := h.press(bob, bob, card, "dl:") h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.Failed }) fresh := h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return !c.Failed && c.ChatID() == bob }) if !uploaded(fresh, "video") { t.Fatal("the fresh download must be uploaded") } h.wait(seq, edits, func(c fakeserver.Call) bool { return c.ChatID() == bob && strings.Contains(c.Text(), "Done") }) if n := len(h.fake.Downloads()); n != 2 { t.Fatalf("yt-dlp ran %d times, want 2 (the original and the re-download)", n) } // The entry is whole again: new file_id, new stored copy. e := h.entry(link, "best") if e == nil || e.TgFileID == "" || e.TgFileID == old.TgFileID || e.StorageKey == "" || e.StorageKey == old.StorageKey { t.Fatalf("entry after re-download = %+v", e) } if _, err := h.app.Storage.Stat(context.Background(), e.StorageKey); err != nil { t.Fatalf("the new stored copy is missing: %v", err) } // Bob was admitted and charged once, although two attempts were made. if got := h.balance(bob); got != 50 { t.Fatalf("balance = %d, want 50 (charged once)", got) } if u := h.usage(bob); u.Downloads != 1 { t.Fatalf("usage = %+v, want 1 download", u) } if n := len(h.waitSent(bob, 1)); n != 1 { t.Fatalf("bob got %d files", n) } h.booksBalance() } // --- derive, fresh, takedown, privacy -------------------------------------- func TestLowerProfileIsDerivedFromTheStoredCopy(t *testing.T) { trans := &fakeTranscoder{} hd := ytdlptest.DefaultInfo(link) hd.Formats = append(hd.Formats, ytdlp.Format{FormatID: "v1080", Ext: "mp4", VCodec: "avc1", ACodec: "none", Height: 1080, Filesize: 20 << 20}) h := startWith(t, &ytdlptest.Fake{Infos: map[string]*ytdlp.Info{link: hd}}, trans, nil) h.fetch(alice, link) // stores "best" at 720p (the fake's output height) card := h.card(bob, bob, link) seq := h.press(bob, bob, card, "dl:"+strings.Split(card.Buttons()[0].Data, ":")[1]+":480") video := h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == bob }) if video.Files["video"].Size != 500 || video.Params["height"] != "480" { t.Fatalf("derived video = %+v %+v", video.Params, video.Files) } h.wait(seq, edits, func(c fakeserver.Call) bool { return c.ChatID() == bob && strings.Contains(c.Text(), "Done") }) if trans.calls.Load() != 1 { t.Fatalf("transcoder ran %d times, want 1", trans.calls.Load()) } if n := len(h.fake.Downloads()); n != 1 { t.Fatalf("yt-dlp ran %d times; the 480p file should come from the stored copy", n) } // The derived profile is cached under its own key. if e := h.entry(link, "480"); e == nil || e.Size != 500 || e.Height != 480 || e.TgFileID == "" { t.Fatalf("derived entry = %+v", e) } // MP3 is derived the same way. cardC := h.card(carol, carol, link) var mp3 string for _, b := range cardC.Buttons() { if strings.HasSuffix(b.Data, ":mp3") { mp3 = b.Data } } seq = h.srv.Seq() h.srv.PushCallback(carol, carol, cardC.MessageID, mp3) h.wait(seq, "sendAudio", func(c fakeserver.Call) bool { return c.ChatID() == carol }) if trans.calls.Load() != 2 || len(h.fake.Downloads()) != 1 { t.Fatalf("transcodes=%d downloads=%d, want 2 and 1", trans.calls.Load(), len(h.fake.Downloads())) } } func TestFailedDeriveFallsBackToDownload(t *testing.T) { trans := &fakeTranscoder{} trans.fail.Store(true) hd := ytdlptest.DefaultInfo(link) hd.Formats = append(hd.Formats, ytdlp.Format{FormatID: "v1080", Ext: "mp4", VCodec: "avc1", ACodec: "none", Height: 1080, Filesize: 20 << 20}) h := startWith(t, &ytdlptest.Fake{Infos: map[string]*ytdlp.Info{link: hd}}, trans, nil) h.fetch(alice, link) card := h.card(bob, bob, link) seq := h.press(bob, bob, card, "dl:"+strings.Split(card.Buttons()[0].Data, ":")[1]+":480") h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == bob }) if trans.calls.Load() != 1 || len(h.fake.Downloads()) != 2 { t.Fatalf("transcodes=%d downloads=%d, want 1 failed transcode and a download instead", trans.calls.Load(), len(h.fake.Downloads())) } dl := h.fake.Downloads() if string(dl[1].Profile) != "480" { t.Fatalf("fallback downloaded profile %s", dl[1].Profile) } } func TestFreshCommandSkipsTheCacheUnderNormalLimits(t *testing.T) { h := start(t, nil, func(c *config.Config) { c.Limits.Free.DailyDownloads = 2 }) h.fetch(alice, link) old := h.entry(link, "best") seq := h.srv.Seq() h.srv.PushMessage(alice, alice, "/fresh "+link) card := h.wait(seq, "sendPhoto|editMessageText", func(c fakeserver.Call) bool { _, ok := c.Button("dl:"); return ok }) seq = h.press(alice, alice, card, "dl:") video := h.wait(seq, "sendVideo", nil) if !uploaded(video, "video") { t.Fatal("/fresh must download and upload again") } h.wait(seq, edits, textHas("Done")) if n := len(h.fake.Downloads()); n != 2 { t.Fatalf("downloads = %d, want 2", n) } // The fresh result replaces the cached one. deadline := time.Now().Add(5 * time.Second) for { if e := h.entry(link, "best"); e != nil && e.StorageKey != old.StorageKey { break } if time.Now().After(deadline) { t.Fatal("the cache entry was not replaced by the fresh download") } time.Sleep(20 * time.Millisecond) } if n := h.storedFiles(); n != 1 { t.Fatalf("stored files = %d, the replaced copy must be deleted", n) } // Normal limits apply: that was the second and last download today. seq = h.srv.Seq() h.srv.PushMessage(alice, alice, "/fresh "+link) card = h.wait(seq, "sendPhoto|editMessageText", func(c fakeserver.Call) bool { _, ok := c.Button("dl:"); return ok }) seq = h.press(alice, alice, card, "dl:") alert := h.wait(seq, "answerCallbackQuery", nil) if !strings.Contains(alert.Params["text"], "You used your 2 downloads for today") { t.Fatalf("alert = %q", alert.Params["text"]) } } func TestPrivateContentIsNeverCached(t *testing.T) { private := ytdlptest.DefaultInfo(link) private.Availability = "needs_auth" h := start(t, &ytdlptest.Fake{Infos: map[string]*ytdlp.Info{link: private}}, nil) h.fetch(alice, link) h.waitJobs(db.JobDone, 1) if e := h.entry(link, "best"); e != nil { t.Fatalf("content that needed a login was cached: %+v", e) } if n := h.storedFiles(); n != 0 { t.Fatalf("%d files kept for content that must not be stored", n) } // The next requester gets a download of their own, not a shared copy. second := h.fetch(bob, link) if !uploaded(second, "video") || len(h.fake.Downloads()) != 2 { t.Fatalf("private content was shared between users: downloads=%d", len(h.fake.Downloads())) } } func TestPurgeCommandTakesDownAndBlocks(t *testing.T) { h := start(t, nil, func(c *config.Config) { c.Owners = []int64{alice} }) h.fetch(bob, link) if h.entry(link, "best") == nil || h.storedFiles() != 1 { t.Fatal("setup: the file should be cached") } // Only the owner can purge. seq := h.srv.Seq() h.srv.PushMessage(bob, bob, "/purge "+link) h.never(seq, "sendMessage", textHas("Taken down")) seq = h.srv.Seq() h.srv.PushMessage(alice, alice, "/purge "+link+" copyright notice") done := h.wait(seq, "sendMessage", textHas("Taken down")) if !strings.Contains(done.Text(), "1 cached file was removed") || !strings.Contains(done.Text(), "fake:vid-") { t.Fatalf("purge answer = %q", done.Text()) } if n := h.storedFiles(); n != 0 { t.Fatalf("stored files after purge = %d", n) } if e := h.entry(link, "best"); e == nil || e.Status != db.CacheBlocked || e.TgFileID != "" { t.Fatalf("entry after purge = %+v", e) } // Nobody can get it anymore, from the cache or fresh. card := h.card(carol, carol, link) seq = h.press(carol, carol, card, "dl:") alert := h.wait(seq, "answerCallbackQuery", nil) if !strings.Contains(alert.Params["text"], "not available through this bot") { t.Fatalf("alert = %q", alert.Params["text"]) } h.never(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == carol }) if n := len(h.fake.Downloads()); n != 1 { t.Fatalf("a purged video was downloaded again (%d downloads)", n) } seq = h.srv.Seq() h.srv.PushMessage(alice, alice, "/cache") h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return strings.Contains(c.Text(), "Taken down: 1") && strings.Contains(c.Text(), "Entries: 0") }) } // --- playlists, subtitles, history ----------------------------------------- func TestPlaylistItemsAreSeparateJobsStartedInTurn(t *testing.T) { list := "https://example.com/playlist?list=PL1" var entries []ytdlp.Entry for i := 1; i <= 5; i++ { entries = append(entries, ytdlp.Entry{ID: fmt.Sprint(i), Title: fmt.Sprintf("Part %d", i), URL: fmt.Sprintf("https://example.com/part%d", i)}) } h := start(t, &ytdlptest.Fake{Infos: map[string]*ytdlp.Info{ list: {Type: "playlist", ID: "PL1", Title: "My List", Entries: entries}, }}, nil) seq := h.srv.Seq() h.srv.PushMessage(alice, alice, list) card := h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { _, ok := c.Button("pl:"); return ok }) // The free tier fetches 3 of the 5 items. if !strings.Contains(card.Text(), "Playlist with 5 items. I will fetch 3 of them") { t.Fatalf("playlist card = %q", card.Text()) } if labels(card) != "Best | 720p | 480p | MP3 | Cancel" { t.Fatalf("playlist buttons = %q", labels(card)) } seq = h.press(alice, alice, card, "pl:") h.wait(seq, "editMessageText", textHas("3 items are lined up")) for i := 1; i <= 3; i++ { h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return strings.Contains(c.Text(), "Test Video") && c.Files["video"].Size > 0 }) } h.waitJobs(db.JobDone, 3) // One job and one cache entry per item, in playlist order. dl := h.fake.Downloads() if len(dl) != 3 { t.Fatalf("downloads = %d, want 3", len(dl)) } for i, d := range dl { if want := fmt.Sprintf("https://example.com/part%d", i+1); d.URL != want { t.Errorf("download %d was %s, want %s", i, d.URL, want) } if h.entry(d.URL, "best") == nil { t.Errorf("item %d has no cache entry of its own", i) } } if u := h.usage(alice); u.Downloads != 3 { t.Fatalf("usage = %+v, each item counts as a download", u) } } func TestCancelStopsWaitingPlaylistItems(t *testing.T) { list := "https://example.com/playlist?list=PL2" block := make(chan struct{}) defer close(block) h := start(t, &ytdlptest.Fake{Block: block, Infos: map[string]*ytdlp.Info{ list: {Type: "playlist", ID: "PL2", Title: "L", Entries: []ytdlp.Entry{ {URL: "https://example.com/a1"}, {URL: "https://example.com/a2"}, {URL: "https://example.com/a3"}, }}, }}, nil) seq := h.srv.Seq() h.srv.PushMessage(alice, alice, list) card := h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { _, ok := c.Button("pl:"); return ok }) h.press(alice, alice, card, "pl:") h.waitJobs(db.JobRunning, 1) // one runs, two wait (free tier: one at a time) if n, _ := h.app.Store.CountWaitingRequests(context.Background(), alice); n != 2 { t.Fatalf("waiting items = %d, want 2", n) } seq = h.srv.Seq() h.srv.PushMessage(alice, alice, "/cancel") h.wait(seq, "sendMessage", textHas("Cancelled 3 downloads.")) h.waitJobs(db.JobCancelled, 1) time.Sleep(300 * time.Millisecond) if n := len(h.fake.Downloads()); n != 1 { t.Fatalf("a cancelled playlist kept downloading: %d downloads", n) } } func TestSubtitlesListLanguagesWithTheUsersFirst(t *testing.T) { withSubs := ytdlptest.DefaultInfo(link) withSubs.Subtitles = map[string][]ytdlp.SubTrack{"de": {{Ext: "vtt"}}, "en": {{Ext: "vtt"}}, "fr": {{Ext: "vtt"}}} withSubs.AutomaticCaptions = map[string][]ytdlp.SubTrack{"es": {{Ext: "vtt"}}, "en": {{Ext: "vtt"}}} bare := "https://example.com/nosubs" h := start(t, &ytdlptest.Fake{Infos: map[string]*ytdlp.Info{link: withSubs}}, nil) seq := h.srv.Seq() h.srv.PushMessage(alice, alice, "/subs "+link) card := h.wait(seq, "editMessageText", textHas("Pick a subtitle language")) // English is the user's language: first and marked. Written subtitles // come before automatic ones. if labels(card) != "✓ en | de | fr | es (auto) | Cancel" { t.Fatalf("subtitle buttons = %q", labels(card)) } seq = h.press(alice, alice, card, "dl:") doc := h.wait(seq, "sendDocument", nil) if doc.Files["document"].Name != "Test Video.srt" { t.Fatalf("subtitle file = %+v", doc.Files) } if dl := h.fake.Downloads(); len(dl) != 1 || string(dl[0].Profile) != "subs:en" { t.Fatalf("downloads = %+v", dl) } seq = h.srv.Seq() h.srv.PushMessage(alice, alice, "/subs "+bare) h.wait(seq, "editMessageText", textHas("has no subtitles")) } func TestHistoryResendsFromTheCache(t *testing.T) { h := start(t, nil, nil) seq := h.srv.Seq() h.srv.PushMessage(alice, alice, "/history") h.wait(seq, "sendMessage", textHas("no past downloads")) h.fetch(alice, link) seq = h.srv.Seq() h.srv.PushMessage(alice, alice, "/history") list := h.wait(seq, "sendMessage", textHas("Your past downloads")) if !strings.Contains(list.Text(), "1. Test Video · Best") || labels(list) != "1. Test Video" { t.Fatalf("history = %q buttons=%q", list.Text(), labels(list)) } // Bob cannot resend from Alice's history. seq = h.press(alice, bob, list, "rs:") h.wait(seq, "answerCallbackQuery", nil) h.never(seq, "sendVideo", nil) seq = h.press(alice, alice, list, "rs:") again := h.wait(seq, "sendVideo", nil) if uploaded(again, "video") || len(h.fake.Downloads()) != 1 { t.Fatal("a resend should come from the cache") } // A resend is a download like any other and counts. if u := h.usage(alice); u.Downloads != 2 { t.Fatalf("usage = %+v", u) } }