Phase 3: cache
Repeat downloads are instant, and the cache never bypasses a limit. - internal/cache: canonical key (extractor + video id + profile, URL hash fallback), per-bot file_id layer, stored copy layer, metadata layer, TTL by source type, LRU-plus-hits eviction that keeps file_ids, orphan sweeper, takedown that deletes, invalidates and blocks - One admission gate: a cache hit passes the same size, duration, quota, volume, active job and queue checks as a fresh download, is judged by the real cached file, and costs the same. It only skips the worker - Singleflight: a second requester joins the job that is queued or running for the same result. Each keeps their own caps, checked at delivery - Derive: lower profiles and audio are transcoded from a stored copy with ffmpeg; a higher profile that already fits is served as an alias; a failed derive falls back to a download - Self-healing: a rejected file_id falls back to the stored copy, then to a fresh download, and the entry is updated either way - Private or login-gated content and live streams are never cached - Playlists as per-item jobs started in turn, /subs, /history with resend, /fresh, owner /purge and /cache - Worker removes its temp files right after the upload Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
0d50f453a0
commit
9c9d641eda
+26
-1
@@ -17,8 +17,10 @@ import (
|
||||
"github.com/noderunners/dlbot/internal/billing"
|
||||
"github.com/noderunners/dlbot/internal/billing/lnbits"
|
||||
"github.com/noderunners/dlbot/internal/bot"
|
||||
"github.com/noderunners/dlbot/internal/cache"
|
||||
"github.com/noderunners/dlbot/internal/config"
|
||||
"github.com/noderunners/dlbot/internal/db"
|
||||
"github.com/noderunners/dlbot/internal/ffmpeg"
|
||||
"github.com/noderunners/dlbot/internal/i18n"
|
||||
"github.com/noderunners/dlbot/internal/sched"
|
||||
"github.com/noderunners/dlbot/internal/service"
|
||||
@@ -35,6 +37,8 @@ type Options struct {
|
||||
Log *slog.Logger
|
||||
// Runner replaces the real yt-dlp, for tests.
|
||||
Runner ytdlp.Runner
|
||||
// Transcoder replaces the real ffmpeg, for tests.
|
||||
Transcoder ffmpeg.Transcoder
|
||||
// Tune is called with the bot before it starts, for tests.
|
||||
Tune func(*bot.Bot)
|
||||
}
|
||||
@@ -48,6 +52,7 @@ type App struct {
|
||||
Storage storage.Storage
|
||||
Sched *sched.Scheduler
|
||||
Billing *billing.Billing
|
||||
Cache *cache.Cache
|
||||
Service *service.Service
|
||||
Bot *bot.Bot
|
||||
HTTP *api.Server
|
||||
@@ -171,11 +176,24 @@ func New(ctx context.Context, opts Options) (*App, error) {
|
||||
ln = lnbits.New(cfg.LNbits.URL, cfg.LNbits.InvoiceKey)
|
||||
}
|
||||
a.Billing = billing.New(a.Store, ln, cfg, log)
|
||||
a.Service = service.New(cfg, a.Store, a.Sched, a.Billing, a.runner, log)
|
||||
|
||||
if a.tgBot, err = tg.NewBot(cfg.Telegram.Token, cfg.Telegram.APIURL); err != nil {
|
||||
return fail(fmt.Errorf("app: telegram client: %w", err))
|
||||
}
|
||||
// file_ids only work for the bot that got them, so the cache is keyed
|
||||
// by the bot's ID, which is the number in front of the token.
|
||||
a.Cache = cache.New(cache.Config{
|
||||
Enabled: cfg.Cache.Enabled,
|
||||
BudgetBytes: cfg.Cache.BudgetMB << 20,
|
||||
TTLDefault: cfg.Cache.TTL.D(),
|
||||
TTLStable: cfg.Cache.TTLStable.D(),
|
||||
TTLEphemeral: cfg.Cache.TTLEphemeral.D(),
|
||||
Stable: cfg.Cache.StableSites,
|
||||
Ephemeral: cfg.Cache.EphemeralSites,
|
||||
MetaTTL: cfg.Cache.MetaTTL.D(),
|
||||
Derive: cfg.Cache.Derive,
|
||||
}, a.tgBot.ID(), a.Store, a.Storage, log)
|
||||
a.Service = service.New(cfg, a.Store, a.Sched, a.Billing, a.Cache, a.runner, log)
|
||||
a.Bot, err = bot.New(ctx, bot.Deps{
|
||||
API: a.tgBot,
|
||||
Config: cfg,
|
||||
@@ -183,6 +201,7 @@ func New(ctx context.Context, opts Options) (*App, error) {
|
||||
Sched: a.Sched,
|
||||
Service: a.Service,
|
||||
Billing: a.Billing,
|
||||
Cache: a.Cache,
|
||||
Storage: a.Storage,
|
||||
I18n: tr,
|
||||
Log: log,
|
||||
@@ -208,6 +227,11 @@ func New(ctx context.Context, opts Options) (*App, error) {
|
||||
Heartbeat: cfg.Queue.Heartbeat.D(),
|
||||
ClaimWait: 5 * time.Second,
|
||||
}, &sched.Local{Sched: a.Sched, Storage: a.Storage}, a.runner, log)
|
||||
trans := opts.Transcoder
|
||||
if trans == nil {
|
||||
trans = &ffmpeg.Exec{Path: cfg.Worker.FfmpegPath, Timeout: cfg.Worker.DownloadTimeout.D()}
|
||||
}
|
||||
a.worker.SetTranscoder(trans)
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
@@ -257,6 +281,7 @@ func (a *App) Run(ctx context.Context) error {
|
||||
})
|
||||
run(func() { a.Sched.Run(ctx) })
|
||||
run(func() { a.Billing.Run(ctx) })
|
||||
run(func() { a.Cache.Run(ctx, a.cfg.Cache.SweepInterval.D()) })
|
||||
if a.worker != nil {
|
||||
run(func() { a.worker.Run(ctx) })
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/noderunners/dlbot/internal/bot"
|
||||
"github.com/noderunners/dlbot/internal/config"
|
||||
"github.com/noderunners/dlbot/internal/db"
|
||||
"github.com/noderunners/dlbot/internal/ffmpeg"
|
||||
"github.com/noderunners/dlbot/internal/storage"
|
||||
"github.com/noderunners/dlbot/internal/tg/fakeserver"
|
||||
"github.com/noderunners/dlbot/internal/ytdlp"
|
||||
@@ -29,6 +30,7 @@ type harness struct {
|
||||
srv *fakeserver.Server
|
||||
fake *ytdlptest.Fake
|
||||
runner ytdlp.Runner
|
||||
trans ffmpeg.Transcoder
|
||||
app *app.App
|
||||
cfg config.Config
|
||||
cancel context.CancelFunc
|
||||
@@ -52,6 +54,17 @@ func start(t *testing.T, fake *ytdlptest.Fake, mut func(*config.Config)) *harnes
|
||||
return h
|
||||
}
|
||||
|
||||
// startWith starts a core with a scripted yt-dlp and a scripted ffmpeg.
|
||||
func startWith(t *testing.T, fake *ytdlptest.Fake, trans ffmpeg.Transcoder, mut func(*config.Config)) *harness {
|
||||
t.Helper()
|
||||
pendingTranscoder = trans
|
||||
defer func() { pendingTranscoder = nil }()
|
||||
return start(t, fake, mut)
|
||||
}
|
||||
|
||||
// pendingTranscoder hands a transcoder to the next harness that starts.
|
||||
var pendingTranscoder ffmpeg.Transcoder
|
||||
|
||||
func startWithRunner(t *testing.T, runner ytdlp.Runner, mut func(*config.Config)) *harness {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
@@ -68,7 +81,7 @@ func startWithRunner(t *testing.T, runner ytdlp.Runner, mut func(*config.Config)
|
||||
if mut != nil {
|
||||
mut(&cfg)
|
||||
}
|
||||
h := &harness{t: t, srv: srv, runner: runner, cfg: cfg}
|
||||
h := &harness{t: t, srv: srv, runner: runner, cfg: cfg, trans: pendingTranscoder}
|
||||
h.boot()
|
||||
t.Cleanup(func() {
|
||||
h.stop()
|
||||
@@ -90,8 +103,8 @@ func (h *harness) boot() {
|
||||
a, err := app.New(ctx, app.Options{
|
||||
Config: h.cfg,
|
||||
Log: slog.New(&guardHandler{Handler: base, t: h.t}),
|
||||
Runner: h.runner,
|
||||
Tune: func(b *bot.Bot) { b.SetTimings(60*time.Millisecond, 0) },
|
||||
Runner: h.runner, Transcoder: h.trans,
|
||||
Tune: func(b *bot.Bot) { b.SetTimings(60*time.Millisecond, 0) },
|
||||
})
|
||||
if err != nil {
|
||||
cancel()
|
||||
@@ -302,8 +315,9 @@ func TestPrivateLinkReturnsFile(t *testing.T) {
|
||||
}
|
||||
|
||||
h.waitJobs(db.JobDone, 1)
|
||||
if n := h.storedFiles(); n != 0 {
|
||||
t.Fatalf("%d files left in storage after delivery", n)
|
||||
// The delivered file stays as the cache's stored copy.
|
||||
if n := h.storedFiles(); n != 1 {
|
||||
t.Fatalf("%d files in storage after delivery, want the one cached copy", n)
|
||||
}
|
||||
if n := len(h.fake.Probes()); n != 1 {
|
||||
t.Fatalf("probes = %d, want 1", n)
|
||||
@@ -572,9 +586,11 @@ func TestSendGivesUpAfterRepeatedFailures(t *testing.T) {
|
||||
}
|
||||
seq := h.press(alice, alice, card, "dl:")
|
||||
h.wait(seq, edits, textHas("could not send the file to Telegram"))
|
||||
h.waitJobs(db.JobDone, 1) // the job itself is closed and cleaned up
|
||||
if n := h.storedFiles(); n != 0 {
|
||||
t.Fatalf("%d files left in storage", n)
|
||||
h.waitJobs(db.JobDone, 1) // the job itself is closed
|
||||
// The download worked, only the send did not: the file is kept in the
|
||||
// cache, so the next request does not have to fetch it again.
|
||||
if n := h.storedFiles(); n != 1 {
|
||||
t.Fatalf("%d files in storage, want the cached copy", n)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -774,7 +790,7 @@ func TestCommandMenuIsRegistered(t *testing.T) {
|
||||
if err := json.Unmarshal([]byte(calls[0].Params["commands"]), &cmds); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(cmds) != 9 || cmds[0].Command != "dl" || cmds[0].Description != "Download a video from a link" {
|
||||
if len(cmds) != 10 || cmds[0].Command != "dl" || cmds[0].Description != "Download a video from a link" {
|
||||
t.Fatalf("commands = %+v", cmds)
|
||||
}
|
||||
for _, c := range cmds {
|
||||
|
||||
@@ -0,0 +1,798 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,10 @@ import (
|
||||
"github.com/noderunners/dlbot/internal/ytdlp/ytdlptest"
|
||||
)
|
||||
|
||||
const bigLink = "https://example.com/big"
|
||||
const (
|
||||
bigLink = "https://example.com/big"
|
||||
bigLink2 = "https://example.com/big2"
|
||||
)
|
||||
|
||||
// bigInfo is an 80 MB, one minute video: over the free size cap, well
|
||||
// inside the paid one.
|
||||
@@ -59,6 +62,9 @@ func startMoney(t *testing.T, fake *ytdlptest.Fake, mut func(*config.Config)) *m
|
||||
fake.Infos = map[string]*ytdlp.Info{}
|
||||
}
|
||||
fake.Infos[bigLink] = bigInfo()
|
||||
second := bigInfo()
|
||||
second.ID = "big2"
|
||||
fake.Infos[bigLink2] = second
|
||||
addr := freePort(t)
|
||||
h := start(t, fake, func(c *config.Config) {
|
||||
c.HTTP.Listen = addr
|
||||
@@ -422,7 +428,7 @@ func TestOverLimitPayForThisFileOnly(t *testing.T) {
|
||||
}
|
||||
|
||||
// It was for one file. The next big file is refused again.
|
||||
card = h.card(alice, alice, bigLink)
|
||||
card = h.card(alice, alice, bigLink2)
|
||||
seq = h.press(alice, alice, card, "dl:")
|
||||
h.wait(seq, "sendMessage", textHas("You can lift the limit"))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user