diff --git a/.env.example b/.env.example index 7f75f25..d4e4705 100644 --- a/.env.example +++ b/.env.example @@ -66,6 +66,25 @@ QUEUE_HEARTBEAT=10s # Tries per job. 2 means one automatic retry. QUEUE_MAX_ATTEMPTS=2 +# --- Cache ------------------------------------------------------------------ +# The cache only makes repeat downloads faster. It never changes limits. +CACHE_ENABLED=true +# Largest total size of stored copies, in MB. 0 means no cap. +CACHE_BUDGET_MB=20000 +# How long a result is served before it is fetched again, by kind of site. +CACHE_TTL=168h +CACHE_TTL_STABLE=720h +CACHE_TTL_EPHEMERAL=6h +# yt-dlp extractor name prefixes for the two special classes. +CACHE_STABLE_SITES=youtube,vimeo,archive.org,soundcloud,dailymotion,peertube,bandcamp +CACHE_EPHEMERAL_SITES=twitter,instagram,tiktok,facebook,reddit,twitch,generic +# How long link metadata is remembered, so cards for known links are instant. +CACHE_META_TTL=30m +# Make lower qualities and audio from a stored copy with ffmpeg instead of +# downloading again. +CACHE_DERIVE=true +CACHE_SWEEP_INTERVAL=10m + # --- Free tier limits ------------------------------------------------------- FREE_MAX_SIZE_MB=50 FREE_MAX_DURATION=10m @@ -73,6 +92,8 @@ FREE_ACTIVE_JOBS=1 # Per UTC day. 0 means no cap. FREE_DAILY_DOWNLOADS=5 FREE_DAILY_MB=250 +# Items fetched from one playlist link. +FREE_PLAYLIST_ITEMS=3 # --- Paid limits (passes, credits, one-off payments) ------------------------ # Sizes above TELEGRAM_MAX_UPLOAD_MB need a local Bot API server. @@ -82,6 +103,7 @@ PAID_ACTIVE_JOBS=3 PAID_DAILY_DOWNLOADS=100 # The daily volume cap applies to paying users too. PAID_DAILY_MB=20000 +PAID_PLAYLIST_ITEMS=25 # --- Payments (LNbits) ------------------------------------------------------ # Leave LNBITS_URL and LNBITS_INVOICE_KEY empty to run without payments. diff --git a/README.md b/README.md index c47337c..34ea3ec 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,8 @@ A Telegram bot that downloads video and audio from links, in private chats and in groups. Written in Go on top of yt-dlp. -> Status: Phase 2 of 8 (core bot and payments). The cache, remote workers, -> group settings, the Mini App and more languages follow. See +> Status: Phase 3 of 8 (core bot, payments, cache). Remote workers, group +> settings, the Mini App and more languages follow. See > [docs/ASSUMPTIONS.md](docs/ASSUMPTIONS.md) for the decisions made so far. ## What works today @@ -24,6 +24,11 @@ and in groups. Written in Go on top of yt-dlp. - Money is safe: append-only ledger, idempotent settlement, reconciliation at startup, automatic refunds for failed downloads. - Gift codes, referral rewards and tips. +- A smart cache: repeat downloads are instant, two people asking for the + same video share one download, lower qualities are made from a stored + copy. A cache hit is checked against exactly the same limits as a fresh + download. +- Playlists (each item its own job), subtitles, download history. - Friendly, translated error messages. Raw tool output stays in the logs. ## Quick start @@ -62,7 +67,10 @@ curl localhost:8080/healthz | `/dl ` | Download a video. In groups also works as a reply to a link. | | `/audio ` | Download the audio as MP3 | | `/thumb ` | Send the thumbnail | +| `/subs ` | Pick a subtitle language and get the file | | `/info ` | Show formats and sizes without downloading | +| `/fresh ` | Download again instead of using a saved copy | +| `/history` | Your past downloads, one tap to get them again | | `/queue` | Your downloads in progress | | `/cancel` | Cancel your downloads | | `/account` | Your pass, balance and usage today (private chat) | @@ -73,6 +81,13 @@ curl localhost:8080/healthz | `/referral` | Your invite link and how many joined (private chat) | | `/donate` | Send a tip (private chat) | +Owner commands (private chat, only for the IDs in `OWNER_IDS`): + +| Command | What it does | +| --- | --- | +| `/purge ` | Take a video down: delete its files, block it for good | +| `/cache` | Cache size, hit rate and volume saved | + ### Turning on payments Payments are off until LNbits is configured. You need an LNbits wallet and @@ -137,6 +152,8 @@ internal/bot Telegram handlers, cards, status, delivery internal/service download rules shared by all front ends internal/entitle who pays and which limits apply (pure function) internal/billing wallets, ledger, passes, invoices, LNbits client +internal/cache file_id and stored-copy cache +internal/ffmpeg transcoding from a stored copy internal/sched the job queue internal/worker the download worker internal/ytdlp yt-dlp and ffprobe wrapper diff --git a/config.example.toml b/config.example.toml index e9e44c0..e8200ad 100644 --- a/config.example.toml +++ b/config.example.toml @@ -49,6 +49,7 @@ max_duration = "10m" active_jobs = 1 daily_downloads = 5 # per UTC day, 0 for no cap daily_mb = 250 +playlist_items = 3 # items fetched from one playlist link # Passes, credits and one-off payments all run under these limits. [limits.paid] @@ -57,6 +58,20 @@ max_duration = "3h" active_jobs = 3 daily_downloads = 100 daily_mb = 20000 # applies to paying users too +playlist_items = 25 + +# The cache only makes repeat downloads faster. It never changes limits. +[cache] +enabled = true +budget_mb = 20000 # total size of stored copies, 0 for no cap +ttl = "168h" # default lifetime of a cached result +ttl_stable = "720h" +ttl_ephemeral = "6h" +stable_sites = ["youtube", "vimeo", "archive.org", "soundcloud", "dailymotion", "peertube", "bandcamp"] +ephemeral_sites = ["twitter", "instagram", "tiktok", "facebook", "reddit", "twitch", "generic"] +meta_ttl = "30m" +derive = true # make lower qualities from a stored copy with ffmpeg +sweep_interval = "10m" # Payments. Set the invoice key through LNBITS_INVOICE_KEY in the # environment, not here. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index b248edb..8f171d4 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -37,6 +37,8 @@ phase; sections for later phases say so. | `internal/entitle` | Pure entitlement resolver: what pays, which limits apply. | | `internal/billing` | Wallets, ledger, passes, invoices, settlement, gift codes. | | `internal/billing/lnbits` | LNbits HTTP client. | +| `internal/cache` | file_id and stored-copy cache, TTLs, eviction, takedown. | +| `internal/ffmpeg` | Transcoding lower profiles from a stored copy. | | `internal/links` | URL extraction, validation, redaction. | | `internal/storage` | `Storage` interface and the local disk backend. | | `internal/db` | Schema migrations and queries for SQLite and Postgres. | @@ -220,6 +222,64 @@ by the ledger dedupe key, so every failure path can call it without coordination. The reconcile loop also sweeps for deliveries that ended without a file and were never released. +## The cache + +The cache has three layers, from fastest to most general: + +1. **Telegram `file_id`**, per bot. Sending by `file_id` costs no upload. +2. **A stored copy** in Storage. It is the fallback when a `file_id` stops + working and the source for transcoding lower profiles. +3. **Link metadata**, in memory for 30 minutes, so the card for a link that + was just seen appears without running yt-dlp. + +### One gate + +``` + request + | + resolve: cache key, takedown check, what the cache has + | + admit: size, duration, live, daily quota, daily volume <-- same for all + | + +--+----------------+-----------------+------------------+ + | hit | same result | higher profile | nothing + | | in flight | is stored | + v v v v + job created attach to that derive job download job + as "delivering" job (ffmpeg) (yt-dlp) + | | | | + +-------------------+-----------------+------------------+ + | + charge, count quota (one transaction with the job or the attachment) + | + deliver: by file_id, or upload from the stored copy +``` + +`service.Start` is the only way a file gets to a user, and admission comes +before the fork. This is what "the cache never bypasses limits" means in +code: there is no cache path that skips `admit`. For a hit, `admit` is given +the real size and duration of the cached file. + +### Sharing and per-requester caps + +Jobs carry a `cache_key`. A request for a key that is already queued or +running attaches a second delivery to that job. Every delivery stores its +own `max_size` and `max_duration`, and the file is checked against them +when it is delivered, so sharing never widens anyone's limits. + +### Self-healing + +Delivery tries the `file_id` first. If Telegram rejects it, the bot clears +it, uploads the stored copy and saves the new id. If there is no stored +copy, the entry is dropped and the same job is queued as a fresh download. + +### Sweeper + +Every ten minutes the cache deletes expired entries, evicts stored copies +when over budget (least recently and least often used first, keeping their +`file_id`), and removes stored files that no live job and no cache entry +references. + ## Internationalization Handlers never contain user-facing text. They call `i18n.Bundle` with a diff --git a/docs/ASSUMPTIONS.md b/docs/ASSUMPTIONS.md index ab81368..ea940d8 100644 --- a/docs/ASSUMPTIONS.md +++ b/docs/ASSUMPTIONS.md @@ -262,3 +262,107 @@ Read from the LNbits source at `v0.12.12` (the target) and `v1.7.1` (current). not count as a purchase. - **Telegram Stars** as a second payment method is not built ("optional later" in the brief). + +## Phase 3 + +### Cache key + +- The key is yt-dlp's `extractor` (lower case, without a `:suffix`) plus its + video `id`, plus the profile. Two URLs of the same video share an entry. +- **Fallback is a hash of the URL, not of the content.** The generic + extractor names a file after the end of its URL, so different sites + collide; for it, and whenever an ID is missing, the key is derived from + the normalized URL. A hash of the file would only be known after the + download, too late to find a hit. +- Entries are per bot (`bot_id`), because a Telegram `file_id` only works + for the bot that received it. + +### What a cache hit is, and is not + +- A hit goes through `service.Start` like any request: same entitlement, + same size and duration checks, same daily quota and volume, same active + job limit and queue cap, same price. It then becomes a job that is created + already finished, so only the worker is skipped. +- **A hit is judged by the real file**, not by metadata estimates. A file a + pass holder put in the cache is refused to a free user it is too large + for, even when the metadata gave no size. This can also go the other way: + if an estimate was too high, the cached file is allowed. +- A resend from `/history` is a download like any other and counts. + +### Sharing a download (singleflight) + +- A second requester for a result that is queued or running joins that job. + Each requester keeps their own caps: when the file is finished, it is + checked against each one's limits before it is sent to them. +- **A queued job is lifted** to the looser caps and to the paid lane when a + paying requester joins. A free user who asked first benefits from that. +- **A running job is only joined when it covers the newcomer's caps.** + Otherwise the newcomer gets a job of their own, because the running one + was started with a size cap that could cut their file short. +- Content that is not cacheable is never shared between users. + +### Stored copies + +- A job's stored file becomes the cache's stored copy in place. Nothing is + moved or copied. +- The result enters the cache right after the first successful send, before + the requester sees "Done". +- A download that worked but could not be sent to anyone is still cached. + +### Derive + +- A lower video profile or audio is transcoded from a stored higher profile + when one exists (`CACHE_DERIVE`). The nearest profile above is used. +- **Alias instead of transcode:** when the stored higher profile is already + no taller than the requested cap (a 360p video asked for as "720"), it is + the same file yt-dlp would fetch and is served as a plain hit. +- A derive job that fails becomes a normal download of that profile, at no + cost in attempts. +- Transcoding is h264 `veryfast` CRF 23 with AAC 128k, MP3 at 192k. + +### Self-healing + +- When Telegram refuses a cached `file_id`: the id is cleared, the stored + copy is uploaded again and the new id is saved. Without a usable stored + copy the entry is dropped and the job goes to the queue as a fresh + download. The requester was admitted and charged once and stays so. + +### Eviction and TTL + +- TTL by extractor: stable sites 30 days, ephemeral ones 6 hours, the rest + 7 days. The lists are configurable prefixes of extractor names. +- Over budget, stored copies are evicted in order of + `last_hit + min(hits, 48) hours`: each hit protects an entry like one more + hour of recency, up to two days. +- **Eviction removes the stored copy and keeps the file_id.** The entry + still serves instant resends; it just cannot heal or be transcoded. +- Never cached: live streams, and anything whose yt-dlp `availability` is + not public or unlisted (private, members-only, needs a login). The bot has + no cookie support yet, so "downloads that needed cookies" cannot occur; + the availability check is what will cover them. + +### Takedown + +- `/purge ` or `/purge extractor:id` deletes the stored files of + every profile of the video, clears their file_ids, marks the entries + blocked and adds the key to the blocklist. A blocked key is refused before + any download and can never be cached again. Takedown markers have no TTL. +- The site blocklist also covers subdomains. + +### Playlists + +- A playlist link shows a card with the item count and the formats. Each + item becomes its own request, job and cache entry. +- **Items start one after another** as the requester's active job slots + free up, instead of all at once. The per-user active job limit therefore + holds for playlists too, and one long playlist cannot fill the queue. +- The per-request cap is by tier: 3 items free, 25 paid. Each item counts + against the daily quota. +- `/cancel` also cancels items that have not started. +- An item that is itself a list is skipped. + +### Subtitles and history + +- `/subs` lists written subtitles before automatic captions, with the + requester's language first and marked. At most 24 languages are shown. +- `/history` shows the last 10 delivered files. diff --git a/internal/app/app.go b/internal/app/app.go index 0c49f6b..3403414 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -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) }) } diff --git a/internal/app/app_test.go b/internal/app/app_test.go index 2fe9519..a454a22 100644 --- a/internal/app/app_test.go +++ b/internal/app/app_test.go @@ -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 { diff --git a/internal/app/cache_test.go b/internal/app/cache_test.go new file mode 100644 index 0000000..7336231 --- /dev/null +++ b/internal/app/cache_test.go @@ -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) + } +} diff --git a/internal/app/money_test.go b/internal/app/money_test.go index 00a435d..27723c7 100644 --- a/internal/app/money_test.go +++ b/internal/app/money_test.go @@ -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")) } diff --git a/internal/bot/bot.go b/internal/bot/bot.go index 996b88a..a9c30b1 100644 --- a/internal/bot/bot.go +++ b/internal/bot/bot.go @@ -14,6 +14,7 @@ import ( "github.com/mymmrac/telego" "github.com/noderunners/dlbot/internal/billing" + "github.com/noderunners/dlbot/internal/cache" "github.com/noderunners/dlbot/internal/config" "github.com/noderunners/dlbot/internal/db" "github.com/noderunners/dlbot/internal/i18n" @@ -33,6 +34,7 @@ type Deps struct { Billing *billing.Billing // Cashu redeems ecash tokens. Nil turns that part of /redeem off. Cashu billing.Cashu + Cache *cache.Cache Storage storage.Storage I18n *i18n.Bundle Log *slog.Logger @@ -50,6 +52,7 @@ type Bot struct { svc *service.Service bill *billing.Billing cashu billing.Cashu + cache *cache.Cache storage storage.Storage tr *i18n.Bundle log *slog.Logger @@ -60,6 +63,7 @@ type Bot struct { events chan sched.Event payEvents chan billing.Event uploads chan struct{} // limits concurrent uploads to Telegram + pump chan struct{} // wakes the playlist pump rate *rateLimiter bg sync.WaitGroup baseCtx context.Context @@ -67,6 +71,7 @@ type Bot struct { statusMu sync.Mutex statuses map[string]*statusState // by delivery ID sending map[string]bool // jobs being delivered right now + pumping map[int64]bool // users whose next playlist item is being started // Tunables, shortened in tests. reconcileEvery time.Duration @@ -97,6 +102,7 @@ func New(ctx context.Context, d Deps) (*Bot, error) { svc: d.Service, bill: d.Billing, cashu: d.Cashu, + cache: d.Cache, storage: d.Storage, tr: d.I18n, log: d.Log, @@ -106,10 +112,12 @@ func New(ctx context.Context, d Deps) (*Bot, error) { events: make(chan sched.Event, 1024), payEvents: make(chan billing.Event, 256), uploads: make(chan struct{}, 4), + pump: make(chan struct{}, 1), rate: newRateLimiter(), baseCtx: ctx, statuses: map[string]*statusState{}, sending: map[string]bool{}, + pumping: map[int64]bool{}, reconcileEvery: 5 * time.Second, statusMinGap: 3 * time.Second, invoiceGrace: 5 * time.Second, diff --git a/internal/bot/card.go b/internal/bot/card.go index a1a936c..e8db005 100644 --- a/internal/bot/card.go +++ b/internal/bot/card.go @@ -32,6 +32,10 @@ type linkRequest struct { url string // preset skips the card and starts this profile right away. preset media.Profile + // fresh skips the cache and downloads again. + fresh bool + // subs shows the subtitle languages instead of the format buttons. + subs bool } // startLink runs the link flow in the background so a slow metadata lookup @@ -60,13 +64,23 @@ func (b *Bot) linkFlow(ctx context.Context, lr linkRequest) { } phID := int64(placeholder.MessageID) - info, err := b.svc.Probe(ctx, lr.url) + probed, err := b.svc.ProbeAny(ctx, lr.url) if err != nil { if ctx.Err() == nil { _ = b.edit(ctx, lr.chatID, phID, false, b.probeErrorText(lang, err), nil) } return } + if probed.Playlist != nil { + b.playlistCard(ctx, lr, phID, probed.Playlist) + return + } + info := probed.Info + if lr.fresh { + cp := *info + cp.Fresh = true + info = &cp + } req := &db.Request{ ID: ids.New(), @@ -103,6 +117,11 @@ func (b *Bot) linkFlow(ctx context.Context, lr linkRequest) { return } + if lr.subs { + b.subsCard(ctx, lr, phID, req, info) + return + } + text := b.cardText(lang, info, true) kb := b.cardKeyboard(lang, req.ID, info) if info.Thumbnail != "" { diff --git a/internal/bot/commands.go b/internal/bot/commands.go index d860fd3..feba7de 100644 --- a/internal/bot/commands.go +++ b/internal/bot/commands.go @@ -48,6 +48,20 @@ func (b *Bot) handleMessage(ctx context.Context, m *telego.Message) { b.cmdDownload(ctx, m, act, media.MP3) case "thumb": b.cmdDownload(ctx, m, act, media.Thumb) + case "fresh": + b.cmdLink(ctx, m, act, linkRequest{fresh: true}) + case "subs": + b.cmdLink(ctx, m, act, linkRequest{subs: true}) + case "history": + b.cmdHistory(ctx, m, act) + case "purge": + if b.isOwner(m) { + b.cmdPurge(ctx, m, act) + } + case "cache": + if b.isOwner(m) { + b.cmdCache(ctx, m, act) + } case "info": b.cmdInfo(ctx, m, act) case "queue": @@ -202,6 +216,23 @@ func (b *Bot) cmdDownload(ctx context.Context, m *telego.Message, act actor, pre }) } +// cmdLink handles the commands that take a link and differ only in how +// the link flow runs: /fresh and /subs. +func (b *Bot) cmdLink(ctx context.Context, m *telego.Message, act actor, lr linkRequest) { + urls := messageLinks(m) + source := int64(m.MessageID) + if len(urls) == 0 && m.ReplyToMessage != nil { + urls = messageLinks(m.ReplyToMessage) + source = int64(m.ReplyToMessage.MessageID) + } + if len(urls) == 0 { + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "dl.usage", nil), nil) + return + } + lr.chatID, lr.chatType, lr.sourceID, lr.act, lr.url = m.Chat.ID, m.Chat.Type, source, act, urls[0] + b.startLink(ctx, lr) +} + func (b *Bot) cmdInfo(ctx context.Context, m *telego.Message, act actor) { urls := messageLinks(m) if len(urls) == 0 && m.ReplyToMessage != nil { @@ -277,6 +308,10 @@ func (b *Bot) cmdCancel(ctx context.Context, m *telego.Message, act actor) { n++ } } + // Playlist items that have not started yet are cancelled too. + if waiting, err := b.store.CancelWaitingRequests(ctx, act.user.ID); err == nil { + n += int(waiting) + } key := "cancel.done" if n == 0 { key = "cancel.nothing" @@ -329,6 +364,10 @@ func (b *Bot) handleCallback(ctx context.Context, q *telego.CallbackQuery) { b.cbDownload(ctx, q, act, id, arg) case cbCancelCard: b.cbCancelCard(ctx, q, act, id) + case cbPlaylist: + b.cbPlaylistStart(ctx, q, act, id, arg) + case cbResend: + b.cbResendFile(ctx, q, act, id) case cbSkipQueue: b.cbSkip(ctx, q, act, id) case cbBuy: diff --git a/internal/bot/deliver.go b/internal/bot/deliver.go index 638115c..0e8ad44 100644 --- a/internal/bot/deliver.go +++ b/internal/bot/deliver.go @@ -62,40 +62,63 @@ func (b *Bot) deliverJob(ctx context.Context, jobID string) { b.log.Error("list deliveries", "job_id", jobID, "err", err) return } - // The first upload yields a file_id that later requesters reuse, so the - // file crosses the wire once. - var fileID string + // A cache hit starts with a file_id. Otherwise the first upload yields + // one that later requesters reuse, so the file crosses the wire once. for _, d := range dels { if ctx.Err() != nil { return } - if id := b.deliverOne(ctx, job, d, fileID); id != "" { - fileID = id + if stop := b.deliverOne(ctx, job, d); stop { + return // the job went back to the queue for a fresh download } } b.finishIfServed(ctx, job) } -// deliverOne sends the file to one requester and returns the Telegram -// file_id on success. -func (b *Bot) deliverOne(ctx context.Context, job *db.Job, d *db.Delivery, reuseFileID string) string { +// sentFile describes a file Telegram accepted. +type sentFile struct { + ID string + UniqueID string + MessageID int64 +} + +// deliverOne sends the file to one requester. It updates job.TgFileID +// when an upload produced a file_id. stop is true when the cached file +// turned out to be unusable and the job was queued for a fresh download. +func (b *Bot) deliverOne(ctx context.Context, job *db.Job, d *db.Delivery) (stop bool) { log := b.log.With("job_id", job.ID, "delivery_id", d.ID, "chat_id", d.ChatID) took, err := b.store.TransitionDelivery(ctx, d.ID, db.DeliveryPending, db.DeliverySending, "") if err != nil || !took { - return "" + return false } + saveCtx := context.WithoutCancel(ctx) + + // Requesters who share a job keep their own caps. The file somebody + // with a pass asked for can be too big for a free user waiting on the + // same job; that user is refused here, like on a download of their own. + if code := overCap(job, d); code != "" { + _, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryFailed, code) + b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, code)+b.release(ctx, d)) + return false + } + text, _, _ := b.renderStatus(ctx, d, job) b.setStatus(ctx, d, text, nil, "uploading", true) sendCtx, cancel := context.WithTimeout(ctx, uploadTimeout) defer cancel() stopAction := b.keepChatAction(sendCtx, d.ChatID, uploadAction(job)) - fileID, messageID, err := b.sendFile(sendCtx, job, d, reuseFileID) + sent, err := b.sendFile(sendCtx, job, d, job.TgFileID) + if err != nil && job.TgFileID != "" && tg.IsBadFileID(err) { + sent, err, stop = b.heal(sendCtx, job, d, err) + } stopAction() + if stop { + _, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryPending, "") + return true + } if err != nil { - // Status changes must be saved even when we are shutting down. - saveCtx := context.WithoutCancel(ctx) switch { case ctx.Err() != nil: // Shutdown interrupted the upload. Leave it for the next start. @@ -119,17 +142,90 @@ func (b *Bot) deliverOne(ctx context.Context, job *db.Job, d *db.Delivery, reuse _, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryFailed, "send_failed") b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, "send_failed")+b.release(ctx, d)) } - return "" + return false } - if err := b.store.MarkDeliverySent(context.WithoutCancel(ctx), d.ID, fileID, messageID); err != nil { + if sent.ID != "" && sent.ID != job.TgFileID { + job.TgFileID = sent.ID + if err := b.store.SetJobFileID(saveCtx, job.ID, sent.ID); err != nil { + log.Error("save file id", "err", err) + } + // The result enters the cache as soon as it exists, before the + // requester is told "done". The next request for it, even one that + // arrives in this instant, is then a cache hit. + b.cacheResult(saveCtx, job, sent.UniqueID) + } + if err := b.store.MarkDeliverySent(saveCtx, d.ID, sent.ID, sent.MessageID); err != nil { log.Error("mark delivery sent", "err", err) } - if err := b.svc.RecordDelivered(context.WithoutCancel(ctx), d, job.FileSize); err != nil { + if err := b.svc.RecordDelivered(saveCtx, d, job.FileSize); err != nil { log.Error("record usage", "err", err) } - log.Info("file delivered", "size", job.FileSize, "profile", job.Profile) + log.Info("file delivered", "size", job.FileSize, "profile", job.Profile, "cache_hit", job.CacheHit) b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.done", nil)) - return fileID + return false +} + +// overCap checks a finished file against one requester's own caps. +func overCap(job *db.Job, d *db.Delivery) string { + kind := jobProfile(job).Kind() + if kind == media.KindThumb || kind == media.KindSubs { + return "" + } + if d.MaxSize > 0 && job.FileSize > d.MaxSize { + return "too_large" + } + if d.MaxDuration > 0 && job.Duration > d.MaxDuration+1 { + return "too_long" + } + return "" +} + +// heal is the cache repairing itself after Telegram refused a file_id. +// The file_id layer is dropped first. Then the stored copy is uploaded +// again, which yields a fresh file_id that is written back to the entry. +// Without a usable stored copy the job is queued for a fresh download and +// stop is true. Either way the requester gets the file, and the entry is +// correct for the next one. +func (b *Bot) heal(ctx context.Context, job *db.Job, d *db.Delivery, cause error) (sent sentFile, err error, stop bool) { + log := b.log.With("job_id", job.ID, "extractor", job.Extractor, "video_id", job.VideoID, "profile", job.Profile) + log.Warn("cached file_id rejected, healing", "err", cause) + bg := context.WithoutCancel(ctx) + // The entry to repair is the one this job was served from, which for + // an alias hit is a higher profile than the job's own. + entry := b.cache.ProfileServing(bg, job) + if err := b.cache.SetFileID(bg, job.Extractor, job.VideoID, entry, "", ""); err != nil { + log.Error("clear cached file id", "err", err) + } + job.TgFileID = "" + _ = b.store.SetJobFileID(bg, job.ID, "") + + if job.StorageKey != "" { + if _, serr := b.storage.Stat(ctx, job.StorageKey); serr == nil { + sent, err = b.sendFile(ctx, job, d, "") + if err == nil { + if cerr := b.cache.SetFileID(bg, job.Extractor, job.VideoID, entry, sent.ID, sent.UniqueID); cerr != nil { + log.Error("save healed file id", "err", cerr) + } + log.Info("healed from the stored copy") + } + return sent, err, false + } + // The entry points at a file that is gone. + if derr := b.cache.DropStored(bg, job.Extractor, job.VideoID, entry); derr != nil { + log.Error("drop missing stored copy", "err", derr) + } + } + // Nothing left to serve from: forget the entry and download again. The + // request was already admitted and charged, so this costs nothing more. + if ferr := b.cache.Forget(bg, job.Extractor, job.VideoID, entry); ferr != nil { + log.Error("forget cache entry", "err", ferr) + } + requeued, rerr := b.sched.Redownload(bg, job.ID) + if rerr != nil || !requeued { + return sentFile{}, cause, false + } + log.Info("no stored copy, downloading again") + return sentFile{}, nil, true } // streamable lists the containers Telegram plays inline as video. @@ -179,7 +275,7 @@ func (b *Bot) keepChatAction(ctx context.Context, chat int64, action string) (st // sendFile uploads the stored file, or resends by file_id when one is // known. A video or photo that Telegram rejects is sent again as a plain // document, which accepts any content. -func (b *Bot) sendFile(ctx context.Context, job *db.Job, d *db.Delivery, reuseFileID string) (fileID string, messageID int64, err error) { +func (b *Bot) sendFile(ctx context.Context, job *db.Job, d *db.Delivery, reuseFileID string) (sentFile, error) { kind := jobProfile(job).Kind() mode := "document" switch { @@ -190,28 +286,28 @@ func (b *Bot) sendFile(ctx context.Context, job *db.Job, d *db.Delivery, reuseFi case kind == media.KindThumb: mode = "photo" } - fileID, messageID, err = b.sendAs(ctx, mode, job, d, reuseFileID) + sent, err := b.sendAs(ctx, mode, job, d, reuseFileID) if err != nil && mode != "document" && reuseFileID == "" && tg.ErrorCode(err) == 400 && !tg.IsBlocked(err) { b.log.Info("media rejected, sending as document", "job_id", job.ID, "mode", mode, "err", err) return b.sendAs(ctx, "document", job, d, "") } - return fileID, messageID, err + return sent, err } -func (b *Bot) sendAs(ctx context.Context, mode string, job *db.Job, d *db.Delivery, reuseFileID string) (string, int64, error) { +func (b *Bot) sendAs(ctx context.Context, mode string, job *db.Job, d *db.Delivery, reuseFileID string) (sentFile, error) { var input telego.InputFile if reuseFileID != "" { input = telego.InputFile{FileID: reuseFileID} } else { if job.StorageKey == "" { - return "", 0, errors.New("bot: job has no stored file") + return sentFile{}, errors.New("bot: job has no stored file") } rc, _, err := b.storage.Open(ctx, job.StorageKey) if err != nil { if errors.Is(err, storage.ErrNotFound) { - return "", 0, errors.New("bot: stored file is missing") + return sentFile{}, errors.New("bot: stored file is missing") } - return "", 0, err + return sentFile{}, err } defer rc.Close() input = telego.InputFile{File: namedReader{Reader: rc, name: fileName(job.Title, job.FileExt)}} @@ -228,66 +324,97 @@ func (b *Bot) sendAs(ctx context.Context, mode string, job *db.Job, d *db.Delive SupportsStreaming: true, ReplyParameters: reply, }) if err != nil { - return "", 0, err + return sentFile{}, err } if msg.Video != nil { - return msg.Video.FileID, int64(msg.MessageID), nil + return sentFile{msg.Video.FileID, msg.Video.FileUniqueID, int64(msg.MessageID)}, nil } if msg.Document != nil { // Telegram may store odd videos as documents - return msg.Document.FileID, int64(msg.MessageID), nil + return sentFile{msg.Document.FileID, msg.Document.FileUniqueID, int64(msg.MessageID)}, nil } - return "", int64(msg.MessageID), nil + return sentFile{MessageID: int64(msg.MessageID)}, nil case "audio": msg, err := b.api.SendAudio(ctx, &telego.SendAudioParams{ ChatID: chat, Audio: input, Title: shorten(job.Title, 120), Performer: shorten(job.Uploader, 60), Duration: int(job.Duration), ReplyParameters: reply, }) if err != nil { - return "", 0, err + return sentFile{}, err } if msg.Audio != nil { - return msg.Audio.FileID, int64(msg.MessageID), nil + return sentFile{msg.Audio.FileID, msg.Audio.FileUniqueID, int64(msg.MessageID)}, nil } - return "", int64(msg.MessageID), nil + return sentFile{MessageID: int64(msg.MessageID)}, nil case "photo": msg, err := b.api.SendPhoto(ctx, &telego.SendPhotoParams{ ChatID: chat, Photo: input, Caption: caption, ParseMode: telego.ModeHTML, ReplyParameters: reply, }) if err != nil { - return "", 0, err + return sentFile{}, err } if n := len(msg.Photo); n > 0 { - return msg.Photo[n-1].FileID, int64(msg.MessageID), nil + return sentFile{msg.Photo[n-1].FileID, msg.Photo[n-1].FileUniqueID, int64(msg.MessageID)}, nil } - return "", int64(msg.MessageID), nil + return sentFile{MessageID: int64(msg.MessageID)}, nil default: msg, err := b.api.SendDocument(ctx, &telego.SendDocumentParams{ ChatID: chat, Document: input, Caption: caption, ParseMode: telego.ModeHTML, ReplyParameters: reply, }) if err != nil { - return "", 0, err + return sentFile{}, err } if msg.Document != nil { - return msg.Document.FileID, int64(msg.MessageID), nil + return sentFile{msg.Document.FileID, msg.Document.FileUniqueID, int64(msg.MessageID)}, nil } - return "", int64(msg.MessageID), nil + return sentFile{MessageID: int64(msg.MessageID)}, nil } } // finishIfServed closes a delivering job once nobody waits for it, and -// removes the stored file. Until the cache exists a file has no use after -// it reached Telegram. +// decides what happens to the stored file: it enters the cache when the +// result is cacheable, and is deleted otherwise. func (b *Bot) finishIfServed(ctx context.Context, job *db.Job) { ctx = context.WithoutCancel(ctx) left, err := b.store.CountDeliveriesInStatus(ctx, job.ID, db.DeliveryPending, db.DeliverySending) if err != nil || left > 0 { return } - if err := b.sched.FinishDelivered(ctx, job.ID); err != nil { - b.log.Error("finish job", "job_id", job.ID, "err", err) + cur, err := b.store.GetJob(ctx, job.ID) + if err != nil || cur.Status != db.JobDelivering { return } - b.removeStored(ctx, job) + if err := b.sched.FinishDelivered(ctx, cur.ID); err != nil { + b.log.Error("finish job", "job_id", cur.ID, "err", err) + return + } + b.pumpSoon() + if cur.CacheHit { + return // the file belongs to the cache entry it was served from + } + // Usually the result was cached at the first successful send. When no + // send succeeded (everyone cancelled or was unreachable) the download + // itself still worked, so the file is kept for the next request. + if b.cacheResult(ctx, cur, "") { + return + } + b.removeStored(ctx, cur) +} + +// cacheResult puts a finished job's file in the cache and reports whether +// the cache now owns that file. It is safe to call more than once. +func (b *Bot) cacheResult(ctx context.Context, job *db.Job, uniqueID string) bool { + if job.CacheHit || !job.Cacheable || !b.cache.Enabled() || job.StorageKey == "" { + return false + } + if e, err := b.cache.Lookup(ctx, job.Extractor, job.VideoID, jobProfile(job)); err == nil && e != nil && + e.StorageKey == job.StorageKey && (e.TgFileID != "" || job.TgFileID == "") { + return true // already in, with everything this job knows + } + if err := b.cache.Put(ctx, job, job.TgFileID, uniqueID); err != nil { + b.log.Debug("result not cached", "job_id", job.ID, "err", err) + return false + } + return true } func (b *Bot) removeStored(ctx context.Context, job *db.Job) { diff --git a/internal/bot/extras.go b/internal/bot/extras.go new file mode 100644 index 0000000..4209f61 --- /dev/null +++ b/internal/bot/extras.go @@ -0,0 +1,453 @@ +package bot + +import ( + "context" + "errors" + "html" + "strconv" + "strings" + "time" + + "github.com/mymmrac/telego" + + "github.com/noderunners/dlbot/internal/cache" + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/i18n" + "github.com/noderunners/dlbot/internal/ids" + "github.com/noderunners/dlbot/internal/media" + "github.com/noderunners/dlbot/internal/service" +) + +const ( + cbPlaylist = "pl" // pl:: + cbResend = "rs" // rs: +) + +// --- playlists --------------------------------------------------------------- + +// playlistCard shows a playlist link: how many items it has, how many of +// them this requester's limits allow, and the format buttons. +func (b *Bot) playlistCard(ctx context.Context, lr linkRequest, messageID int64, pl *service.Playlist) { + lang := lr.act.lang + if len(pl.Entries) == 0 { + _ = b.edit(ctx, lr.chatID, messageID, false, b.tr.HTML(lang, "playlist.empty", nil), nil) + return + } + dec, err := b.svc.Entitlement(ctx, service.Who{UserID: lr.act.user.ID, ChatID: lr.chatID, ChatType: lr.chatType}, false) + if err != nil { + _ = b.edit(ctx, lr.chatID, messageID, false, b.tr.HTML(lang, "error.internal", nil), nil) + return + } + take := playlistTake(len(pl.Entries), dec.Limits.PlaylistItems) + req := &db.Request{ + ID: ids.New(), UserID: lr.act.user.ID, ChatID: lr.chatID, ChatType: lr.chatType, + SourceMessageID: lr.sourceID, CardMessageID: messageID, URL: lr.url, + Status: db.RequestReady, Info: pl.JSON(), Lang: lang, + } + if err := b.store.InsertRequest(ctx, req); err != nil { + b.log.Error("insert playlist request", "err", err) + _ = b.edit(ctx, lr.chatID, messageID, false, b.tr.HTML(lang, "error.internal", nil), nil) + return + } + text := b.tr.HTML(lang, "playlist.card", i18n.Args{ + "Title": shorten(pl.Title, 120), "Count": len(pl.Entries), "Take": take, + }) + var row []telego.InlineKeyboardButton + for _, p := range []media.Profile{media.Best, media.P720, media.P480, media.MP3} { + row = append(row, button(b.profileLabel(lang, p), cbData(cbPlaylist, req.ID, string(p)))) + } + kb := keyboard(row, []telego.InlineKeyboardButton{button(b.tr.T(lang, "btn.cancel", nil), cbData(cbCancelCard, req.ID))}) + _ = b.edit(ctx, lr.chatID, messageID, false, text, kb) +} + +func playlistTake(entries, cap int) int { + if cap > 0 && entries > cap { + return cap + } + return entries +} + +// cbPlaylistStart turns the chosen playlist into waiting items. Each item +// becomes its own request, job and cache entry, and they start one after +// another as the requester's job slots free up. +func (b *Bot) cbPlaylistStart(ctx context.Context, q *telego.CallbackQuery, act actor, requestID, profileArg string) { + req, err := b.store.GetRequest(ctx, requestID) + if err != nil { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + if req.UserID != act.user.ID { + b.answer(ctx, q, b.tr.T(act.lang, "notice.not_yours", nil), false) + return + } + profile, perr := media.Parse(profileArg) + pl, plerr := service.ParsePlaylist(req.Info) + if perr != nil || plerr != nil || len(pl.Entries) == 0 { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + dec, err := b.svc.Entitlement(ctx, service.Who{UserID: req.UserID, ChatID: req.ChatID, ChatType: req.ChatType}, false) + if err != nil { + b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true) + return + } + took, err := b.store.TransitionRequest(ctx, req.ID, db.RequestReady, db.RequestChosen) + if err != nil || !took { + b.answer(ctx, q, b.tr.T(act.lang, "notice.already_chosen", nil), false) + return + } + take := playlistTake(len(pl.Entries), dec.Limits.PlaylistItems) + base := time.Now() + for i, e := range pl.Entries[:take] { + item := &db.Request{ + // Increasing timestamps keep the items in playlist order. + ID: ids.NewAt(base.Add(time.Duration(i) * time.Millisecond)), + UserID: req.UserID, ChatID: req.ChatID, ChatType: req.ChatType, + SourceMessageID: req.SourceMessageID, URL: e.URL, Status: db.RequestWaiting, + Lang: req.Lang, ParentID: req.ID, Profile: string(profile), + } + if err := b.store.InsertRequest(ctx, item); err != nil { + b.log.Error("insert playlist item", "err", err) + } + } + b.answer(ctx, q, "", false) + cardID, isPhoto := cardMessage(q, req) + _ = b.edit(ctx, req.ChatID, cardID, isPhoto, b.tr.HTML(req.Lang, "playlist.queued", i18n.Args{ + "Title": shorten(pl.Title, 120), "Count": take, + }), nil) + b.pumpSoon() +} + +// pumpSoon asks the event loop to look for playlist items that can start. +func (b *Bot) pumpSoon() { + select { + case b.pump <- struct{}{}: + default: + } +} + +// pumpPlaylists starts waiting playlist items for users who have a free +// job slot. It looks at one item per user, so one long playlist cannot +// hold up others. +func (b *Bot) pumpPlaylists(ctx context.Context) { + if ctx.Err() != nil { + return + } + items, err := b.store.WaitingRequests(ctx, 50) + if err != nil { + b.log.Error("list waiting playlist items", "err", err) + return + } + for _, item := range items { + b.statusMu.Lock() + busy := b.pumping[item.UserID] + if !busy { + b.pumping[item.UserID] = true + } + b.statusMu.Unlock() + if busy { + continue + } + item := item + b.goBG("playlist-item", func() { + defer func() { + b.statusMu.Lock() + delete(b.pumping, item.UserID) + b.statusMu.Unlock() + }() + if b.startPlaylistItem(ctx, item) { + b.pumpSoon() // maybe the next one fits too + } + }) + } +} + +// startPlaylistItem tries to start one item. It reports whether the item +// left the waiting state, in which case the next one may be tried. +func (b *Bot) startPlaylistItem(ctx context.Context, item *db.Request) bool { + who := service.Who{UserID: item.UserID, ChatID: item.ChatID, ChatType: item.ChatType} + dec, err := b.svc.Entitlement(ctx, who, false) + if err != nil { + return false + } + if dec.Limits.ActiveJobs > 0 { + n, err := b.store.CountActiveDeliveries(ctx, item.UserID) + if err != nil || n >= dec.Limits.ActiveJobs { + return false // no free slot yet: stay in line + } + } + took, err := b.store.TransitionRequest(ctx, item.ID, db.RequestWaiting, db.RequestChosen) + if err != nil || !took { + return false + } + lang := item.Lang + fail := func(title, reason string) bool { + if _, err := b.store.TransitionRequest(context.WithoutCancel(ctx), item.ID, db.RequestChosen, db.RequestFailed); err != nil { + b.log.Error("fail playlist item", "err", err) + } + _, _ = b.send(ctx, item.ChatID, item.SourceMessageID, b.tr.HTML(lang, "playlist.item_failed", i18n.Args{ + "Title": shorten(title, 80), "Reason": reason, + }), nil) + return true + } + profile, perr := media.Parse(item.Profile) + probed, err := b.svc.ProbeAny(ctx, item.URL) + switch { + case ctx.Err() != nil: + // Shutting down: put it back for the next start. + _, _ = b.store.TransitionRequest(context.WithoutCancel(ctx), item.ID, db.RequestChosen, db.RequestWaiting) + return false + case perr != nil: + return fail(item.URL, b.tr.T(lang, "error.internal", nil)) + case err != nil: + return fail(item.URL, html.UnescapeString(b.probeErrorText(lang, err))) + case probed.Info == nil: + return fail(item.URL, b.tr.T(lang, "error.playlist_nested", nil)) + } + info := probed.Info + if err := b.store.SetRequestInfo(ctx, item.ID, info.JSON()); err != nil { + b.log.Error("save playlist item info", "err", err) + } + item.Info = info.JSON() + msg, err := b.send(ctx, item.ChatID, item.SourceMessageID, titleLine(info.Title)+"\n"+b.tr.HTML(lang, "status.preparing", nil), nil) + if err != nil { + return fail(info.Title, b.tr.T(lang, "error.internal", nil)) + } + job, _, err := b.svc.Start(ctx, service.StartParams{ + Request: item, Info: info, Profile: profile, + StatusMessageID: int64(msg.MessageID), ReplyToMessageID: item.SourceMessageID, + }) + if err != nil { + var le *service.LimitError + if errors.As(err, &le) && le.Code == service.LimitActiveJobs { + // Lost the slot to another download: wait for the next one. + b.deleteMessage(ctx, item.ChatID, int64(msg.MessageID)) + _, _ = b.store.TransitionRequest(context.WithoutCancel(ctx), item.ID, db.RequestChosen, db.RequestWaiting) + return false + } + _, _ = b.store.TransitionRequest(context.WithoutCancel(ctx), item.ID, db.RequestChosen, db.RequestFailed) + _ = b.edit(ctx, item.ChatID, int64(msg.MessageID), false, + titleLine(info.Title)+"\n"+html.EscapeString(b.startErrorText(lang, err)), nil) + return true + } + b.refreshStatus(ctx, job.ID) + return true +} + +// --- subtitles --------------------------------------------------------------- + +// subsCard lists the subtitle languages of a video as buttons, with the +// requester's own language first. +func (b *Bot) subsCard(ctx context.Context, lr linkRequest, messageID int64, req *db.Request, info *service.CardInfo) { + lang := lr.act.lang + type entry struct { + code string + auto bool + } + var all []entry + for _, c := range info.SubLangs { + all = append(all, entry{c, false}) + } + for _, c := range info.AutoSubLangs { + all = append(all, entry{c, true}) + } + if len(all) == 0 { + _ = b.edit(ctx, lr.chatID, messageID, false, titleLine(info.Title)+"\n"+b.tr.HTML(lang, "subs.none", nil), nil) + return + } + // The requester's language goes first, written before automatic. + mine := strings.ToLower(strings.SplitN(lang, "-", 2)[0]) + isMine := func(code string) bool { + return strings.ToLower(strings.SplitN(code, "-", 2)[0]) == mine + } + var first, rest []entry + for _, e := range all { + if isMine(e.code) { + first = append(first, e) + } else { + rest = append(rest, e) + } + } + ordered := append(first, rest...) + const maxLangs = 24 + if len(ordered) > maxLangs { + ordered = ordered[:maxLangs] + } + var rows [][]telego.InlineKeyboardButton + var row []telego.InlineKeyboardButton + for _, e := range ordered { + p := media.Subs(e.code) + if _, err := media.Parse(string(p)); err != nil { + continue // a language code that is not safe to pass on + } + label := e.code + if e.auto { + label = b.tr.T(lang, "btn.subs_auto", i18n.Args{"Lang": e.code}) + } + if isMine(e.code) { + label = "✓ " + label + } + row = append(row, button(label, cbData(cbDownload, req.ID, string(p)))) + if len(row) == 3 { + rows = append(rows, row) + row = nil + } + } + rows = append(rows, row, []telego.InlineKeyboardButton{button(b.tr.T(lang, "btn.cancel", nil), cbData(cbCancelCard, req.ID))}) + _ = b.edit(ctx, lr.chatID, messageID, false, titleLine(info.Title)+"\n"+b.tr.HTML(lang, "subs.pick", nil), keyboard(rows...)) +} + +// --- history ----------------------------------------------------------------- + +func (b *Bot) cmdHistory(ctx context.Context, m *telego.Message, act actor) { + lang := act.lang + dels, err := b.store.History(ctx, act.user.ID, 10) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + if len(dels) == 0 { + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(lang, "history.empty", nil), nil) + return + } + var sb strings.Builder + sb.WriteString(b.tr.HTML(lang, "history.header", nil)) + var rows [][]telego.InlineKeyboardButton + n := 0 + for _, d := range dels { + job, err := b.store.GetJob(ctx, d.JobID) + if err != nil { + continue + } + n++ + label := b.profileLabel(lang, jobProfile(job)) + sb.WriteString("\n") + sb.WriteString(b.tr.HTML(lang, "history.line", i18n.Args{"N": n, "Title": shorten(job.Title, 60), "Label": label})) + rows = append(rows, []telego.InlineKeyboardButton{ + button(b.tr.T(lang, "btn.resend", i18n.Args{"N": n, "Title": shorten(job.Title, 28)}), cbData(cbResend, d.ID)), + }) + } + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), sb.String(), keyboard(rows...)) +} + +// cbResendFile sends a past download again. It is a new request like any +// other: same limits, same quota, same price. The cache usually makes it +// instant. +func (b *Bot) cbResendFile(ctx context.Context, q *telego.CallbackQuery, act actor, deliveryID string) { + lang := act.lang + old, err := b.store.GetDelivery(ctx, deliveryID) + if err != nil || old.UserID != act.user.ID { + b.answer(ctx, q, b.tr.T(lang, "notice.expired", nil), false) + return + } + job, jerr := b.store.GetJob(ctx, old.JobID) + orig, rerr := b.store.GetRequest(ctx, old.RequestID) + if jerr != nil || rerr != nil { + b.answer(ctx, q, b.tr.T(lang, "notice.expired", nil), false) + return + } + info, ierr := service.ParseCardInfo(orig.Info) + profile, perr := media.Parse(job.Profile) + if ierr != nil || perr != nil { + b.answer(ctx, q, b.tr.T(lang, "notice.expired", nil), false) + return + } + chat, chatType := act.user.ID, telego.ChatTypePrivate + if q.Message != nil { + chat, chatType = q.Message.GetChat().ID, q.Message.GetChat().Type + } + b.answer(ctx, q, "", false) + info.Fresh = false + req := &db.Request{ + ID: ids.New(), UserID: act.user.ID, ChatID: chat, ChatType: chatType, URL: orig.URL, + Status: db.RequestReady, Info: info.JSON(), Lang: lang, + } + msg, err := b.send(ctx, chat, 0, titleLine(info.Title)+"\n"+b.tr.HTML(lang, "status.preparing", nil), nil) + if err != nil { + return + } + req.CardMessageID = int64(msg.MessageID) + if err := b.store.InsertRequest(ctx, req); err != nil { + b.internalError(ctx, chat, act, err) + return + } + err = b.startFromRequest(ctx, req, info, profile, nil) + var le *service.LimitError + switch { + case err == nil: + case errors.As(err, &le) && le.Upgradable: + b.offerUpgrade(ctx, chat, req.CardMessageID, lang, req, profile, le, isPrivate(chatType)) + default: + _ = b.edit(ctx, chat, req.CardMessageID, false, titleLine(info.Title)+"\n"+html.EscapeString(b.startErrorText(lang, err)), nil) + } +} + +// --- owner: cache ------------------------------------------------------------ + +// isOwner reports whether a message is an owner command: sent by a +// configured owner, in a private chat. +func (b *Bot) isOwner(m *telego.Message) bool { + return m.From != nil && isPrivate(m.Chat.Type) && b.cfg.IsOwner(m.From.ID) +} + +// cmdPurge is the takedown command: /purge or /purge extractor:id. +func (b *Bot) cmdPurge(ctx context.Context, m *telego.Message, act actor) { + lang := act.lang + arg := commandArgs(m) + if arg == "" { + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "owner.purge_usage", nil), nil) + return + } + target, reason, _ := strings.Cut(arg, " ") + b.goBG("purge", func() { + var extractor, videoID string + if urls := messageLinks(m); len(urls) > 0 { + info, err := b.svc.Probe(ctx, urls[0]) + if err != nil { + _, _ = b.send(ctx, m.Chat.ID, 0, b.probeErrorText(lang, err), nil) + return + } + extractor, videoID = cache.Canonical(info.Extractor, info.VideoID, urls[0]) + b.cache.MetaDrop(urls[0]) + } else { + var ok bool + if extractor, videoID, ok = strings.Cut(target, ":"); !ok || extractor == "" || videoID == "" { + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "owner.purge_usage", nil), nil) + return + } + } + n, err := b.cache.Purge(ctx, extractor, videoID, strings.TrimSpace(reason), act.user.ID) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "owner.purged", i18n.Args{ + "Key": extractor + ":" + videoID, "Count": n, + }), nil) + }) +} + +func (b *Bot) cmdCache(ctx context.Context, m *telego.Message, act actor) { + lang := act.lang + sum, err := b.cache.Summary(ctx) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + st := b.cache.Stats() + rate := "0%" + if total := st.Hits + st.Misses; total > 0 { + rate = b.tr.Percent(lang, float64(st.Hits)/float64(total)) + } + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "owner.cache", i18n.Args{ + "Entries": b.tr.Number(lang, sum.Entries), + "Stored": b.tr.Number(lang, sum.Stored), + "Size": b.tr.Size(lang, sum.Bytes), + "Budget": b.capSize(lang, b.cfg.Cache.BudgetMB<<20), + "Hits": b.tr.Number(lang, sum.Hits), + "Blocked": b.tr.Number(lang, sum.Blocked), + "Rate": rate, + "Saved": b.tr.Size(lang, st.BytesSaved), + "Since": strconv.FormatInt(st.Hits+st.Misses, 10), + }), nil) +} diff --git a/internal/bot/menu.go b/internal/bot/menu.go index 4438c95..7142914 100644 --- a/internal/bot/menu.go +++ b/internal/bot/menu.go @@ -9,7 +9,7 @@ import ( // menuCommands are the commands shown in Telegram's command menu, in // order. Names are lowercase ASCII in every language; only descriptions // are translated, under "menu.". -var menuCommands = []string{"dl", "audio", "thumb", "info", "queue", "cancel", "account", "buy", "help"} +var menuCommands = []string{"dl", "audio", "thumb", "info", "queue", "cancel", "history", "account", "buy", "help"} // RegisterCommands publishes the command menu. A failure is logged and // otherwise ignored: the bot works without a menu. diff --git a/internal/bot/money.go b/internal/bot/money.go index 08103dc..bc505ed 100644 --- a/internal/bot/money.go +++ b/internal/bot/money.go @@ -735,7 +735,7 @@ func (b *Bot) startBuyLink(ctx context.Context, m *telego.Message, act actor, pa return } who := service.Who{UserID: req.UserID, ChatID: req.ChatID, ChatType: req.ChatType} - err = b.svc.Preview(ctx, who, info, profile) + err = b.svc.Preview(ctx, who, req.URL, info, profile) var le *service.LimitError switch { case err == nil: diff --git a/internal/bot/status.go b/internal/bot/status.go index ee3e2e6..124b515 100644 --- a/internal/bot/status.go +++ b/internal/bot/status.go @@ -54,6 +54,8 @@ func (b *Bot) eventLoop(ctx context.Context) { b.safely("event", func() { b.handleEvent(ctx, ev) }) case ev := <-b.payEvents: b.safely("payment", func() { b.handlePayEvent(ctx, ev) }) + case <-b.pump: + b.safely("playlist", func() { b.pumpPlaylists(ctx) }) case <-t.C: b.safely("reconcile", func() { b.reconcile(ctx) }) } @@ -68,8 +70,10 @@ func (b *Bot) handleEvent(ctx context.Context, ev sched.Event) { b.goBG("deliver", func() { b.deliverJob(ctx, ev.JobID) }) case sched.EventFailed: b.failJob(ctx, ev.JobID) + b.pumpSoon() case sched.EventCancelled: b.cleanupCancelled(ctx, ev.JobID) + b.pumpSoon() } } @@ -108,6 +112,7 @@ func (b *Bot) reconcile(ctx context.Context) { // Refunds and paid follow-ups that an interruption left undone. b.svc.ReleasePending(ctx) b.fulfilPending(ctx) + b.pumpPlaylists(ctx) // Jobs whose requesters were all served but that were never closed. delivering, err := b.store.JobsByStatus(ctx, db.JobDelivering, 200) diff --git a/internal/cache/cache.go b/internal/cache/cache.go new file mode 100644 index 0000000..b6dafdb --- /dev/null +++ b/internal/cache/cache.go @@ -0,0 +1,555 @@ +// Package cache makes repeat downloads fast. It has three layers: +// +// 1. Telegram file_ids, valid for one bot token, for instant resends. +// 2. Stored copies in Storage, used to re-upload when a file_id stops +// working and as the source for transcoding lower profiles. +// 3. A short-lived metadata cache, so cards for known links are instant. +// +// The cache only removes work. It decides nothing about limits: every +// request, hit or miss, passes the same admission in package service. +package cache + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "log/slog" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/media" + "github.com/noderunners/dlbot/internal/storage" +) + +// Config holds the cache settings. +type Config struct { + Enabled bool + // BudgetBytes caps the total size of stored copies. 0 means no cap. + BudgetBytes int64 + // TTLs by source class. Stable sites keep files for a long time, + // ephemeral ones (stories, feeds) for a short time. + TTLDefault time.Duration + TTLStable time.Duration + TTLEphemeral time.Duration + // Stable and Ephemeral are extractor name prefixes. + Stable []string + Ephemeral []string + // MetaTTL is how long link metadata is remembered. + MetaTTL time.Duration + // Derive allows making lower profiles from a stored higher one. + Derive bool +} + +// Stats are counters for metrics. +type Stats struct { + Hits int64 + Misses int64 + BytesSaved int64 +} + +// Cache is the cache service. +type Cache struct { + cfg Config + botID int64 + store *db.Store + storage storage.Storage + log *slog.Logger + now func() time.Time + + hits, misses, saved atomic.Int64 + + metaMu sync.Mutex + meta map[string]metaItem +} + +type metaItem struct { + value string + expires time.Time +} + +// New creates the cache for one bot. +func New(cfg Config, botID int64, store *db.Store, st storage.Storage, log *slog.Logger) *Cache { + if log == nil { + log = slog.Default() + } + return &Cache{cfg: cfg, botID: botID, store: store, storage: st, log: log, now: time.Now, meta: map[string]metaItem{}} +} + +// SetClock replaces the time source, for tests. +func (c *Cache) SetClock(now func() time.Time) { c.now = now } + +// Enabled reports whether results are cached. +func (c *Cache) Enabled() bool { return c.cfg.Enabled } + +// Stats returns the counters. +func (c *Cache) Stats() Stats { + return Stats{Hits: c.hits.Load(), Misses: c.misses.Load(), BytesSaved: c.saved.Load()} +} + +// Canonical turns yt-dlp metadata into the two stable parts of a cache +// key. Different URLs of the same video (watch page, short link, embed) +// give the same extractor and ID, which is what lets them share an entry. +// +// The generic extractor has no real IDs: it names a file after the last +// part of its URL, so two sites can collide. For it, and whenever an ID is +// missing, the key falls back to a hash of the URL. +func Canonical(extractor, videoID, url string) (string, string) { + ext := strings.ToLower(strings.TrimSpace(extractor)) + if i := strings.IndexByte(ext, ':'); i > 0 { + ext = ext[:i] // "youtube:tab" and "youtube" are one site + } + id := strings.TrimSpace(videoID) + if ext == "" || ext == "generic" || id == "" { + sum := sha256.Sum256([]byte(url)) + if ext == "" { + ext = "generic" + } + return ext, "url-" + hex.EncodeToString(sum[:16]) + } + return ext, id +} + +// JobKey is the string stored with a job to find others working on the +// same result. +func JobKey(extractor, videoID, profile string) string { + return extractor + "\x1f" + videoID + "\x1f" + profile +} + +// Cacheable reports whether content with this availability may be kept. +// Anything that needed a login, is private or is members-only is never +// cached or shared between users. +func Cacheable(availability string, live bool) bool { + if live { + return false + } + switch availability { + case "", "public", "unlisted": + return true + } + return false +} + +// ttl picks the lifetime for an extractor. +func (c *Cache) ttl(extractor string) time.Duration { + for _, p := range c.cfg.Ephemeral { + if strings.HasPrefix(extractor, strings.ToLower(p)) { + return c.cfg.TTLEphemeral + } + } + for _, p := range c.cfg.Stable { + if strings.HasPrefix(extractor, strings.ToLower(p)) { + return c.cfg.TTLStable + } + } + return c.cfg.TTLDefault +} + +// Blocked reports whether a video or its site was taken down by the owner. +func (c *Cache) Blocked(ctx context.Context, extractor, videoID, site string) (bool, error) { + if site != "" { + // A blocked host also blocks its subdomains. + for host := site; strings.Contains(host, "."); host = host[strings.IndexByte(host, '.')+1:] { + if ok, err := c.store.IsBlocked(ctx, db.BlockSite, host); err != nil || ok { + return ok, err + } + } + } + if ok, err := c.store.IsBlocked(ctx, db.BlockKey, extractor+":"+videoID); err != nil || ok { + return ok, err + } + entries, err := c.store.CacheEntriesForVideo(ctx, c.botID, extractor, videoID) + if err != nil { + return false, err + } + for _, e := range entries { + if e.Status == db.CacheBlocked { + return true, nil + } + } + return false, nil +} + +// usable reports whether an entry can serve a request right now. +func (c *Cache) usable(e *db.CacheEntry) bool { + if e == nil || e.Status != db.CacheReady || e.Private { + return false + } + if e.ExpiresAt > 0 && e.ExpiresAt < c.now().UnixMilli() { + return false + } + return e.TgFileID != "" || e.StorageKey != "" +} + +// Lookup finds a ready entry for exactly this profile, or nil. +func (c *Cache) Lookup(ctx context.Context, extractor, videoID string, profile media.Profile) (*db.CacheEntry, error) { + if !c.cfg.Enabled { + return nil, nil + } + e, err := c.store.GetCacheEntry(ctx, c.botID, extractor, videoID, string(profile)) + if errors.Is(err, db.ErrNotFound) { + return nil, nil + } + if err != nil || !c.usable(e) { + return nil, err + } + return e, nil +} + +// higher lists the video profiles above p, nearest first. +func higher(p media.Profile) []media.Profile { + switch p { + case media.P480: + return []media.Profile{media.P720, media.P1080, media.Best} + case media.P720: + return []media.Profile{media.P1080, media.Best} + case media.P1080: + return []media.Profile{media.Best} + case media.MP3, media.M4A: + return []media.Profile{media.P480, media.P720, media.P1080, media.Best} + } + return nil +} + +// Related looks for a cached higher profile that can stand in for the +// requested one. +// +// - alias: a higher profile whose picture is already no taller than the +// requested cap. It is the very file yt-dlp would fetch, so it is +// served as a hit. (A 480p source asked for as "720" is one example.) +// - source: a stored higher profile to transcode from, when Derive is on. +// +// At most one of the two is returned. +func (c *Cache) Related(ctx context.Context, extractor, videoID string, profile media.Profile) (alias, source *db.CacheEntry, err error) { + if !c.cfg.Enabled { + return nil, nil, nil + } + target := profile.Height() + for _, hp := range higher(profile) { + e, err := c.Lookup(ctx, extractor, videoID, hp) + if err != nil { + return nil, nil, err + } + if e == nil { + continue + } + if profile.Kind() == media.KindVideo && e.Height > 0 && e.Height <= target { + return e, nil, nil + } + if source == nil && c.cfg.Derive && e.StorageKey != "" && streamable(e.FileExt) { + if profile.Kind() == media.KindAudio || e.Height > target { + source = e + } + } + } + return nil, source, nil +} + +func streamable(ext string) bool { + switch ext { + case "mp4", "m4v", "mov", "mkv", "webm": + return true + } + return false +} + +// ProfileServing returns the profile of the entry a cache hit job is being +// served from. It is usually the job's own profile, but an alias hit is +// served from a higher profile's entry. The entry is found by the file_id +// or stored copy the job carries. +func (c *Cache) ProfileServing(ctx context.Context, job *db.Job) string { + entries, err := c.store.CacheEntriesForVideo(ctx, c.botID, job.Extractor, job.VideoID) + if err == nil { + for _, e := range entries { + if (job.TgFileID != "" && e.TgFileID == job.TgFileID) || (job.StorageKey != "" && e.StorageKey == job.StorageKey) { + return e.Profile + } + } + } + return job.Profile +} + +// RecordHit counts a hit and the bytes it saved. +func (c *Cache) RecordHit(ctx context.Context, e *db.CacheEntry) { + c.hits.Add(1) + c.saved.Add(e.Size) + if err := c.store.TouchCacheEntry(ctx, e, c.now().UnixMilli()); err != nil { + c.log.Warn("cache: count hit", "err", err) + } +} + +// RecordMiss counts a request the cache could not serve. +func (c *Cache) RecordMiss() { c.misses.Add(1) } + +// Put stores the result of a finished job. The job's stored file becomes +// the cache's stored copy; a copy held by an older entry is deleted. +func (c *Cache) Put(ctx context.Context, job *db.Job, fileID, uniqueID string) error { + if !c.cfg.Enabled || !job.Cacheable || job.Extractor == "" || job.VideoID == "" { + return errors.New("cache: job is not cacheable") + } + now := c.now().UnixMilli() + old, err := c.store.GetCacheEntry(ctx, c.botID, job.Extractor, job.VideoID, job.Profile) + if err != nil && !errors.Is(err, db.ErrNotFound) { + return err + } + if old != nil && old.Status == db.CacheBlocked { + return errors.New("cache: key is blocked") + } + e := &db.CacheEntry{ + BotID: c.botID, Extractor: job.Extractor, VideoID: job.VideoID, Profile: job.Profile, + TgFileID: fileID, TgFileUniqueID: uniqueID, StorageKey: job.StorageKey, Size: job.FileSize, + Duration: job.Duration, Title: job.Title, Uploader: job.Uploader, FileExt: job.FileExt, + Width: job.Width, Height: job.Height, LastHit: now, Status: db.CacheReady, CreatedAt: now, + ExpiresAt: now + c.ttl(job.Extractor).Milliseconds(), + } + if err := c.store.UpsertCacheEntry(ctx, e); err != nil { + return err + } + if old != nil && old.StorageKey != "" && old.StorageKey != job.StorageKey { + if err := c.storage.Delete(ctx, old.StorageKey); err != nil { + c.log.Warn("cache: delete replaced copy", "key", old.StorageKey, "err", err) + } + } + return nil +} + +// SetFileID records a new file_id for an entry, after a re-upload. +func (c *Cache) SetFileID(ctx context.Context, extractor, videoID, profile, fileID, uniqueID string) error { + return c.store.SetCacheFileID(ctx, &db.CacheEntry{BotID: c.botID, Extractor: extractor, VideoID: videoID, Profile: profile}, fileID, uniqueID) +} + +// DropStored forgets a stored copy that turned out to be missing. +func (c *Cache) DropStored(ctx context.Context, extractor, videoID, profile string) error { + return c.store.ClearCacheStorage(ctx, &db.CacheEntry{BotID: c.botID, Extractor: extractor, VideoID: videoID, Profile: profile}) +} + +// Forget removes an entry completely, with its stored copy. +func (c *Cache) Forget(ctx context.Context, extractor, videoID, profile string) error { + e, err := c.store.GetCacheEntry(ctx, c.botID, extractor, videoID, profile) + if errors.Is(err, db.ErrNotFound) { + return nil + } + if err != nil { + return err + } + return c.remove(ctx, e) +} + +func (c *Cache) remove(ctx context.Context, e *db.CacheEntry) error { + if e.StorageKey != "" { + if err := c.storage.Delete(ctx, e.StorageKey); err != nil { + return err + } + } + return c.store.DeleteCacheEntry(ctx, e) +} + +// Purge is a takedown: it deletes the stored files of every profile of a +// video, invalidates their file_ids and blocks the key, so the video is +// neither served from the cache nor downloaded again. It returns the +// number of entries that were purged. +func (c *Cache) Purge(ctx context.Context, extractor, videoID, reason string, by int64) (int, error) { + entries, err := c.store.CacheEntriesForVideo(ctx, c.botID, extractor, videoID) + if err != nil { + return 0, err + } + n := 0 + for _, e := range entries { + if e.StorageKey != "" { + if err := c.storage.Delete(ctx, e.StorageKey); err != nil { + return n, err + } + } + if e.Status == db.CacheReady { + n++ + } + } + if err := c.store.BlockCacheKey(ctx, c.botID, extractor, videoID, c.now().UnixMilli()); err != nil { + return n, err + } + // The blocklist row is what stops a key that was never cached. + if err := c.store.AddBlock(ctx, db.BlockKey, extractor+":"+videoID, reason, by); err != nil { + return n, err + } + c.log.Info("cache: purged", "extractor", extractor, "video_id", videoID, "entries", n, "by", by) + return n, nil +} + +// --- metadata layer -------------------------------------------------------- + +// MetaGet returns remembered metadata for a URL. +func (c *Cache) MetaGet(url string) (string, bool) { + if c.cfg.MetaTTL <= 0 { + return "", false + } + c.metaMu.Lock() + defer c.metaMu.Unlock() + it, ok := c.meta[url] + if !ok || c.now().After(it.expires) { + delete(c.meta, url) + return "", false + } + return it.value, true +} + +// MetaPut remembers metadata for a URL. +func (c *Cache) MetaPut(url, value string) { + if c.cfg.MetaTTL <= 0 { + return + } + c.metaMu.Lock() + defer c.metaMu.Unlock() + if len(c.meta) >= 5000 { + now := c.now() + for k, v := range c.meta { + if now.After(v.expires) || len(c.meta) >= 5000 { + delete(c.meta, k) + } + if len(c.meta) < 4000 { + break + } + } + } + c.meta[url] = metaItem{value: value, expires: c.now().Add(c.cfg.MetaTTL)} +} + +// MetaDrop forgets the metadata of a URL. +func (c *Cache) MetaDrop(url string) { + c.metaMu.Lock() + delete(c.meta, url) + c.metaMu.Unlock() +} + +// --- eviction -------------------------------------------------------------- + +// SweepResult summarizes one sweep. +type SweepResult struct { + Expired int + Evicted int + Orphans int +} + +// orphanAge is how old an unreferenced stored file must be before the +// sweeper removes it. It leaves room for an upload that is in progress. +const orphanAge = time.Hour + +// Sweep expires old entries, enforces the size budget and deletes stored +// files that nothing references anymore. +func (c *Cache) Sweep(ctx context.Context) (SweepResult, error) { + var res SweepResult + now := c.now().UnixMilli() + + expired, err := c.store.ExpiredCacheEntries(ctx, c.botID, now, 500) + if err != nil { + return res, err + } + for _, e := range expired { + if err := c.remove(ctx, e); err != nil { + c.log.Warn("cache: expire entry", "err", err) + continue + } + res.Expired++ + } + + if c.cfg.BudgetBytes > 0 { + used, err := c.store.CacheStoredBytes(ctx, c.botID) + if err != nil { + return res, err + } + for used > c.cfg.BudgetBytes { + victims, err := c.store.CacheEvictionCandidates(ctx, c.botID, 50) + if err != nil { + return res, err + } + if len(victims) == 0 { + break + } + for _, e := range victims { + if used <= c.cfg.BudgetBytes { + break + } + // Only the stored copy goes. The file_id stays, so the entry + // still serves instant resends at no storage cost. + if err := c.storage.Delete(ctx, e.StorageKey); err != nil { + return res, err + } + if err := c.store.ClearCacheStorage(ctx, e); err != nil { + return res, err + } + if e.TgFileID == "" { + _ = c.store.DeleteCacheEntry(ctx, e) // nothing left to serve + } + used -= e.Size + res.Evicted++ + } + } + } + + orphans, err := c.sweepOrphans(ctx) + res.Orphans = orphans + if res.Expired+res.Evicted+res.Orphans > 0 { + c.log.Info("cache: sweep", "expired", res.Expired, "evicted", res.Evicted, "orphans", res.Orphans) + } + return res, err +} + +// sweepOrphans deletes stored files that neither a live job nor a cache +// entry points at, such as the leftovers of a crash between an upload and +// its bookkeeping. +func (c *Cache) sweepOrphans(ctx context.Context) (int, error) { + inCache, err := c.store.CacheStorageKeys(ctx) + if err != nil { + return 0, err + } + inJobs, err := c.store.JobStorageKeys(ctx) + if err != nil { + return 0, err + } + cutoff := c.now().Add(-orphanAge) + var doomed []string + err = c.storage.List(ctx, "jobs/", func(o storage.Object) error { + if !inCache[o.Key] && !inJobs[o.Key] && o.ModTime.Before(cutoff) { + doomed = append(doomed, o.Key) + } + return nil + }) + if err != nil { + return 0, err + } + n := 0 + for _, key := range doomed { + if err := c.storage.Delete(ctx, key); err != nil { + c.log.Warn("cache: delete orphan", "key", key, "err", err) + continue + } + n++ + } + return n, nil +} + +// Run sweeps on a schedule until ctx ends. +func (c *Cache) Run(ctx context.Context, every time.Duration) { + if every <= 0 { + every = 10 * time.Minute + } + t := time.NewTicker(every) + defer t.Stop() + for { + if _, err := c.Sweep(ctx); err != nil && ctx.Err() == nil { + c.log.Error("cache: sweep failed", "err", err) + } + select { + case <-ctx.Done(): + return + case <-t.C: + } + } +} + +// Summary returns counts for the owner. +func (c *Cache) Summary(ctx context.Context) (db.CacheCounts, error) { + return c.store.CacheSummary(ctx, c.botID) +} diff --git a/internal/cache/cache_test.go b/internal/cache/cache_test.go new file mode 100644 index 0000000..da93b56 --- /dev/null +++ b/internal/cache/cache_test.go @@ -0,0 +1,495 @@ +package cache_test + +import ( + "context" + "errors" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/noderunners/dlbot/internal/cache" + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/db/dbtest" + "github.com/noderunners/dlbot/internal/media" + "github.com/noderunners/dlbot/internal/storage" +) + +const botID = int64(777) + +type rig struct { + t *testing.T + store *db.Store + st *storage.Local + c *cache.Cache + now atomic.Int64 + seq int +} + +func newRig(t *testing.T, mut func(*cache.Config)) *rig { + t.Helper() + st, err := storage.NewLocal(filepath.Join(t.TempDir(), "files")) + if err != nil { + t.Fatal(err) + } + cfg := cache.Config{ + Enabled: true, TTLDefault: 7 * 24 * time.Hour, TTLStable: 30 * 24 * time.Hour, + TTLEphemeral: 6 * time.Hour, Stable: []string{"youtube"}, Ephemeral: []string{"twitter", "generic"}, + MetaTTL: 30 * time.Minute, Derive: true, + } + if mut != nil { + mut(&cfg) + } + r := &rig{t: t, store: dbtest.Open(t).Store(), st: st} + r.now.Store(time.Date(2026, 5, 1, 0, 0, 0, 0, time.UTC).UnixMilli()) + r.c = cache.New(cfg, botID, r.store, st, nil) + r.c.SetClock(func() time.Time { return time.UnixMilli(r.now.Load()) }) + return r +} + +func (r *rig) advance(d time.Duration) { r.now.Add(d.Milliseconds()) } + +// put stores a result of the given size as a finished job would. +func (r *rig) put(extractor, videoID, profile string, size int64, height int, fileID string) *db.Job { + r.t.Helper() + r.seq++ + key := "jobs/job" + strings.Repeat("0", 3) + string(rune('a'+r.seq)) + "/media" + if err := r.st.Put(context.Background(), key, strings.NewReader(strings.Repeat("x", int(size))), size); err != nil { + r.t.Fatal(err) + } + job := &db.Job{ + ID: "job" + string(rune('a'+r.seq)), Extractor: extractor, VideoID: videoID, Profile: profile, + StorageKey: key, FileSize: size, FileExt: "mp4", Duration: 60, Width: height * 16 / 9, Height: height, + Title: "T", Cacheable: true, + } + if err := r.c.Put(context.Background(), job, fileID, "u-"+fileID); err != nil { + r.t.Fatalf("Put: %v", err) + } + return job +} + +func (r *rig) lookup(extractor, videoID string, p media.Profile) *db.CacheEntry { + r.t.Helper() + e, err := r.c.Lookup(context.Background(), extractor, videoID, p) + if err != nil { + r.t.Fatal(err) + } + return e +} + +func (r *rig) stored(key string) bool { + _, err := r.st.Stat(context.Background(), key) + return err == nil +} + +func TestCanonical(t *testing.T) { + tests := []struct { + name string + extractor, id, url string + wantExt, wantID string + }{ + {"plain", "youtube", "dQw4w9WgXcQ", "https://www.youtube.com/watch?v=dQw4w9WgXcQ", "youtube", "dQw4w9WgXcQ"}, + {"short link, same video", "youtube", "dQw4w9WgXcQ", "https://youtu.be/dQw4w9WgXcQ?t=5", "youtube", "dQw4w9WgXcQ"}, + {"extractor case and suffix", "Youtube:tab", "abc", "https://youtube.com/x", "youtube", "abc"}, + {"spaces", " vimeo ", " 123 ", "https://vimeo.com/123", "vimeo", "123"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + ext, id := cache.Canonical(tc.extractor, tc.id, tc.url) + if ext != tc.wantExt || id != tc.wantID { + t.Fatalf("Canonical = %q, %q; want %q, %q", ext, id, tc.wantExt, tc.wantID) + } + }) + } + + // The generic extractor names files after the end of the URL, so two + // sites can produce the same ID. Its key must come from the whole URL. + e1, id1 := cache.Canonical("generic", "video", "https://a.example/video.mp4") + e2, id2 := cache.Canonical("generic", "video", "https://b.example/video.mp4") + _, id3 := cache.Canonical("generic", "video", "https://a.example/video.mp4") + if e1 != "generic" || e2 != "generic" || id1 == id2 { + t.Fatalf("generic IDs must differ per URL: %q vs %q", id1, id2) + } + if id1 != id3 || !strings.HasPrefix(id1, "url-") || id1 == "video" { + t.Fatalf("generic IDs must be stable hashes: %q, %q", id1, id3) + } + // A missing ID or extractor falls back the same way. + if ext, id := cache.Canonical("", "", "https://x.example/y"); ext != "generic" || !strings.HasPrefix(id, "url-") { + t.Fatalf("empty metadata: %q, %q", ext, id) + } + if _, id := cache.Canonical("vimeo", "", "https://vimeo.com/1"); !strings.HasPrefix(id, "url-") { + t.Fatalf("missing ID: %q", id) + } + if a, b := cache.JobKey("youtube", "abc", "720"), cache.JobKey("youtube", "abc", "480"); a == b { + t.Fatal("profiles must have separate job keys") + } +} + +func TestCacheable(t *testing.T) { + for av, want := range map[string]bool{ + "": true, "public": true, "unlisted": true, + "private": false, "needs_auth": false, "premium_only": false, "subscriber_only": false, + } { + if got := cache.Cacheable(av, false); got != want { + t.Errorf("Cacheable(%q) = %v, want %v", av, got, want) + } + } + if cache.Cacheable("public", true) { + t.Error("live streams are never cached") + } +} + +func TestPutLookupAndReplace(t *testing.T) { + r := newRig(t, nil) + ctx := context.Background() + if e := r.lookup("youtube", "v1", media.P720); e != nil { + t.Fatalf("empty cache returned %+v", e) + } + first := r.put("youtube", "v1", "720", 1000, 720, "file-1") + e := r.lookup("youtube", "v1", media.P720) + if e == nil || e.TgFileID != "file-1" || e.TgFileUniqueID != "u-file-1" || e.StorageKey != first.StorageKey || + e.Size != 1000 || e.Height != 720 || e.BotID != botID || e.Status != db.CacheReady { + t.Fatalf("entry = %+v", e) + } + if r.lookup("youtube", "v1", media.P480) != nil || r.lookup("youtube", "v2", media.P720) != nil { + t.Fatal("lookup must match extractor, video and profile exactly") + } + + r.c.RecordHit(ctx, e) + r.c.RecordHit(ctx, e) + r.c.RecordMiss() + if e := r.lookup("youtube", "v1", media.P720); e.Hits != 2 { + t.Fatalf("hits = %d", e.Hits) + } + if st := r.c.Stats(); st.Hits != 2 || st.Misses != 1 || st.BytesSaved != 2000 { + t.Fatalf("stats = %+v", st) + } + + // A newer result for the same key replaces the stored copy and keeps + // the hit count. + second := r.put("youtube", "v1", "720", 1200, 720, "file-2") + e = r.lookup("youtube", "v1", media.P720) + if e.TgFileID != "file-2" || e.StorageKey != second.StorageKey || e.Size != 1200 || e.Hits != 2 { + t.Fatalf("replaced entry = %+v", e) + } + if r.stored(first.StorageKey) || !r.stored(second.StorageKey) { + t.Fatal("the replaced copy must be deleted, the new one kept") + } + + // file_ids belong to one bot. Another bot on the same database sees + // nothing. + other := cache.New(cache.Config{Enabled: true, TTLDefault: time.Hour}, botID+1, r.store, r.st, nil) + if e, _ := other.Lookup(ctx, "youtube", "v1", media.P720); e != nil { + t.Fatalf("another bot got this bot's entry: %+v", e) + } + // A disabled cache finds nothing and stores nothing. + off := cache.New(cache.Config{Enabled: false}, botID, r.store, r.st, nil) + if e, _ := off.Lookup(ctx, "youtube", "v1", media.P720); e != nil { + t.Fatal("a disabled cache must not serve") + } + if err := off.Put(ctx, second, "x", ""); err == nil { + t.Fatal("a disabled cache must not store") + } + notCacheable := *second + notCacheable.Cacheable = false + if err := r.c.Put(ctx, ¬Cacheable, "x", ""); err == nil { + t.Fatal("a job that is not cacheable must be refused") + } +} + +func TestTTLBySourceType(t *testing.T) { + r := newRig(t, nil) + stable := r.put("youtube", "s", "best", 10, 1080, "f1") // 30 days + normal := r.put("vimeo", "n", "best", 10, 1080, "f2") // 7 days + ephemeral := r.put("twitter", "e", "best", 10, 720, "f3") // 6 hours + generic := r.put("generic", "url-abc", "best", 10, 720, "f4") // 6 hours + + alive := func() (s, n, e, g bool) { + return r.lookup("youtube", "s", media.Best) != nil, r.lookup("vimeo", "n", media.Best) != nil, + r.lookup("twitter", "e", media.Best) != nil, r.lookup("generic", "url-abc", media.Best) != nil + } + if s, n, e, g := alive(); !s || !n || !e || !g { + t.Fatal("fresh entries must all be served") + } + r.advance(7 * time.Hour) + if s, n, e, g := alive(); !s || !n || e || g { + t.Fatalf("after 7h: stable=%v normal=%v ephemeral=%v generic=%v", s, n, e, g) + } + res, err := r.c.Sweep(context.Background()) + if err != nil || res.Expired != 2 { + t.Fatalf("sweep = %+v, %v", res, err) + } + if r.stored(ephemeral.StorageKey) || r.stored(generic.StorageKey) || !r.stored(stable.StorageKey) { + t.Fatal("expired entries lose their files, live ones keep them") + } + r.advance(8 * 24 * time.Hour) + if s, n, _, _ := alive(); !s || n { + t.Fatalf("after 8 days: stable=%v normal=%v", s, n) + } + r.advance(30 * 24 * time.Hour) + if _, err := r.c.Sweep(context.Background()); err != nil { + t.Fatal(err) + } + if r.stored(stable.StorageKey) || r.stored(normal.StorageKey) { + t.Fatal("everything is expired and swept by now") + } +} + +func TestBudgetEvictsLeastValuableStoredCopies(t *testing.T) { + r := newRig(t, func(c *cache.Config) { c.BudgetBytes = 2500 }) + ctx := context.Background() + old := r.put("vimeo", "old", "best", 1000, 720, "f-old") + r.advance(time.Hour) + popular := r.put("vimeo", "popular", "best", 1000, 720, "f-pop") + r.advance(time.Hour) + recent := r.put("vimeo", "recent", "best", 1000, 720, "f-new") + + // "popular" is older than "recent" but was requested many times. + e := r.lookup("vimeo", "popular", media.Best) + for i := 0; i < 5; i++ { + r.c.RecordHit(ctx, e) + } + // 3000 bytes against a budget of 2500: one copy has to go, and it is + // the one nobody asked for in the longest time. + res, err := r.c.Sweep(ctx) + if err != nil || res.Evicted != 1 { + t.Fatalf("sweep = %+v, %v", res, err) + } + if r.stored(old.StorageKey) || !r.stored(popular.StorageKey) || !r.stored(recent.StorageKey) { + t.Fatal("the wrong copy was evicted") + } + // The evicted entry still serves instant resends through its file_id. + e = r.lookup("vimeo", "old", media.Best) + if e == nil || e.TgFileID != "f-old" || e.StorageKey != "" { + t.Fatalf("evicted entry = %+v", e) + } + + // Hits outweigh recency: with room for one copy, "popular" survives + // although "recent" is newer. + r.advance(time.Minute) + small := newRigConfig(r, 1000) + if res, err := small.Sweep(ctx); err != nil || res.Evicted != 1 { + t.Fatalf("second sweep = %+v, %v", res, err) + } + if !r.stored(popular.StorageKey) || r.stored(recent.StorageKey) { + t.Fatal("hit count must protect the popular entry") + } + // An entry with neither file_id nor stored copy is removed entirely. + lone := r.put("vimeo", "lone", "best", 1000, 720, "") + tiny := newRigConfig(r, 1) + if _, err := tiny.Sweep(ctx); err != nil { + t.Fatal(err) + } + if r.stored(lone.StorageKey) { + t.Fatal("the copy should be gone") + } + if _, err := r.store.GetCacheEntry(ctx, botID, "vimeo", "lone", "best"); !errors.Is(err, db.ErrNotFound) { + t.Fatalf("an entry with nothing to serve must be deleted: %v", err) + } +} + +// newRigConfig returns a cache on the same data with another budget. +func newRigConfig(r *rig, budget int64) *cache.Cache { + c := cache.New(cache.Config{Enabled: true, BudgetBytes: budget, TTLDefault: 7 * 24 * time.Hour}, botID, r.store, r.st, nil) + c.SetClock(func() time.Time { return time.UnixMilli(r.now.Load()) }) + return c +} + +func TestRelatedAliasAndDeriveSource(t *testing.T) { + r := newRig(t, nil) + ctx := context.Background() + + // A 1080p "best" is stored. 720 and 480 can be transcoded from it, + // and so can audio. + r.put("youtube", "hd", "best", 5000, 1080, "f-hd") + for _, p := range []media.Profile{media.P720, media.P480, media.MP3, media.M4A} { + alias, source, err := r.c.Related(ctx, "youtube", "hd", p) + if err != nil || alias != nil || source == nil || source.Profile != "best" { + t.Errorf("%s: alias=%v source=%+v err=%v, want the best copy as source", p, alias, source, err) + } + } + // Nothing sits above best. + if alias, source, _ := r.c.Related(ctx, "youtube", "hd", media.Best); alias != nil || source != nil { + t.Error("best has nothing to derive from") + } + + // A 360p "best" is stored. Asked for as 720 or 480 it is already the + // file yt-dlp would fetch, so it is served as is, without transcoding. + r.put("youtube", "sd", "best", 800, 360, "f-sd") + for _, p := range []media.Profile{media.P720, media.P480} { + alias, source, err := r.c.Related(ctx, "youtube", "sd", p) + if err != nil || source != nil || alias == nil || alias.TgFileID != "f-sd" { + t.Errorf("%s: alias=%+v source=%v err=%v, want the 360p file as alias", p, alias, source, err) + } + } + + // The nearest profile above wins as a source: less work to scale. + r.put("youtube", "multi", "best", 9000, 2160, "f-4k") + r.put("youtube", "multi", "720", 2000, 720, "f-720") + if _, source, _ := r.c.Related(ctx, "youtube", "multi", media.P480); source == nil || source.Profile != "720" { + t.Errorf("480 should derive from the 720 copy, got %+v", source) + } + + // Without a stored copy there is nothing to transcode from. + r.put("vimeo", "nofile", "best", 5000, 1080, "f-x") + e := r.lookup("vimeo", "nofile", media.Best) + if err := r.c.DropStored(ctx, "vimeo", "nofile", "best"); err != nil { + t.Fatal(err) + } + if _, source, _ := r.c.Related(ctx, "vimeo", "nofile", media.P720); source != nil { + t.Errorf("an entry without a stored copy (was %s) cannot be a source", e.StorageKey) + } + // Deriving can be switched off. + noDerive := cache.New(cache.Config{Enabled: true, TTLDefault: time.Hour, Derive: false}, botID, r.store, r.st, nil) + noDerive.SetClock(func() time.Time { return time.UnixMilli(r.now.Load()) }) + if _, source, _ := noDerive.Related(ctx, "youtube", "hd", media.P720); source != nil { + t.Error("derive is off, no source expected") + } + if alias, _, _ := noDerive.Related(ctx, "youtube", "sd", media.P720); alias == nil { + t.Error("aliases need no transcoding and still work with derive off") + } +} + +func TestPurgeDeletesInvalidatesAndBlocks(t *testing.T) { + r := newRig(t, nil) + ctx := context.Background() + a := r.put("youtube", "bad", "best", 100, 1080, "f-a") + b := r.put("youtube", "bad", "mp3", 50, 0, "f-b") + keep := r.put("youtube", "good", "best", 100, 1080, "f-k") + + if blocked, _ := r.c.Blocked(ctx, "youtube", "bad", "youtube.com"); blocked { + t.Fatal("nothing is blocked yet") + } + n, err := r.c.Purge(ctx, "youtube", "bad", "copyright notice", 1) + if err != nil || n != 2 { + t.Fatalf("Purge = %d, %v", n, err) + } + if r.stored(a.StorageKey) || r.stored(b.StorageKey) || !r.stored(keep.StorageKey) { + t.Fatal("purge must delete exactly the files of that video") + } + if r.lookup("youtube", "bad", media.Best) != nil || r.lookup("youtube", "bad", media.MP3) != nil { + t.Fatal("a purged video must not be served") + } + e, err := r.store.GetCacheEntry(ctx, botID, "youtube", "bad", "best") + if err != nil || e.Status != db.CacheBlocked || e.TgFileID != "" || e.StorageKey != "" { + t.Fatalf("purged entry = %+v, %v", e, err) + } + if blocked, _ := r.c.Blocked(ctx, "youtube", "bad", "youtube.com"); !blocked { + t.Fatal("the key must be blocked") + } + if blocked, _ := r.c.Blocked(ctx, "youtube", "good", "youtube.com"); blocked { + t.Fatal("other videos stay available") + } + // A blocked key cannot be cached again, whatever finishes later. + late := *a + late.StorageKey = "jobs/late/media" + if err := r.c.Put(ctx, &late, "f-late", ""); err == nil { + t.Fatal("a blocked key must refuse new results") + } + // Purging a video that was never cached still blocks it. + if n, err := r.c.Purge(ctx, "vimeo", "never", "", 1); err != nil || n != 0 { + t.Fatalf("purge of an unknown key = %d, %v", n, err) + } + if blocked, _ := r.c.Blocked(ctx, "vimeo", "never", "vimeo.com"); !blocked { + t.Fatal("a never-cached key must be blocked too") + } + // Expiry sweeps never remove takedown markers. + r.advance(365 * 24 * time.Hour) + if _, err := r.c.Sweep(ctx); err != nil { + t.Fatal(err) + } + if blocked, _ := r.c.Blocked(ctx, "youtube", "bad", ""); !blocked { + t.Fatal("a takedown must outlive every TTL") + } +} + +func TestSiteBlocklistCoversSubdomains(t *testing.T) { + r := newRig(t, nil) + ctx := context.Background() + if err := r.store.AddBlock(ctx, db.BlockSite, "bad.example", "spam", 1); err != nil { + t.Fatal(err) + } + for site, want := range map[string]bool{ + "bad.example": true, "cdn.bad.example": true, "a.b.bad.example": true, + "notbad.example": false, "example": false, "good.example": false, "": false, + } { + got, err := r.c.Blocked(ctx, "generic", "url-x", site) + if err != nil || got != want { + t.Errorf("Blocked(site=%q) = %v, %v; want %v", site, got, err, want) + } + } + if ok, _ := r.store.RemoveBlock(ctx, db.BlockSite, "bad.example"); !ok { + t.Fatal("RemoveBlock should report the removal") + } + if got, _ := r.c.Blocked(ctx, "generic", "url-x", "cdn.bad.example"); got { + t.Fatal("an unblocked site must be available again") + } +} + +func TestSweepRemovesOrphanFiles(t *testing.T) { + r := newRig(t, nil) + ctx := context.Background() + // Orphans are judged by the real modification time of their files, so + // this test starts its clock at the real time. + r.now.Store(time.Now().UnixMilli()) + cached := r.put("youtube", "v", "best", 100, 720, "f") + for _, key := range []string{"jobs/orphan1/media", "jobs/orphan2/media"} { + if err := r.st.Put(ctx, key, strings.NewReader("left over"), 9); err != nil { + t.Fatal(err) + } + } + // A file of a job that is still running must survive. + live := &db.Job{ID: "livejob", URL: "u", Profile: "best", Status: db.JobRunning, CreatedAt: 1, QueuedAt: 1, MaxAttempts: 2} + if err := r.store.InsertJob(ctx, live); err != nil { + t.Fatal(err) + } + if err := r.st.Put(ctx, "jobs/livejob/media", strings.NewReader("in progress"), 11); err != nil { + t.Fatal(err) + } + + // Young files are left alone: an upload may still be running. + if res, err := r.c.Sweep(ctx); err != nil || res.Orphans != 0 { + t.Fatalf("sweep of young files = %+v, %v", res, err) + } + r.advance(2 * time.Hour) + res, err := r.c.Sweep(ctx) + if err != nil || res.Orphans != 2 { + t.Fatalf("sweep = %+v, %v", res, err) + } + if r.stored("jobs/orphan1/media") || r.stored("jobs/orphan2/media") { + t.Fatal("orphans must be deleted") + } + if !r.stored(cached.StorageKey) || !r.stored("jobs/livejob/media") { + t.Fatal("referenced files must be kept") + } +} + +func TestMetaLayer(t *testing.T) { + r := newRig(t, nil) + if _, ok := r.c.MetaGet("https://a.example/1"); ok { + t.Fatal("empty meta cache hit") + } + r.c.MetaPut("https://a.example/1", `{"x":1}`) + if v, ok := r.c.MetaGet("https://a.example/1"); !ok || v != `{"x":1}` { + t.Fatalf("meta = %q, %v", v, ok) + } + r.advance(29 * time.Minute) + if _, ok := r.c.MetaGet("https://a.example/1"); !ok { + t.Fatal("metadata should still be remembered") + } + r.advance(2 * time.Minute) + if _, ok := r.c.MetaGet("https://a.example/1"); ok { + t.Fatal("metadata should have expired") + } + r.c.MetaPut("https://a.example/2", "v") + r.c.MetaDrop("https://a.example/2") + if _, ok := r.c.MetaGet("https://a.example/2"); ok { + t.Fatal("dropped metadata was served") + } + off := cache.New(cache.Config{Enabled: true, MetaTTL: 0}, botID, r.store, r.st, nil) + off.MetaPut("k", "v") + if _, ok := off.MetaGet("k"); ok { + t.Fatal("a zero TTL turns the metadata layer off") + } +} diff --git a/internal/config/config.go b/internal/config/config.go index f6968a6..c3be281 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -44,6 +44,7 @@ type Config struct { Queue Queue `toml:"queue"` Limits Limits `toml:"limits"` LNbits LNbits `toml:"lnbits"` + Cache Cache `toml:"cache"` Prices Prices `toml:"prices"` Rate Rate `toml:"rate"` Log Log `toml:"log"` @@ -131,6 +132,32 @@ type Tier struct { // DailyMB is the volume per UTC day in MB, 0 for no cap. It applies to // paid users too, as a guard against abuse. DailyMB int64 `toml:"daily_mb"` + // PlaylistItems is how many items of one playlist link are fetched. + PlaylistItems int `toml:"playlist_items"` +} + +// Cache holds the smart cache settings. +type Cache struct { + Enabled bool `toml:"enabled" env:"CACHE_ENABLED"` + // BudgetMB caps the total size of stored copies. 0 means no cap. + BudgetMB int64 `toml:"budget_mb" env:"CACHE_BUDGET_MB"` + // TTLs by source class: how long a result is served before it is + // fetched again. + TTL Duration `toml:"ttl" env:"CACHE_TTL"` + TTLStable Duration `toml:"ttl_stable" env:"CACHE_TTL_STABLE"` + TTLEphemeral Duration `toml:"ttl_ephemeral" env:"CACHE_TTL_EPHEMERAL"` + // StableSites and EphemeralSites are yt-dlp extractor name prefixes. + StableSites []string `toml:"stable_sites" env:"CACHE_STABLE_SITES"` + EphemeralSites []string `toml:"ephemeral_sites" env:"CACHE_EPHEMERAL_SITES"` + // MetaTTL is how long link metadata is remembered, so cards for known + // links appear at once. + MetaTTL Duration `toml:"meta_ttl" env:"CACHE_META_TTL"` + // Derive makes lower profiles and audio from a stored higher profile + // with ffmpeg instead of downloading again. + Derive bool `toml:"derive" env:"CACHE_DERIVE"` + // SweepInterval is how often expiry, the size budget and orphan files + // are checked. + SweepInterval Duration `toml:"sweep_interval" env:"CACHE_SWEEP_INTERVAL"` } // Limits holds the per-tier limits. Free applies to everyone without a @@ -227,9 +254,21 @@ func Default() Config { }, Limits: Limits{ Free: Tier{MaxSizeMB: 50, MaxDuration: Duration(10 * time.Minute), ActiveJobs: 1, - DailyDownloads: 5, DailyMB: 250}, + DailyDownloads: 5, DailyMB: 250, PlaylistItems: 3}, Paid: Tier{MaxSizeMB: 2000, MaxDuration: Duration(3 * time.Hour), ActiveJobs: 3, - DailyDownloads: 100, DailyMB: 20000}, + DailyDownloads: 100, DailyMB: 20000, PlaylistItems: 25}, + }, + Cache: Cache{ + Enabled: true, + BudgetMB: 20000, + TTL: Duration(7 * 24 * time.Hour), + TTLStable: Duration(30 * 24 * time.Hour), + TTLEphemeral: Duration(6 * time.Hour), + StableSites: []string{"youtube", "vimeo", "archive.org", "soundcloud", "dailymotion", "peertube", "bandcamp"}, + EphemeralSites: []string{"twitter", "instagram", "tiktok", "facebook", "reddit", "twitch", "generic"}, + MetaTTL: Duration(30 * time.Minute), + Derive: true, + SweepInterval: Duration(10 * time.Minute), }, LNbits: LNbits{ PollInterval: Duration(5 * time.Second), @@ -387,6 +426,13 @@ func applyTierEnv(prefix string, t *Tier, lookup func(string) (string, bool)) er } t.DailyDownloads = n } + if v, ok := lookup(prefix + "_PLAYLIST_ITEMS"); ok && v != "" { + n, err := strconv.Atoi(v) + if err != nil { + return fmt.Errorf("config: %s_PLAYLIST_ITEMS: %w", prefix, err) + } + t.PlaylistItems = n + } if v, ok := lookup(prefix + "_DAILY_MB"); ok && v != "" { n, err := strconv.ParseInt(v, 10, 64) if err != nil { diff --git a/internal/db/cache.go b/internal/db/cache.go new file mode 100644 index 0000000..7961021 --- /dev/null +++ b/internal/db/cache.go @@ -0,0 +1,226 @@ +package db + +import ( + "context" + "database/sql" +) + +const cacheCols = `bot_id, extractor, video_id, profile, tg_file_id, tg_file_unique_id, storage_key, size, + duration, title, uploader, file_ext, width, height, hits, last_hit, expires_at, private, status, created_at` + +func scanCache(sc interface{ Scan(...any) error }) (*CacheEntry, error) { + var e CacheEntry + err := sc.Scan(&e.BotID, &e.Extractor, &e.VideoID, &e.Profile, &e.TgFileID, &e.TgFileUniqueID, &e.StorageKey, + &e.Size, &e.Duration, &e.Title, &e.Uploader, &e.FileExt, &e.Width, &e.Height, &e.Hits, &e.LastHit, + &e.ExpiresAt, &e.Private, &e.Status, &e.CreatedAt) + if err != nil { + return nil, notFound(err) + } + return &e, nil +} + +func scanCaches(rows *sql.Rows, err error) ([]*CacheEntry, error) { + if err != nil { + return nil, err + } + defer rows.Close() + var out []*CacheEntry + for rows.Next() { + e, err := scanCache(rows) + if err != nil { + return nil, err + } + out = append(out, e) + } + return out, rows.Err() +} + +// GetCacheEntry loads one entry in any status. +func (s *Store) GetCacheEntry(ctx context.Context, botID int64, extractor, videoID, profile string) (*CacheEntry, error) { + return scanCache(s.row(ctx, `SELECT `+cacheCols+` FROM cache_entries + WHERE bot_id = ? AND extractor = ? AND video_id = ? AND profile = ?`, botID, extractor, videoID, profile)) +} + +// CacheEntriesForVideo lists every profile cached for a video. +func (s *Store) CacheEntriesForVideo(ctx context.Context, botID int64, extractor, videoID string) ([]*CacheEntry, error) { + return scanCaches(s.rows(ctx, `SELECT `+cacheCols+` FROM cache_entries + WHERE bot_id = ? AND extractor = ? AND video_id = ? ORDER BY profile`, botID, extractor, videoID)) +} + +// UpsertCacheEntry stores a result. An existing entry keeps its hit +// counters. A blocked entry is never overwritten. +func (s *Store) UpsertCacheEntry(ctx context.Context, e *CacheEntry) error { + _, err := s.exec(ctx, `INSERT INTO cache_entries (`+cacheCols+`) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT (bot_id, extractor, video_id, profile) DO UPDATE SET + tg_file_id = excluded.tg_file_id, + tg_file_unique_id = excluded.tg_file_unique_id, + storage_key = excluded.storage_key, + size = excluded.size, + duration = excluded.duration, + title = excluded.title, + uploader = excluded.uploader, + file_ext = excluded.file_ext, + width = excluded.width, + height = excluded.height, + expires_at = excluded.expires_at, + private = excluded.private + WHERE cache_entries.status <> 'blocked'`, + e.BotID, e.Extractor, e.VideoID, e.Profile, e.TgFileID, e.TgFileUniqueID, e.StorageKey, e.Size, + e.Duration, e.Title, e.Uploader, e.FileExt, e.Width, e.Height, e.Hits, e.LastHit, e.ExpiresAt, + e.Private, e.Status, e.CreatedAt) + return err +} + +// TouchCacheEntry counts a hit. +func (s *Store) TouchCacheEntry(ctx context.Context, e *CacheEntry, now int64) error { + _, err := s.exec(ctx, `UPDATE cache_entries SET hits = hits + 1, last_hit = ? + WHERE bot_id = ? AND extractor = ? AND video_id = ? AND profile = ?`, + now, e.BotID, e.Extractor, e.VideoID, e.Profile) + return err +} + +// SetCacheFileID replaces the Telegram file_id of an entry. An empty ID +// invalidates the instant-resend layer. +func (s *Store) SetCacheFileID(ctx context.Context, e *CacheEntry, fileID, uniqueID string) error { + _, err := s.exec(ctx, `UPDATE cache_entries SET tg_file_id = ?, tg_file_unique_id = ? + WHERE bot_id = ? AND extractor = ? AND video_id = ? AND profile = ?`, + fileID, uniqueID, e.BotID, e.Extractor, e.VideoID, e.Profile) + return err +} + +// ClearCacheStorage forgets the stored copy of an entry. +func (s *Store) ClearCacheStorage(ctx context.Context, e *CacheEntry) error { + _, err := s.exec(ctx, `UPDATE cache_entries SET storage_key = '' + WHERE bot_id = ? AND extractor = ? AND video_id = ? AND profile = ?`, + e.BotID, e.Extractor, e.VideoID, e.Profile) + return err +} + +// DeleteCacheEntry removes an entry unless it is a takedown marker. +func (s *Store) DeleteCacheEntry(ctx context.Context, e *CacheEntry) error { + _, err := s.exec(ctx, `DELETE FROM cache_entries + WHERE bot_id = ? AND extractor = ? AND video_id = ? AND profile = ? AND status <> 'blocked'`, + e.BotID, e.Extractor, e.VideoID, e.Profile) + return err +} + +// BlockCacheKey turns every entry of a video into a takedown marker +// without a file, and adds a marker for the key as a whole. +func (s *Store) BlockCacheKey(ctx context.Context, botID int64, extractor, videoID string, now int64) error { + _, err := s.exec(ctx, `UPDATE cache_entries SET status = 'blocked', tg_file_id = '', tg_file_unique_id = '', + storage_key = '', size = 0 WHERE bot_id = ? AND extractor = ? AND video_id = ?`, botID, extractor, videoID) + return err +} + +// ExpiredCacheEntries lists ready entries past their expiry. +func (s *Store) ExpiredCacheEntries(ctx context.Context, botID, now int64, limit int) ([]*CacheEntry, error) { + return scanCaches(s.rows(ctx, `SELECT `+cacheCols+` FROM cache_entries + WHERE bot_id = ? AND status = 'ready' AND expires_at > 0 AND expires_at < ? LIMIT ?`, botID, now, limit)) +} + +// CacheStoredBytes sums the size of all stored copies. +func (s *Store) CacheStoredBytes(ctx context.Context, botID int64) (int64, error) { + var n sql.NullInt64 + err := s.row(ctx, `SELECT SUM(size) FROM cache_entries WHERE bot_id = ? AND status = 'ready' AND storage_key <> ''`, + botID).Scan(&n) + return n.Int64, err +} + +// CacheEvictionCandidates lists entries with a stored copy, least valuable +// first. Value is recency plus a bonus per hit: every hit, up to 48, +// protects an entry like one more hour of recency. +func (s *Store) CacheEvictionCandidates(ctx context.Context, botID int64, limit int) ([]*CacheEntry, error) { + return scanCaches(s.rows(ctx, `SELECT `+cacheCols+` FROM cache_entries + WHERE bot_id = ? AND status = 'ready' AND storage_key <> '' + ORDER BY (last_hit + (CASE WHEN hits > 48 THEN 48 ELSE hits END) * 3600000) ASC, created_at ASC + LIMIT ?`, botID, limit)) +} + +// CacheStorageKeys returns every storage key the cache still references. +func (s *Store) CacheStorageKeys(ctx context.Context) (map[string]bool, error) { + rows, err := s.rows(ctx, `SELECT storage_key FROM cache_entries WHERE storage_key <> ''`) + if err != nil { + return nil, err + } + defer rows.Close() + out := map[string]bool{} + for rows.Next() { + var k string + if err := rows.Scan(&k); err != nil { + return nil, err + } + out[k] = true + } + return out, rows.Err() +} + +// CacheCounts summarizes the cache for the owner. +type CacheCounts struct { + Entries int64 + Stored int64 + Bytes int64 + Hits int64 + Blocked int64 +} + +// CacheSummary counts entries, stored copies, bytes and hits. +func (s *Store) CacheSummary(ctx context.Context, botID int64) (CacheCounts, error) { + var c CacheCounts + var bytes, hits sql.NullInt64 + err := s.row(ctx, `SELECT + COALESCE(SUM(CASE WHEN status = 'ready' THEN 1 ELSE 0 END), 0), + COALESCE(SUM(CASE WHEN status = 'ready' AND storage_key <> '' THEN 1 ELSE 0 END), 0), + SUM(CASE WHEN status = 'ready' AND storage_key <> '' THEN size ELSE 0 END), + SUM(hits), + COALESCE(SUM(CASE WHEN status = 'blocked' THEN 1 ELSE 0 END), 0) + FROM cache_entries WHERE bot_id = ?`, botID).Scan(&c.Entries, &c.Stored, &bytes, &hits, &c.Blocked) + c.Bytes, c.Hits = bytes.Int64, hits.Int64 + return c, err +} + +// --- blocklist ------------------------------------------------------------- + +// AddBlock adds a site or key to the owner blocklist. +func (s *Store) AddBlock(ctx context.Context, kind, value, reason string, by int64) error { + _, err := s.exec(ctx, `INSERT INTO blocklist (kind, value, reason, created_by, created_at) VALUES (?, ?, ?, ?, ?) + ON CONFLICT (kind, value) DO UPDATE SET reason = excluded.reason`, kind, value, reason, by, NowMilli()) + return err +} + +// RemoveBlock removes an entry and reports whether it existed. +func (s *Store) RemoveBlock(ctx context.Context, kind, value string) (bool, error) { + n, err := s.exec(ctx, `DELETE FROM blocklist WHERE kind = ? AND value = ?`, kind, value) + return n > 0, err +} + +// IsBlocked reports whether a site or key is on the blocklist. +func (s *Store) IsBlocked(ctx context.Context, kind, value string) (bool, error) { + var n int + err := s.row(ctx, `SELECT COUNT(*) FROM blocklist WHERE kind = ? AND value = ?`, kind, value).Scan(&n) + return n > 0, err +} + +// Block is one blocklist row. +type Block struct { + Kind, Value, Reason string + CreatedAt int64 +} + +// ListBlocks returns the blocklist, newest first. +func (s *Store) ListBlocks(ctx context.Context, limit int) ([]Block, error) { + rows, err := s.rows(ctx, `SELECT kind, value, reason, created_at FROM blocklist ORDER BY created_at DESC LIMIT ?`, limit) + if err != nil { + return nil, err + } + defer rows.Close() + var out []Block + for rows.Next() { + var b Block + if err := rows.Scan(&b.Kind, &b.Value, &b.Reason, &b.CreatedAt); err != nil { + return nil, err + } + out = append(out, b) + } + return out, rows.Err() +} diff --git a/internal/db/deliveries.go b/internal/db/deliveries.go index 99eed28..928b5c1 100644 --- a/internal/db/deliveries.go +++ b/internal/db/deliveries.go @@ -7,13 +7,15 @@ import ( const deliveryCols = `id, job_id, request_id, user_id, chat_id, chat_type, reply_to_message_id, status_message_id, status_is_photo, lang, status, attempts, error_code, tg_file_id, - tg_message_id, created_at, updated_at, source, wallet_id, charge_sats, quota_day, released` + tg_message_id, created_at, updated_at, source, wallet_id, charge_sats, quota_day, released, + max_size, max_duration` func scanDelivery(sc interface{ Scan(...any) error }) (*Delivery, error) { var d Delivery err := sc.Scan(&d.ID, &d.JobID, &d.RequestID, &d.UserID, &d.ChatID, &d.ChatType, &d.ReplyToMessageID, &d.StatusMessageID, &d.StatusIsPhoto, &d.Lang, &d.Status, &d.Attempts, &d.ErrorCode, &d.TgFileID, - &d.TgMessageID, &d.CreatedAt, &d.UpdatedAt, &d.Source, &d.WalletID, &d.ChargeSats, &d.QuotaDay, &d.Released) + &d.TgMessageID, &d.CreatedAt, &d.UpdatedAt, &d.Source, &d.WalletID, &d.ChargeSats, &d.QuotaDay, &d.Released, + &d.MaxSize, &d.MaxDuration) if err != nil { return nil, notFound(err) } @@ -46,10 +48,11 @@ func (s *Store) InsertDelivery(ctx context.Context, d *Delivery) error { d.Source = "free" } _, err := s.exec(ctx, `INSERT INTO deliveries (`+deliveryCols+`) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, d.ID, d.JobID, d.RequestID, d.UserID, d.ChatID, d.ChatType, d.ReplyToMessageID, d.StatusMessageID, d.StatusIsPhoto, d.Lang, d.Status, d.Attempts, d.ErrorCode, d.TgFileID, - d.TgMessageID, d.CreatedAt, d.UpdatedAt, d.Source, d.WalletID, d.ChargeSats, d.QuotaDay, d.Released) + d.TgMessageID, d.CreatedAt, d.UpdatedAt, d.Source, d.WalletID, d.ChargeSats, d.QuotaDay, d.Released, + d.MaxSize, d.MaxDuration) return err } @@ -162,3 +165,9 @@ func (s *Store) CountDeliveriesForRequest(ctx context.Context, requestID string) err := s.row(ctx, `SELECT COUNT(*) FROM deliveries WHERE request_id = ?`, requestID).Scan(&n) return n, err } + +// History lists a user's delivered files, newest first. +func (s *Store) History(ctx context.Context, userID int64, limit int) ([]*Delivery, error) { + return scanDeliveries(s.rows(ctx, `SELECT `+deliveryCols+` FROM deliveries + WHERE user_id = ? AND status = 'sent' ORDER BY updated_at DESC, id DESC LIMIT ?`, userID, limit)) +} diff --git a/internal/db/jobs.go b/internal/db/jobs.go index 8e40ac7..5ef78ce 100644 --- a/internal/db/jobs.go +++ b/internal/db/jobs.go @@ -10,7 +10,7 @@ const jobCols = `id, kind, url, extractor, video_id, profile, cache_key, status, required_tags, max_size, max_duration, attempts, max_attempts, worker_id, lease_expires_at, cancel_requested, stage, progress_bytes, total_bytes, error_code, error_detail, storage_key, file_ext, file_size, duration, width, height, title, uploader, created_at, queued_at, - started_at, finished_at` + started_at, finished_at, source_key, tg_file_id, cacheable, cache_hit` func scanJob(sc interface{ Scan(...any) error }) (*Job, error) { var j Job @@ -18,7 +18,8 @@ func scanJob(sc interface{ Scan(...any) error }) (*Job, error) { &j.Lane, &j.Priority, &j.RequiredTags, &j.MaxSize, &j.MaxDuration, &j.Attempts, &j.MaxAttempts, &j.WorkerID, &j.LeaseExpiresAt, &j.CancelRequested, &j.Stage, &j.ProgressBytes, &j.TotalBytes, &j.ErrorCode, &j.ErrorDetail, &j.StorageKey, &j.FileExt, &j.FileSize, &j.Duration, &j.Width, - &j.Height, &j.Title, &j.Uploader, &j.CreatedAt, &j.QueuedAt, &j.StartedAt, &j.FinishedAt) + &j.Height, &j.Title, &j.Uploader, &j.CreatedAt, &j.QueuedAt, &j.StartedAt, &j.FinishedAt, + &j.SourceKey, &j.TgFileID, &j.Cacheable, &j.CacheHit) if err != nil { return nil, notFound(err) } @@ -44,12 +45,13 @@ func scanJobs(rows *sql.Rows, err error) ([]*Job, error) { // InsertJob stores a new job. func (s *Store) InsertJob(ctx context.Context, j *Job) error { _, err := s.exec(ctx, `INSERT INTO jobs (`+jobCols+`) VALUES ( - ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, + ?, ?, ?, ?)`, j.ID, j.Kind, j.URL, j.Extractor, j.VideoID, j.Profile, j.CacheKey, j.Status, j.Lane, j.Priority, j.RequiredTags, j.MaxSize, j.MaxDuration, j.Attempts, j.MaxAttempts, j.WorkerID, j.LeaseExpiresAt, j.CancelRequested, j.Stage, j.ProgressBytes, j.TotalBytes, j.ErrorCode, j.ErrorDetail, j.StorageKey, j.FileExt, j.FileSize, j.Duration, j.Width, j.Height, j.Title, j.Uploader, j.CreatedAt, j.QueuedAt, - j.StartedAt, j.FinishedAt) + j.StartedAt, j.FinishedAt, j.SourceKey, j.TgFileID, j.Cacheable, j.CacheHit) return err } @@ -111,18 +113,20 @@ type JobResult struct { VideoID string } -// CompleteJob stores the result and moves the job to delivering. +// CompleteJob stores the result and moves the job to delivering. The +// extractor and video ID a job was queued with are its cache key and are +// kept; the worker's values only fill them in when they were empty. func (s *Store) CompleteJob(ctx context.Context, id, workerID string, r JobResult, now int64) (bool, error) { n, err := s.exec(ctx, `UPDATE jobs SET status = 'delivering', storage_key = ?, file_ext = ?, file_size = ?, duration = ?, width = ?, height = ?, title = CASE WHEN ? <> '' THEN ? ELSE title END, uploader = CASE WHEN ? <> '' THEN ? ELSE uploader END, - extractor = CASE WHEN ? <> '' THEN ? ELSE extractor END, - video_id = CASE WHEN ? <> '' THEN ? ELSE video_id END, + extractor = CASE WHEN extractor = '' THEN ? ELSE extractor END, + video_id = CASE WHEN video_id = '' THEN ? ELSE video_id END, lease_expires_at = 0, stage = 'uploading', finished_at = ? WHERE id = ? AND worker_id = ? AND status = 'running'`, r.StorageKey, r.FileExt, r.FileSize, r.Duration, r.Width, r.Height, - r.Title, r.Title, r.Uploader, r.Uploader, r.Extractor, r.Extractor, r.VideoID, r.VideoID, + r.Title, r.Title, r.Uploader, r.Uploader, r.Extractor, r.VideoID, now, id, workerID) return n == 1, err } @@ -240,3 +244,68 @@ func (s *Store) PromoteJob(ctx context.Context, id string) (bool, error) { n, err := s.exec(ctx, `UPDATE jobs SET lane = 'paid' WHERE id = ? AND status = 'queued' AND lane = 'free'`, id) return n == 1, err } + +// ActiveJobForKey returns the newest queued or running job for a cache +// key, which a second requester can share, or ErrNotFound. +func (s *Store) ActiveJobForKey(ctx context.Context, cacheKey string) (*Job, error) { + return scanJob(s.row(ctx, `SELECT `+jobCols+` FROM jobs + WHERE cache_key = ? AND status IN ('queued', 'running') ORDER BY id DESC LIMIT 1`, cacheKey)) +} + +// RaiseJob lifts a queued job to cover another requester: the caps become +// the looser of the two (0 means no cap) and the lane becomes paid when +// the newcomer pays. +func (s *Store) RaiseJob(ctx context.Context, id string, maxSize, maxDuration int64, lane string) (bool, error) { + n, err := s.exec(ctx, `UPDATE jobs SET + max_size = CASE WHEN max_size = 0 OR ? = 0 THEN 0 WHEN ? > max_size THEN ? ELSE max_size END, + max_duration = CASE WHEN max_duration = 0 OR ? = 0 THEN 0 WHEN ? > max_duration THEN ? ELSE max_duration END, + lane = CASE WHEN ? = 'paid' THEN 'paid' ELSE lane END + WHERE id = ? AND status = 'queued'`, + maxSize, maxSize, maxSize, maxDuration, maxDuration, maxDuration, lane, id) + return n == 1, err +} + +// RedownloadJob turns a job that could not be served from the cache or +// derived from a stored copy into a plain download and queues it. The +// attempt counter starts over: nothing was the job's fault. +func (s *Store) RedownloadJob(ctx context.Context, id string, from []string, now int64) (bool, error) { + ph, args := in(from) + all := append([]any{KindDownload, false, now, id}, args...) + n, err := s.exec(ctx, `UPDATE jobs SET status = 'queued', kind = ?, cache_hit = ?, source_key = '', + tg_file_id = '', storage_key = '', worker_id = '', lease_expires_at = 0, attempts = 0, stage = '', + progress_bytes = 0, total_bytes = 0, queued_at = ?, error_code = '', error_detail = '' + WHERE id = ? AND status IN (`+ph+`)`, all...) + return n == 1, err +} + +// SetJobFileID records the Telegram file_id a job's file got. +func (s *Store) SetJobFileID(ctx context.Context, id, fileID string) error { + _, err := s.exec(ctx, `UPDATE jobs SET tg_file_id = ? WHERE id = ?`, fileID, id) + return err +} + +// JobStorageKeys lists the storage keys still referenced by jobs that are +// not finished, so the orphan sweeper leaves them alone. +func (s *Store) JobStorageKeys(ctx context.Context) (map[string]bool, error) { + rows, err := s.rows(ctx, `SELECT id, storage_key, source_key FROM jobs + WHERE status IN ('queued', 'running', 'delivering')`) + if err != nil { + return nil, err + } + defer rows.Close() + out := map[string]bool{} + for rows.Next() { + var id, key, src string + if err := rows.Scan(&id, &key, &src); err != nil { + return nil, err + } + out["jobs/"+id+"/media"] = true + if key != "" { + out[key] = true + } + if src != "" { + out[src] = true + } + } + return out, rows.Err() +} diff --git a/internal/db/migrations/00003_cache.sql b/internal/db/migrations/00003_cache.sql new file mode 100644 index 0000000..f329947 --- /dev/null +++ b/internal/db/migrations/00003_cache.sql @@ -0,0 +1,75 @@ +-- +goose Up +-- The smart cache. One row per (bot, extractor, video, profile). +-- tg_file_id layer 1: resend instantly, valid for one bot token only +-- storage_key layer 2: stored copy, used for re-upload and transcoding +-- A row with status 'blocked' is a takedown: it has no file and stops the +-- key from being downloaded or cached again. +CREATE TABLE cache_entries ( + bot_id BIGINT NOT NULL, + extractor TEXT NOT NULL, + video_id TEXT NOT NULL, + profile TEXT NOT NULL, + tg_file_id TEXT NOT NULL DEFAULT '', + tg_file_unique_id TEXT NOT NULL DEFAULT '', + storage_key TEXT NOT NULL DEFAULT '', + size BIGINT NOT NULL DEFAULT 0, + duration BIGINT NOT NULL DEFAULT 0, + title TEXT NOT NULL DEFAULT '', + uploader TEXT NOT NULL DEFAULT '', + file_ext TEXT NOT NULL DEFAULT '', + width INTEGER NOT NULL DEFAULT 0, + height INTEGER NOT NULL DEFAULT 0, + hits BIGINT NOT NULL DEFAULT 0, + last_hit BIGINT NOT NULL DEFAULT 0, + expires_at BIGINT NOT NULL DEFAULT 0, + private BOOLEAN NOT NULL DEFAULT FALSE, + status TEXT NOT NULL DEFAULT 'ready', + created_at BIGINT NOT NULL, + PRIMARY KEY (bot_id, extractor, video_id, profile) +); +CREATE INDEX cache_expiry_idx ON cache_entries (status, expires_at); +CREATE INDEX cache_lru_idx ON cache_entries (status, last_hit); + +-- Owner blocklist: kind is 'site' (a host) or 'key' (extractor and video). +CREATE TABLE blocklist ( + kind TEXT NOT NULL, + value TEXT NOT NULL, + reason TEXT NOT NULL DEFAULT '', + created_by BIGINT NOT NULL DEFAULT 0, + created_at BIGINT NOT NULL, + PRIMARY KEY (kind, value) +); + +-- source_key: stored copy a derive job transcodes from. +-- tg_file_id: file_id a cache hit resends. +-- cacheable: whether the result may enter the cache. +-- cache_hit: the job was served from the cache and never saw a worker. +ALTER TABLE jobs ADD COLUMN source_key TEXT NOT NULL DEFAULT ''; +ALTER TABLE jobs ADD COLUMN tg_file_id TEXT NOT NULL DEFAULT ''; +ALTER TABLE jobs ADD COLUMN cacheable BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE jobs ADD COLUMN cache_hit BOOLEAN NOT NULL DEFAULT FALSE; +CREATE INDEX jobs_cache_key_idx ON jobs (cache_key, status); + +-- Each requester keeps their own caps, because several requesters with +-- different limits can share one job. +ALTER TABLE deliveries ADD COLUMN max_size BIGINT NOT NULL DEFAULT 0; +ALTER TABLE deliveries ADD COLUMN max_duration BIGINT NOT NULL DEFAULT 0; + +-- Playlist items are requests that wait their turn under a parent. +ALTER TABLE requests ADD COLUMN parent_id TEXT NOT NULL DEFAULT ''; +ALTER TABLE requests ADD COLUMN profile TEXT NOT NULL DEFAULT ''; +CREATE INDEX requests_waiting_idx ON requests (status, user_id, created_at); + +-- +goose Down +DROP INDEX requests_waiting_idx; +ALTER TABLE requests DROP COLUMN profile; +ALTER TABLE requests DROP COLUMN parent_id; +ALTER TABLE deliveries DROP COLUMN max_duration; +ALTER TABLE deliveries DROP COLUMN max_size; +DROP INDEX jobs_cache_key_idx; +ALTER TABLE jobs DROP COLUMN cache_hit; +ALTER TABLE jobs DROP COLUMN cacheable; +ALTER TABLE jobs DROP COLUMN tg_file_id; +ALTER TABLE jobs DROP COLUMN source_key; +DROP TABLE blocklist; +DROP TABLE cache_entries; diff --git a/internal/db/models.go b/internal/db/models.go index bb268e6..413d379 100644 --- a/internal/db/models.go +++ b/internal/db/models.go @@ -5,6 +5,8 @@ const ( RequestReady = "ready" // card shown, waiting for a format choice RequestChosen = "chosen" // a format was picked and a job exists RequestCancelled = "cancelled" // the requester dismissed the card + RequestWaiting = "waiting" // playlist item waiting for a free slot + RequestFailed = "failed" // playlist item that could not start ) // Job statuses. @@ -35,6 +37,20 @@ const ( // Job kinds. const ( KindDownload = "download" + // KindDerive transcodes a stored copy into a lower profile. + KindDerive = "derive" +) + +// Cache entry statuses. +const ( + CacheReady = "ready" + CacheBlocked = "blocked" // taken down: never download or cache again +) + +// Blocklist kinds. +const ( + BlockSite = "site" + BlockKey = "key" ) // User is a Telegram user known to the bot. @@ -67,6 +83,10 @@ type Request struct { Lang string CreatedAt int64 UpdatedAt int64 + // ParentID is the playlist request an item belongs to. + ParentID string + // Profile is the format chosen for a waiting playlist item. + Profile string } // Job is one unit of work for a worker. @@ -106,6 +126,14 @@ type Job struct { QueuedAt int64 StartedAt int64 FinishedAt int64 + // SourceKey is the stored copy a derive job transcodes from. + SourceKey string + // TgFileID is the Telegram file_id of the result, when known. + TgFileID string + // Cacheable says the result may be kept in the cache. + Cacheable bool + // CacheHit says the job was served from the cache without a worker. + CacheHit bool } // Active reports whether the job still needs a worker or the core. @@ -143,6 +171,34 @@ type Delivery struct { QuotaDay int // Released is true once charge and quota were given back. Released bool + // MaxSize and MaxDuration are this requester's own caps. Requesters + // who share a job can have different limits. + MaxSize int64 + MaxDuration int64 +} + +// CacheEntry is one cached result. +type CacheEntry struct { + BotID int64 + Extractor string + VideoID string + Profile string + TgFileID string + TgFileUniqueID string + StorageKey string + Size int64 + Duration int64 + Title string + Uploader string + FileExt string + Width int + Height int + Hits int64 + LastHit int64 + ExpiresAt int64 + Private bool + Status string + CreatedAt int64 } // Wallet owner types. diff --git a/internal/db/requests.go b/internal/db/requests.go index 83ecc12..1680801 100644 --- a/internal/db/requests.go +++ b/internal/db/requests.go @@ -3,12 +3,12 @@ package db import "context" const requestCols = `id, user_id, chat_id, chat_type, source_message_id, card_message_id, - card_is_photo, url, status, info, lang, created_at, updated_at` + card_is_photo, url, status, info, lang, created_at, updated_at, parent_id, profile` func scanRequest(sc interface{ Scan(...any) error }) (*Request, error) { var r Request err := sc.Scan(&r.ID, &r.UserID, &r.ChatID, &r.ChatType, &r.SourceMessageID, &r.CardMessageID, - &r.CardIsPhoto, &r.URL, &r.Status, &r.Info, &r.Lang, &r.CreatedAt, &r.UpdatedAt) + &r.CardIsPhoto, &r.URL, &r.Status, &r.Info, &r.Lang, &r.CreatedAt, &r.UpdatedAt, &r.ParentID, &r.Profile) if err != nil { return nil, notFound(err) } @@ -22,9 +22,9 @@ func (s *Store) InsertRequest(ctx context.Context, r *Request) error { } r.UpdatedAt = r.CreatedAt _, err := s.exec(ctx, `INSERT INTO requests (`+requestCols+`) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, r.ID, r.UserID, r.ChatID, r.ChatType, r.SourceMessageID, r.CardMessageID, - r.CardIsPhoto, r.URL, r.Status, r.Info, r.Lang, r.CreatedAt, r.UpdatedAt) + r.CardIsPhoto, r.URL, r.Status, r.Info, r.Lang, r.CreatedAt, r.UpdatedAt, r.ParentID, r.Profile) return err } @@ -48,3 +48,45 @@ func (s *Store) TransitionRequest(ctx context.Context, id, from, to string) (boo to, NowMilli(), id, from) return n == 1, err } + +// SetRequestInfo stores the metadata of a request. +func (s *Store) SetRequestInfo(ctx context.Context, id, info string) error { + _, err := s.exec(ctx, `UPDATE requests SET info = ?, updated_at = ? WHERE id = ?`, info, NowMilli(), id) + return err +} + +// WaitingRequests lists playlist items that have not started yet, oldest +// first, at most one per user so the pump stays fair. +func (s *Store) WaitingRequests(ctx context.Context, limit int) ([]*Request, error) { + rows, err := s.rows(ctx, `SELECT `+requestCols+` FROM requests r + WHERE status = 'waiting' AND id = ( + SELECT MIN(w.id) FROM requests w WHERE w.status = 'waiting' AND w.user_id = r.user_id + ) ORDER BY id LIMIT ?`, limit) + if err != nil { + return nil, err + } + defer rows.Close() + var out []*Request + for rows.Next() { + r, err := scanRequest(rows) + if err != nil { + return nil, err + } + out = append(out, r) + } + return out, rows.Err() +} + +// CancelWaitingRequests cancels a user's playlist items that have not +// started, and returns how many there were. +func (s *Store) CancelWaitingRequests(ctx context.Context, userID int64) (int64, error) { + return s.exec(ctx, `UPDATE requests SET status = 'cancelled', updated_at = ? + WHERE user_id = ? AND status = 'waiting'`, NowMilli(), userID) +} + +// CountWaitingRequests counts a user's playlist items that wait to start. +func (s *Store) CountWaitingRequests(ctx context.Context, userID int64) (int, error) { + var n int + err := s.row(ctx, `SELECT COUNT(*) FROM requests WHERE user_id = ? AND status = 'waiting'`, userID).Scan(&n) + return n, err +} diff --git a/internal/entitle/entitle.go b/internal/entitle/entitle.go index 2df0e55..8abebf4 100644 --- a/internal/entitle/entitle.go +++ b/internal/entitle/entitle.go @@ -40,6 +40,8 @@ type Limits struct { ActiveJobs int DailyDownloads int DailyBytes int64 + // PlaylistItems is how many items of one playlist link are fetched. + PlaylistItems int } // Wallet is the state of a wallet that matters for resolution. diff --git a/internal/ffmpeg/ffmpeg.go b/internal/ffmpeg/ffmpeg.go new file mode 100644 index 0000000..f5651b7 --- /dev/null +++ b/internal/ffmpeg/ffmpeg.go @@ -0,0 +1,126 @@ +// Package ffmpeg makes lower profiles and audio from a stored file, so a +// video that is already in the cache does not have to be downloaded again. +package ffmpeg + +import ( + "bytes" + "context" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "syscall" + "time" + + "github.com/noderunners/dlbot/internal/links" + "github.com/noderunners/dlbot/internal/media" + "github.com/noderunners/dlbot/internal/ytdlp" +) + +// Transcoder derives one profile from a source file. +type Transcoder interface { + // Derive writes the profile made from src into dir and describes it. + // Failures are returned as *ytdlp.Error. + Derive(ctx context.Context, src, dir string, profile media.Profile) (*ytdlp.Result, error) +} + +// Exec runs the real ffmpeg. +type Exec struct { + // Path of the ffmpeg binary. Defaults to "ffmpeg". ffprobe is expected + // next to it. + Path string + // Timeout bounds one transcode. Defaults to 30 minutes. + Timeout time.Duration +} + +var _ Transcoder = (*Exec)(nil) + +func (e *Exec) bin() string { + if e.Path == "" { + return "ffmpeg" + } + return e.Path +} + +func (e *Exec) probeBin() string { + if e.Path == "" || e.Path == "ffmpeg" { + return "ffprobe" + } + return filepath.Join(filepath.Dir(e.Path), "ffprobe") +} + +// Args returns the ffmpeg arguments for a profile and the output file +// name. It is exported for tests and the operations docs. +func Args(src, dir string, profile media.Profile) (args []string, out string, err error) { + base := []string{"-hide_banner", "-loglevel", "error", "-nostdin", "-y", "-i", src} + switch { + case profile == media.MP3: + out = filepath.Join(dir, "media.mp3") + return append(base, "-vn", "-c:a", "libmp3lame", "-b:a", "192k", out), out, nil + case profile == media.M4A: + out = filepath.Join(dir, "media.m4a") + return append(base, "-vn", "-c:a", "aac", "-b:a", "160k", "-movflags", "+faststart", out), out, nil + case profile.Height() > 0: + out = filepath.Join(dir, "media.mp4") + // Scale to the target height, keep the aspect ratio, and keep the + // width even, which h264 requires. + scale := "scale=-2:" + strconv.Itoa(profile.Height()) + return append(base, "-vf", scale, "-c:v", "libx264", "-preset", "veryfast", "-crf", "23", + "-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", out), out, nil + } + return nil, "", fmt.Errorf("ffmpeg: profile %q cannot be derived", profile) +} + +// Derive implements Transcoder. +func (e *Exec) Derive(ctx context.Context, src, dir string, profile media.Profile) (*ytdlp.Result, error) { + timeout := e.Timeout + if timeout <= 0 { + timeout = 30 * time.Minute + } + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + if err := os.MkdirAll(dir, 0o750); err != nil { + return nil, &ytdlp.Error{Code: ytdlp.CodeInternal, Retryable: true, Raw: err.Error()} + } + args, out, err := Args(src, dir, profile) + if err != nil { + return nil, &ytdlp.Error{Code: ytdlp.CodeProcessing, Raw: err.Error()} + } + cmd := exec.CommandContext(ctx, e.bin(), args...) + 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 + var stderr bytes.Buffer + cmd.Stderr = &stderr + runErr := cmd.Run() + if ctxErr := ctx.Err(); ctxErr != nil { + if errors.Is(ctxErr, context.DeadlineExceeded) { + return nil, &ytdlp.Error{Code: ytdlp.CodeTimeout, Retryable: true, Raw: "transcode timed out"} + } + return nil, &ytdlp.Error{Code: ytdlp.CodeCancelled, Raw: "transcode cancelled"} + } + if runErr != nil { + raw := strings.TrimSpace(stderr.String()) + if len(raw) > 600 { + raw = raw[len(raw)-600:] + } + return nil, &ytdlp.Error{Code: ytdlp.CodeProcessing, Raw: "ffmpeg: " + links.RedactText(raw)} + } + st, err := os.Stat(out) + if err != nil || st.Size() == 0 { + return nil, &ytdlp.Error{Code: ytdlp.CodeProcessing, Raw: "ffmpeg produced no output"} + } + res := &ytdlp.Result{Path: out, Size: st.Size(), Ext: strings.TrimPrefix(filepath.Ext(out), ".")} + if d, w, h, err := ytdlp.FileInfo(ctx, e.probeBin(), out); err == nil { + res.Duration, res.Width, res.Height = d, w, h + } + return res, nil +} diff --git a/internal/ffmpeg/ffmpeg_test.go b/internal/ffmpeg/ffmpeg_test.go new file mode 100644 index 0000000..c33f9ab --- /dev/null +++ b/internal/ffmpeg/ffmpeg_test.go @@ -0,0 +1,93 @@ +package ffmpeg + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/noderunners/dlbot/internal/media" + "github.com/noderunners/dlbot/internal/ytdlp" +) + +func TestArgs(t *testing.T) { + tests := map[media.Profile]struct{ want, out string }{ + media.P480: {"-vf scale=-2:480 -c:v libx264 -preset veryfast -crf 23 -c:a aac -b:a 128k -movflags +faststart", "media.mp4"}, + media.P720: {"-vf scale=-2:720", "media.mp4"}, + media.MP3: {"-vn -c:a libmp3lame -b:a 192k", "media.mp3"}, + media.M4A: {"-vn -c:a aac -b:a 160k -movflags +faststart", "media.m4a"}, + } + for p, tc := range tests { + args, out, err := Args("/src/in", "/dst", p) + if err != nil { + t.Errorf("%s: %v", p, err) + continue + } + joined := strings.Join(args, " ") + if !strings.Contains(joined, tc.want) || out != filepath.Join("/dst", tc.out) || args[len(args)-1] != out { + t.Errorf("%s: args = %q, out = %q", p, joined, out) + } + if !strings.Contains(joined, "-i /src/in") || !strings.Contains(joined, "-nostdin") { + t.Errorf("%s: input or -nostdin missing: %q", p, joined) + } + } + // Profiles that are not made by transcoding. + for _, p := range []media.Profile{media.Best, media.Thumb, media.Subs("en")} { + if _, _, err := Args("in", "out", p); err == nil { + t.Errorf("%s must not be derivable", p) + } + } +} + +// TestDeriveWithRealFfmpeg makes a two second 720p test clip and derives +// 480p and MP3 from it. It is skipped when ffmpeg is not installed. +func TestDeriveWithRealFfmpeg(t *testing.T) { + if _, err := exec.LookPath("ffmpeg"); err != nil { + t.Skip("ffmpeg is not installed") + } + dir := t.TempDir() + src := filepath.Join(dir, "source.mp4") + gen := exec.Command("ffmpeg", "-hide_banner", "-loglevel", "error", "-y", + "-f", "lavfi", "-i", "testsrc=duration=2:size=1280x720:rate=15", + "-f", "lavfi", "-i", "sine=frequency=440:duration=2", + "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", src) + if out, err := gen.CombinedOutput(); err != nil { + t.Skipf("cannot generate a test clip with this ffmpeg build: %v %s", err, out) + } + e := &Exec{Timeout: time.Minute} + ctx := context.Background() + + video, err := e.Derive(ctx, src, filepath.Join(dir, "v"), media.P480) + if err != nil { + t.Fatalf("derive 480: %v", err) + } + if video.Ext != "mp4" || video.Height != 480 || video.Width != 854 || video.Size == 0 || + video.Duration < 1.5 || video.Duration > 2.6 { + t.Fatalf("480p result = %+v", video) + } + audio, err := e.Derive(ctx, src, filepath.Join(dir, "a"), media.MP3) + if err != nil { + t.Fatalf("derive mp3: %v", err) + } + if audio.Ext != "mp3" || audio.Size == 0 || audio.Width != 0 || audio.Duration < 1.5 { + t.Fatalf("mp3 result = %+v", audio) + } + + // A source that is not media gives a classified error, not a crash. + bad := filepath.Join(dir, "bad.mp4") + if err := os.WriteFile(bad, []byte("this is not a video"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := e.Derive(ctx, bad, filepath.Join(dir, "b"), media.P480); ytdlp.CodeOf(err) != ytdlp.CodeProcessing { + t.Fatalf("bad source: %v, want processing_failed", err) + } + // Cancelling stops ffmpeg. + cctx, cancel := context.WithCancel(ctx) + cancel() + if _, err := e.Derive(cctx, src, filepath.Join(dir, "c"), media.P480); ytdlp.CodeOf(err) != ytdlp.CodeCancelled { + t.Fatalf("cancelled derive: %v, want cancelled", err) + } +} diff --git a/internal/ids/ids.go b/internal/ids/ids.go index 621d905..338980d 100644 --- a/internal/ids/ids.go +++ b/internal/ids/ids.go @@ -53,3 +53,7 @@ func Valid(s string) bool { } return true } + +// NewAt returns an identifier stamped with the given time. A batch that +// must keep its order gets increasing times. +func NewAt(t time.Time) string { return newAt(t) } diff --git a/internal/sched/local.go b/internal/sched/local.go index c7b6f51..fa4a4f3 100644 --- a/internal/sched/local.go +++ b/internal/sched/local.go @@ -3,6 +3,7 @@ package sched import ( "context" "errors" + "io" "os" "time" @@ -63,6 +64,24 @@ func (l *Local) Upload(ctx context.Context, job *workerproto.Job, path string) e return l.Storage.Put(ctx, job.UploadKey, f, st.Size()) } +// Fetch copies a stored source file to a local path, for derive jobs. +func (l *Local) Fetch(ctx context.Context, job *workerproto.Job, path string) error { + rc, _, err := l.Storage.Open(ctx, job.SourceKey) + if err != nil { + return err + } + defer rc.Close() + f, err := os.Create(path) + if err != nil { + return err + } + if _, err := io.Copy(f, rc); err != nil { + f.Close() + return err + } + return f.Close() +} + // leaseError marks ErrLeaseLost for the worker package, which cannot import // this one. type leaseError struct{ error } diff --git a/internal/sched/sched.go b/internal/sched/sched.go index 77e6775..addb726 100644 --- a/internal/sched/sched.go +++ b/internal/sched/sched.go @@ -168,6 +168,32 @@ type EnqueueParams struct { WalletID string ChargeSats int64 QuotaDay int + + // Kind is the job kind, download by default. + Kind string + // CacheKey identifies the result, so a second requester for the same + // result can share the job. + CacheKey string + // Cacheable says the result may be kept in the cache. + Cacheable bool + // SourceKey is the stored copy a derive job transcodes from. + SourceKey string + // Hit, when set, makes the job a cache hit: it is created already + // finished and never waits for a worker. + Hit *CacheHit +} + +// CacheHit describes a cached result a job is served from. +type CacheHit struct { + StorageKey string + TgFileID string + FileExt string + FileSize int64 + Duration int64 + Width int + Height int + Title string + Uploader string } // Enqueue adds a job with one delivery in its own transaction. @@ -198,13 +224,19 @@ func (s *Scheduler) EnqueueTx(ctx context.Context, tx *db.Store, p EnqueueParams if p.Lane == "" { p.Lane = db.LaneFree } + if p.Kind == "" { + p.Kind = db.KindDownload + } job := &db.Job{ ID: ids.New(), - Kind: db.KindDownload, + Kind: p.Kind, URL: p.URL, Extractor: p.Extractor, VideoID: p.VideoID, Profile: p.Profile, + CacheKey: p.CacheKey, + Cacheable: p.Cacheable, + SourceKey: p.SourceKey, Status: db.JobQueued, Lane: p.Lane, Priority: p.Priority, @@ -216,24 +248,22 @@ func (s *Scheduler) EnqueueTx(ctx context.Context, tx *db.Store, p EnqueueParams CreatedAt: now, QueuedAt: now, } - del := &db.Delivery{ - ID: ids.New(), - JobID: job.ID, - RequestID: p.RequestID, - UserID: p.UserID, - ChatID: p.ChatID, - ChatType: p.ChatType, - ReplyToMessageID: p.ReplyToMessageID, - StatusMessageID: p.StatusMessageID, - StatusIsPhoto: p.StatusIsPhoto, - Lang: p.Lang, - Status: db.DeliveryPending, - CreatedAt: now, - Source: p.Source, - WalletID: p.WalletID, - ChargeSats: p.ChargeSats, - QuotaDay: p.QuotaDay, + if h := p.Hit; h != nil { + // Served from the cache: the result exists, so the job starts in + // the state a worker would have left it in. + job.Status = db.JobDelivering + job.CacheHit = true + job.StorageKey, job.TgFileID, job.FileExt = h.StorageKey, h.TgFileID, h.FileExt + job.FileSize, job.Duration, job.Width, job.Height = h.FileSize, h.Duration, h.Width, h.Height + if h.Title != "" { + job.Title = h.Title + } + if h.Uploader != "" { + job.Uploader = h.Uploader + } + job.StartedAt, job.FinishedAt = now, now } + del := s.newDelivery(job.ID, p, now) if p.ActiveLimit > 0 { n, err := tx.CountActiveDeliveries(ctx, p.UserID) if err != nil { @@ -261,14 +291,104 @@ func (s *Scheduler) EnqueueTx(ctx context.Context, tx *db.Store, p EnqueueParams return job, del, nil } +func (s *Scheduler) newDelivery(jobID string, p EnqueueParams, now int64) *db.Delivery { + return &db.Delivery{ + ID: ids.New(), + JobID: jobID, + RequestID: p.RequestID, + UserID: p.UserID, + ChatID: p.ChatID, + ChatType: p.ChatType, + ReplyToMessageID: p.ReplyToMessageID, + StatusMessageID: p.StatusMessageID, + StatusIsPhoto: p.StatusIsPhoto, + Lang: p.Lang, + Status: db.DeliveryPending, + CreatedAt: now, + Source: p.Source, + WalletID: p.WalletID, + ChargeSats: p.ChargeSats, + QuotaDay: p.QuotaDay, + MaxSize: p.MaxSize, + MaxDuration: p.MaxDuration, + } +} + +// covers reports whether a job cap is at least as loose as a requester's +// cap, where 0 means "no cap". +func covers(jobCap, myCap int64) bool { + return jobCap == 0 || (myCap != 0 && jobCap >= myCap) +} + +// AttachTx adds a requester to a job that is already queued or running +// for the same result, so the file is fetched once and everyone is +// notified when it is done. It reports false when the job cannot be +// shared: a running job was started under tighter caps than this +// requester has, and would fail or fall short for them. +// +// A queued job is lifted instead: its caps become the looser of the two +// and it moves to the paid lane when the newcomer pays, which also speeds +// it up for whoever asked first. +func (s *Scheduler) AttachTx(ctx context.Context, tx *db.Store, job *db.Job, p EnqueueParams) (*db.Delivery, bool, error) { + if p.ActiveLimit > 0 { + n, err := tx.CountActiveDeliveries(ctx, p.UserID) + if err != nil { + return nil, false, err + } + if n >= p.ActiveLimit { + return nil, false, ErrTooManyActive + } + } + shared := covers(job.MaxSize, p.MaxSize) && covers(job.MaxDuration, p.MaxDuration) + if job.Status == db.JobQueued { + raised, err := tx.RaiseJob(ctx, job.ID, p.MaxSize, p.MaxDuration, p.Lane) + if err != nil { + return nil, false, err + } + shared = shared || raised + } + if !shared { + return nil, false, nil + } + del := s.newDelivery(job.ID, p, s.now()) + if err := tx.InsertDelivery(ctx, del); err != nil { + return nil, false, err + } + return del, true, nil +} + // Announce tells listeners and waiting workers about a committed job. func (s *Scheduler) Announce(job *db.Job, del *db.Delivery) { s.log.Info("job queued", "job_id", job.ID, "delivery_id", del.ID, "user_id", del.UserID, - "profile", job.Profile, "lane", job.Lane, "source", del.Source) + "profile", job.Profile, "lane", job.Lane, "source", del.Source, "kind", job.Kind, "cache_hit", job.CacheHit) + if job.CacheHit { + s.emit(EventStored, job.ID) // nothing to wait for: deliver now + return + } s.emit(EventQueued, job.ID) s.notifyWork() } +// AnnounceAttached tells listeners that a requester joined a job. +func (s *Scheduler) AnnounceAttached(job *db.Job, del *db.Delivery) { + s.log.Info("requester attached to job", "job_id", job.ID, "delivery_id", del.ID, "user_id", del.UserID) + s.emit(EventRequeued, job.ID) // refreshes status messages + s.notifyWork() +} + +// Redownload turns a job that was meant to be served from the cache into +// a plain download, when the cached file turned out to be unusable. +func (s *Scheduler) Redownload(ctx context.Context, jobID string) (bool, error) { + ok, err := s.store.RedownloadJob(ctx, jobID, []string{db.JobDelivering}, s.now()) + if err != nil || !ok { + return false, err + } + s.log.Info("cached file unusable, downloading again", "job_id", jobID) + s.emit(EventRequeued, jobID) + s.notifyWork() + return true, nil +} + // Claim order: paid jobs first, then free. var ( allLanes = []string{db.LanePaid, db.LaneFree} @@ -367,6 +487,7 @@ func (s *Scheduler) Claim(ctx context.Context, req workerproto.ClaimRequest) (*w Profile: job.Profile, MaxSize: job.MaxSize, MaxDuration: job.MaxDuration, + SourceKey: job.SourceKey, UploadKey: UploadKey(job.ID), Attempt: job.Attempts, LeaseSeconds: int(s.cfg.Lease.Seconds()), @@ -474,6 +595,11 @@ func (s *Scheduler) Fail(ctx context.Context, req workerproto.FailRequest) error ev = EventCancelled _, err = tx.FinishJob(ctx, job.ID, db.JobCancelled, string(ytdlp.CodeCancelled), req.Detail, []string{db.JobRunning}, s.now()) + case job.Kind == db.KindDerive && req.Code != string(ytdlp.CodeWorkerLost): + // Transcoding from the stored copy did not work. Downloading + // the profile directly is the fallback, at no cost in attempts. + ev = EventRequeued + _, err = tx.RedownloadJob(ctx, job.ID, []string{db.JobRunning}, s.now()) case req.Retryable && req.Code == string(ytdlp.CodeWorkerLost): // A clean worker shutdown is not the job's fault: hand it to // another worker without spending an attempt. diff --git a/internal/service/service.go b/internal/service/service.go index d5c4c94..3e57c1f 100644 --- a/internal/service/service.go +++ b/internal/service/service.go @@ -9,9 +9,11 @@ import ( "errors" "log/slog" "math" + "strings" "time" "github.com/noderunners/dlbot/internal/billing" + "github.com/noderunners/dlbot/internal/cache" "github.com/noderunners/dlbot/internal/config" "github.com/noderunners/dlbot/internal/db" "github.com/noderunners/dlbot/internal/entitle" @@ -38,6 +40,47 @@ type CardInfo struct { // Sizes maps a profile to its estimated size in bytes. Profiles with an // unknown size are absent. Sizes map[string]int64 `json:"sizes,omitempty"` + // Availability is yt-dlp's access class ("public", "private", ...). + // Anything that is not public or unlisted is never cached. + Availability string `json:"availability,omitempty"` + // SubLangs are the subtitle languages, written ones before automatic. + SubLangs []string `json:"sub_langs,omitempty"` + AutoSubLangs []string `json:"auto_sub_langs,omitempty"` + // Fresh asks to skip the cache and download again. + Fresh bool `json:"fresh,omitempty"` +} + +// Playlist is a link that resolved to a list of items. +type Playlist struct { + Title string `json:"title"` + Entries []PlaylistEntry `json:"entries"` +} + +// PlaylistEntry is one item of a playlist. +type PlaylistEntry struct { + URL string `json:"url"` + Title string `json:"title,omitempty"` +} + +// JSON encodes the playlist for storage. +func (p *Playlist) JSON() string { + b, _ := json.Marshal(p) + return string(b) +} + +// ParsePlaylist decodes a stored playlist. +func ParsePlaylist(s string) (*Playlist, error) { + var p Playlist + if err := json.Unmarshal([]byte(s), &p); err != nil { + return nil, err + } + return &p, nil +} + +// Probed is the result of looking up a link: one item or a playlist. +type Probed struct { + Info *CardInfo `json:"info,omitempty"` + Playlist *Playlist `json:"playlist,omitempty"` } // JSON encodes the info for storage. @@ -72,6 +115,8 @@ func cardInfo(url string, info *ytdlp.Info) *CardInfo { Live: info.Live(), Sizes: map[string]int64{}, } + c.Availability = info.Availability + c.SubLangs, c.AutoSubLangs = info.SubtitleLangs() if c.Title == "" { c.Title = info.ID } @@ -107,6 +152,9 @@ const ( LimitQueueFull = "queue_full" LimitDailyDownloads = "daily_downloads" LimitDailyVolume = "daily_volume" + // LimitBlocked is a takedown by the owner: the video or its site is on + // the blocklist. + LimitBlocked = "blocked" ) // ErrPlaylist is returned by Probe for links that resolve to a list. @@ -118,6 +166,7 @@ type Service struct { store *db.Store sched *sched.Scheduler billing *billing.Billing + cache *cache.Cache runner ytdlp.Runner log *slog.Logger probes chan struct{} @@ -125,13 +174,13 @@ type Service struct { } // New creates the service. -func New(cfg config.Config, store *db.Store, sch *sched.Scheduler, bill *billing.Billing, runner ytdlp.Runner, log *slog.Logger) *Service { +func New(cfg config.Config, store *db.Store, sch *sched.Scheduler, bill *billing.Billing, ch *cache.Cache, runner ytdlp.Runner, log *slog.Logger) *Service { n := cfg.Worker.ProbeConcurrency if n < 1 { n = 1 } return &Service{ - cfg: cfg, store: store, sched: sch, billing: bill, runner: runner, log: log, + cfg: cfg, store: store, sched: sch, billing: bill, cache: ch, runner: runner, log: log, probes: make(chan struct{}, n), now: time.Now, } } @@ -139,9 +188,30 @@ func New(cfg config.Config, store *db.Store, sch *sched.Scheduler, bill *billing // SetClock replaces the time source, for tests. func (s *Service) SetClock(now func() time.Time) { s.now = now } -// Probe looks up the metadata of a link. Lookups are limited to a few at a -// time so a burst of links cannot start dozens of yt-dlp processes. +// Probe looks up the metadata of a single item. A link that turns out to +// be a playlist gives ErrPlaylist; use ProbeAny to handle both. func (s *Service) Probe(ctx context.Context, url string) (*CardInfo, error) { + p, err := s.ProbeAny(ctx, url) + if err != nil { + return nil, err + } + if p.Info == nil { + return nil, ErrPlaylist + } + return p.Info, nil +} + +// ProbeAny looks up a link, which may be one item or a playlist. Results +// are remembered for a while, so a link that was just seen answers at +// once. Lookups are limited to a few at a time so a burst of links cannot +// start dozens of yt-dlp processes. +func (s *Service) ProbeAny(ctx context.Context, url string) (*Probed, error) { + if raw, ok := s.cache.MetaGet(url); ok { + var p Probed + if json.Unmarshal([]byte(raw), &p) == nil && (p.Info != nil || p.Playlist != nil) { + return &p, nil + } + } select { case s.probes <- struct{}{}: defer func() { <-s.probes }() @@ -156,10 +226,24 @@ func (s *Service) Probe(ctx context.Context, url string) (*CardInfo, error) { } return nil, err } + p := &Probed{} if info.IsPlaylist() { - return nil, ErrPlaylist + pl := &Playlist{Title: info.Title} + for _, e := range info.Entries { + // Flat listings sometimes carry bare IDs. Only real links are + // usable as separate downloads. + if u, err := links.Normalize(e.URL); err == nil && strings.Contains(e.URL, "://") { + pl.Entries = append(pl.Entries, PlaylistEntry{URL: u, Title: e.Title}) + } + } + p.Playlist = pl + } else { + p.Info = cardInfo(url, info) } - return cardInfo(url, info), nil + if raw, err := json.Marshal(p); err == nil { + s.cache.MetaPut(url, string(raw)) + } + return p, nil } // tier converts a configured tier to resolver limits. @@ -170,6 +254,7 @@ func tier(t config.Tier) entitle.Limits { ActiveJobs: t.ActiveJobs, DailyDownloads: t.DailyDownloads, DailyBytes: t.DailyMB << 20, + PlaylistItems: t.PlaylistItems, } } @@ -256,7 +341,7 @@ func (s *Service) admit(ctx context.Context, who Who, info *CardInfo, profile me func (s *Service) limitError(code string, info *CardInfo, profile media.Profile, dec entitle.Decision) *LimitError { le := &LimitError{Code: code, Decision: dec, Size: info.Sizes[string(profile)]} - if code == LimitLive || code == LimitQueueFull || dec.Source.Paid() || !s.billing.Enabled() { + if code == LimitLive || code == LimitQueueFull || code == LimitBlocked || dec.Source.Paid() || !s.billing.Enabled() { return le } // Would the paid tier accept it? Only then is it worth offering. @@ -268,15 +353,72 @@ func (s *Service) limitError(code string, info *CardInfo, profile media.Profile, return le } +// resolved is what a request maps to before admission: the canonical +// cache key and, when the cache can serve it, the entry to serve from. +type resolved struct { + extractor string + videoID string + cacheable bool + // hit is a cached result that answers the request as is. + hit *db.CacheEntry + // source is a stored higher profile to transcode from. + source *db.CacheEntry + // view is the metadata admission judges. For a hit it carries the real + // size and duration of the cached file instead of estimates. + view *CardInfo +} + +// resolve finds the cache key of a request and what the cache has for it. +// It refuses content the owner took down. +func (s *Service) resolve(ctx context.Context, url string, info *CardInfo, profile media.Profile, dec entitle.Decision) (*resolved, error) { + r := &resolved{view: info} + r.extractor, r.videoID = cache.Canonical(info.Extractor, info.VideoID, url) + blocked, err := s.cache.Blocked(ctx, r.extractor, r.videoID, info.Site) + if err != nil { + return nil, err + } + if blocked { + return nil, &LimitError{Code: LimitBlocked, Decision: dec} + } + r.cacheable = s.cache.Enabled() && cache.Cacheable(info.Availability, info.Live) + if !r.cacheable || info.Fresh { + return r, nil + } + if r.hit, err = s.cache.Lookup(ctx, r.extractor, r.videoID, profile); err != nil { + return nil, err + } + if r.hit == nil { + if r.hit, r.source, err = s.cache.Related(ctx, r.extractor, r.videoID, profile); err != nil { + return nil, err + } + } + if r.hit != nil { + // Judge the request by the real file. This is what keeps the cache + // from bypassing limits: a file somebody with a pass put in the + // cache is still too large for a free user, and says so here. + view := *info + view.Sizes = map[string]int64{string(profile): r.hit.Size} + if r.hit.Duration > 0 { + view.Duration = r.hit.Duration + } + r.view = &view + } + return r, nil +} + // Preview reports whether a download would be accepted right now, without // queueing or charging anything. It returns *LimitError when a rule would // refuse it. -func (s *Service) Preview(ctx context.Context, who Who, info *CardInfo, profile media.Profile) error { +func (s *Service) Preview(ctx context.Context, who Who, url string, info *CardInfo, profile media.Profile) error { dec, err := s.Entitlement(ctx, who, false) if err != nil { return err } - return s.admit(ctx, who, info, profile, dec) + r, err := s.resolve(ctx, url, info, profile, dec) + if err != nil { + return err + } + return s.admit(ctx, who, r.view, profile, dec) } // StartParams describes a download a requester asked for. @@ -292,8 +434,13 @@ type StartParams struct { } // Start resolves the entitlement, checks every limit, charges the wallet -// when credits pay, and queues the download. Charge, quota and job are -// written in one transaction. It returns *LimitError when a rule refuses. +// when credits pay, and gets the file on its way: from the cache when it +// is there, by joining a download that is already running for the same +// result, by transcoding a stored copy, or by a fresh download. +// +// Whichever of those it is, the request passes the same admission and +// costs the same. Charge, quota and job are written in one transaction. +// It returns *LimitError when a rule refuses. func (s *Service) Start(ctx context.Context, p StartParams) (*db.Job, *db.Delivery, error) { who := Who{UserID: p.Request.UserID, ChatID: p.Request.ChatID, ChatType: p.Request.ChatType} // A wallet changing under us (two downloads racing for the last @@ -313,14 +460,20 @@ func (s *Service) startOnce(ctx context.Context, who Who, p StartParams) (*db.Jo if err != nil { return nil, nil, err } - if err := s.admit(ctx, who, p.Info, p.Profile, dec); err != nil { + r, err := s.resolve(ctx, p.Request.URL, p.Info, p.Profile, dec) + if err != nil { + return nil, nil, err + } + // One gate for everything. A cache hit is admitted exactly like a + // fresh download; it only skips the worker afterwards. + if err := s.admit(ctx, who, r.view, p.Profile, dec); err != nil { return nil, nil, err } day := Day(s.now()) params := sched.EnqueueParams{ URL: p.Request.URL, - Extractor: p.Info.Extractor, - VideoID: p.Info.VideoID, + Extractor: r.extractor, + VideoID: r.videoID, Profile: string(p.Profile), Title: p.Info.Title, Uploader: p.Info.Uploader, @@ -341,6 +494,8 @@ func (s *Service) startOnce(ctx context.Context, who Who, p StartParams) (*db.Jo WalletID: dec.WalletID, ChargeSats: dec.Charge, QuotaDay: day, + CacheKey: cache.JobKey(r.extractor, r.videoID, string(p.Profile)), + Cacheable: r.cacheable, } if p.OneOff != nil { // Prepaid by invoice. Remember the amount and the payer's wallet so @@ -352,14 +507,46 @@ func (s *Service) startOnce(ctx context.Context, who Who, p StartParams) (*db.Jo params.WalletID = w.ID params.ChargeSats = p.OneOff.AmountSats } + switch { + case r.hit != nil: + params.Hit = &sched.CacheHit{ + StorageKey: r.hit.StorageKey, TgFileID: r.hit.TgFileID, FileExt: r.hit.FileExt, + FileSize: r.hit.Size, Duration: r.hit.Duration, Width: r.hit.Width, Height: r.hit.Height, + Title: r.hit.Title, Uploader: r.hit.Uploader, + } + case r.source != nil: + params.Kind = db.KindDerive + params.SourceKey = r.source.StorageKey + } var ( - job *db.Job - del *db.Delivery + job *db.Job + del *db.Delivery + attached bool ) err = s.store.InTx(ctx, func(tx *db.Store) error { - var err error - if job, del, err = s.sched.EnqueueTx(ctx, tx, params); err != nil { - return err + job, del, attached = nil, nil, false + // Singleflight: the same result is already on its way for somebody + // else, so wait for that instead of fetching it twice. + if r.hit == nil && r.cacheable && !p.Info.Fresh { + active, err := tx.ActiveJobForKey(ctx, params.CacheKey) + if err != nil && !errors.Is(err, db.ErrNotFound) { + return err + } + if active != nil { + d, ok, err := s.sched.AttachTx(ctx, tx, active, params) + if err != nil { + return err + } + if ok { + job, del, attached = active, d, true + } + } + } + if !attached { + var err error + if job, del, err = s.sched.EnqueueTx(ctx, tx, params); err != nil { + return err + } } if dec.Charge > 0 { if _, err := tx.AddLedger(ctx, &db.LedgerEntry{ @@ -379,7 +566,17 @@ func (s *Service) startOnce(ctx context.Context, who Who, p StartParams) (*db.Jo case err != nil: return nil, nil, err } - s.sched.Announce(job, del) + switch { + case r.hit != nil: + s.cache.RecordHit(ctx, r.hit) + case r.cacheable: + s.cache.RecordMiss() + } + if attached { + s.sched.AnnounceAttached(job, del) + } else { + s.sched.Announce(job, del) + } return job, del, nil } diff --git a/internal/tg/api.go b/internal/tg/api.go index a9f58c0..b84f016 100644 --- a/internal/tg/api.go +++ b/internal/tg/api.go @@ -113,3 +113,22 @@ func RetryAfter(err error) time.Duration { } return 0 } + +// IsBadFileID reports that Telegram no longer accepts a file_id: it was +// issued for another bot, the file was removed, or the reference expired. +// The cache treats this as "layer 1 is gone" and falls back. +func IsBadFileID(err error) bool { + if ErrorCode(err) != 400 { + return false + } + d := Description(err) + for _, needle := range []string{ + "wrong file identifier", "wrong remote file", "file reference", "invalid file", + "wrong file_id", "file_id", "wrong type of the web page content", "file is temporarily unavailable", + } { + if strings.Contains(d, needle) { + return true + } + } + return false +} diff --git a/internal/worker/worker.go b/internal/worker/worker.go index b955d61..c3c60cb 100644 --- a/internal/worker/worker.go +++ b/internal/worker/worker.go @@ -14,6 +14,7 @@ import ( "sync/atomic" "time" + "github.com/noderunners/dlbot/internal/ffmpeg" "github.com/noderunners/dlbot/internal/ids" "github.com/noderunners/dlbot/internal/media" "github.com/noderunners/dlbot/internal/workerproto" @@ -29,6 +30,9 @@ type Coordinator interface { Fail(ctx context.Context, req workerproto.FailRequest) error // Upload stores the finished file under the job's upload key. Upload(ctx context.Context, job *workerproto.Job, path string) error + // Fetch copies the job's source file from storage to a local path. + // It is only used by derive jobs. + Fetch(ctx context.Context, job *workerproto.Job, path string) error } // Config holds the worker settings. @@ -48,10 +52,15 @@ type Worker struct { cfg Config coord Coordinator runner ytdlp.Runner + trans ffmpeg.Transcoder log *slog.Logger active atomic.Int32 } +// SetTranscoder gives the worker the means to run derive jobs. Without it +// a derive job fails and the core falls back to a plain download. +func (w *Worker) SetTranscoder(t ffmpeg.Transcoder) { w.trans = t } + // New creates a worker. func New(cfg Config, coord Coordinator, runner ytdlp.Runner, log *slog.Logger) *Worker { if cfg.Concurrency < 1 { @@ -213,9 +222,12 @@ func (w *Worker) process(ctx context.Context, job *workerproto.Job) { res *ytdlp.Result err error ) - if perr != nil { + switch { + case perr != nil: err = &ytdlp.Error{Code: ytdlp.CodeInternal, Raw: perr.Error()} - } else { + case job.Kind == workerproto.KindDerive: + res, err = w.derive(jobCtx, job, dir, profile, setStage) + default: res, err = w.runner.Download(jobCtx, ytdlp.DownloadRequest{ URL: job.URL, Profile: profile, @@ -241,6 +253,12 @@ func (w *Worker) process(ctx context.Context, job *workerproto.Job) { } } } + // The file is in storage (or the job failed): the local copy has no + // further use. Removing it now, before the outcome is reported, frees + // the disk as early as possible. + if rmErr := os.RemoveAll(dir); rmErr != nil { + log.Warn("cannot remove temp dir", "err", rmErr) + } stopHeartbeat() // Outcome reports must go out even when the worker is shutting down. @@ -291,6 +309,32 @@ func (w *Worker) process(ctx context.Context, job *workerproto.Job) { })) } +// derive transcodes the job's stored source into the requested profile. +func (w *Worker) derive(ctx context.Context, job *workerproto.Job, dir string, profile media.Profile, setStage func(string)) (*ytdlp.Result, error) { + if w.trans == nil { + return nil, &ytdlp.Error{Code: ytdlp.CodeProcessing, Raw: "this worker has no transcoder"} + } + if err := os.MkdirAll(dir, 0o750); err != nil { + return nil, &ytdlp.Error{Code: ytdlp.CodeInternal, Retryable: true, Raw: err.Error()} + } + src := filepath.Join(dir, "source") + if err := w.coord.Fetch(ctx, job, src); err != nil { + if ctx.Err() != nil { + return nil, &ytdlp.Error{Code: ytdlp.CodeCancelled, Raw: "cancelled"} + } + return nil, &ytdlp.Error{Code: ytdlp.CodeProcessing, Raw: "fetch source: " + err.Error()} + } + setStage(ytdlp.StageProcessing) + res, err := w.trans.Derive(ctx, src, filepath.Join(dir, "out"), profile) + if err != nil { + return nil, err + } + if job.MaxSize > 0 && res.Size > job.MaxSize { + return nil, &ytdlp.Error{Code: ytdlp.CodeTooLarge, Raw: "derived file is over the cap"} + } + return res, nil +} + func (w *Worker) report(log *slog.Logger, err error) { if err != nil && !isLeaseLost(err) { log.Error("cannot report job outcome", "err", err) diff --git a/internal/workerproto/proto.go b/internal/workerproto/proto.go index fd50423..754ac59 100644 --- a/internal/workerproto/proto.go +++ b/internal/workerproto/proto.go @@ -3,6 +3,13 @@ // workers send the same structures as JSON over HTTPS. package workerproto +// Job kinds. +const ( + KindDownload = "download" + // KindDerive transcodes SourceKey into Profile. + KindDerive = "derive" +) + // ClaimRequest asks the core for one job. type ClaimRequest struct { WorkerID string `json:"worker_id"` @@ -25,6 +32,9 @@ type Job struct { // must fail the job instead of delivering a file over a cap. MaxSize int64 `json:"max_size"` MaxDuration int64 `json:"max_duration"` + // SourceKey is set for derive jobs: the stored file to transcode into + // Profile instead of downloading from URL. + SourceKey string `json:"source_key,omitempty"` // UploadKey is the storage key the result must be uploaded to. UploadKey string `json:"upload_key"` Attempt int `json:"attempt"` diff --git a/internal/ytdlp/exec.go b/internal/ytdlp/exec.go index 20f2094..82fe48f 100644 --- a/internal/ytdlp/exec.go +++ b/internal/ytdlp/exec.go @@ -393,9 +393,19 @@ type probed struct { } func (e *Exec) ffprobe(ctx context.Context, path string) (probed, error) { + return ffprobe(ctx, e.ffprobeBin(), path) +} + +// FileInfo reads duration and picture size of a media file with ffprobe. +func FileInfo(ctx context.Context, ffprobePath, path string) (duration float64, width, height int, err error) { + p, err := ffprobe(ctx, ffprobePath, path) + return p.duration, p.width, p.height, err +} + +func ffprobe(ctx context.Context, bin, path string) (probed, error) { ctx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() - out, err := exec.CommandContext(ctx, e.ffprobeBin(), "-v", "error", + out, err := exec.CommandContext(ctx, bin, "-v", "error", "-show_entries", "format=duration:stream=codec_type,width,height", "-of", "json", path).Output() if err != nil { diff --git a/internal/ytdlp/ytdlptest/fake.go b/internal/ytdlp/ytdlptest/fake.go index 778afbd..1b802e8 100644 --- a/internal/ytdlp/ytdlptest/fake.go +++ b/internal/ytdlp/ytdlptest/fake.go @@ -3,6 +3,8 @@ package ytdlptest import ( "context" + "crypto/sha256" + "encoding/hex" "os" "path/filepath" "sync" @@ -37,10 +39,12 @@ type Fake struct { var _ ytdlp.Runner = (*Fake)(nil) // DefaultInfo is the metadata returned for URLs without an explicit entry. +// Every URL is its own video: the ID is derived from the URL. func DefaultInfo(url string) *ytdlp.Info { + sum := sha256.Sum256([]byte(url)) return &ytdlp.Info{ Type: "video", - ID: "vid123", + ID: "vid-" + hex.EncodeToString(sum[:5]), Title: "Test Video", Extractor: "fake", WebpageURL: url, diff --git a/locales/en.toml b/locales/en.toml index e5d5cba..c0b162e 100644 --- a/locales/en.toml +++ b/locales/en.toml @@ -31,7 +31,10 @@ In a group, use /dl with a link, or reply /dl to a message that has a link. /dl link - download a video /audio link - download the audio as MP3 /thumb link - get the thumbnail +/subs link - get the subtitles /info link - show formats and sizes without downloading +/fresh link - download again instead of using a saved copy +/history - your past downloads, with one tap to get them again /queue - your running downloads /cancel - cancel your downloads @@ -58,6 +61,7 @@ thumb = "Get the thumbnail" info = "Show formats and sizes" queue = "Your downloads in progress" cancel = "Cancel your downloads" +history = "Your past downloads" account = "Your pass, balance and usage" buy = "Get a pass or credits" help = "How to use the bot" @@ -107,6 +111,8 @@ open_wallet = "Open in wallet" check_payment = "Check payment" this_file = "This file only" buy_for_me = "Buy for me" +subs_auto = "{{.Lang}} (auto)" +resend = "{{.N}}. {{.Title}}" [status] queued = "In the queue. Position {{.Position}}, about {{.Wait}}." @@ -115,6 +121,7 @@ downloading_bytes = "Downloading… {{.Done}}" downloading_progress = "Downloading…\n{{.Bar}} {{.Percent}}\n{{.Done}} of {{.Total}}" processing = "Processing the file…" uploading = "Sending it to Telegram…" +preparing = "Getting it ready…" done = "Done. Enjoy." cancelled = "Cancelled." failed = "That did not work. {{.Reason}}" @@ -140,6 +147,7 @@ too_large = "This file is larger than your limit of {{.MaxSize}}. Try a lower qu too_long = "This is longer than your limit of {{.MaxDuration}}." live = "Live streams cannot be downloaded." queue_full = "The queue is full right now. Please try again in a few minutes." +blocked = "This content is not available through this bot." daily_volume = "You reached your daily volume of {{.MaxVolume}}. It resets at midnight UTC." [limit.daily_downloads] @@ -189,7 +197,8 @@ cancelled = "The download was cancelled." worker_lost = "The download was interrupted. Please try again." internal = "Something went wrong on my side. Please try again." unknown = "The download failed. Please try again later." -playlist = "That link is a playlist. Send the link of a single video for now." +playlist = "That link is a playlist. Send it to me as a normal message to pick a format for the whole list." +playlist_nested = "This item is a list itself, so I skipped it." send_failed = "I could not send the file to Telegram. Please try again." # --- Money ------------------------------------------------------------------- @@ -310,3 +319,53 @@ skip_not_needed = "That download is not waiting in the queue anymore, so there i [over] options = "You can lift the limit:" started = "Your limits allow it now. The download has started." + +# --- Playlists, subtitles, history ------------------------------------------ + +[playlist] +empty = "I could not find any items in that playlist." +item_failed = "{{.Title}}\nSkipped. {{.Reason}}" + +[playlist.card] +one = """ +{{.Title}} +Playlist with {{.Count}} item. I will fetch {{.Take}} of them, one after another. + +Pick a format for all of them:""" +other = """ +{{.Title}} +Playlist with {{.Count}} items. I will fetch {{.Take}} of them, one after another. + +Pick a format for all of them:""" + +[playlist.queued] +one = "{{.Title}}\n{{.Count}} item is lined up. It starts as soon as you have a free slot. /cancel stops it." +other = "{{.Title}}\n{{.Count}} items are lined up. They start one after another as you have free slots. /cancel stops them." + +[subs] +pick = "Pick a subtitle language:" +none = "This video has no subtitles." + +[history] +empty = "You have no past downloads yet." +header = "Your past downloads\nTap one to get it again." +line = "{{.N}}. {{.Title}} · {{.Label}}" + +# --- Owner commands --------------------------------------------------------- + +[owner] +purge_usage = "Send a link, or a key as extractor:video_id.\nExample: /purge https://example.com/video copyright notice" +cache = """ +Cache +Entries: {{.Entries}} ({{.Stored}} with a stored copy) +Stored: {{.Size}} of {{.Budget}} +Hits, all time: {{.Hits}} +Taken down: {{.Blocked}} + +Since the last start +Hit rate: {{.Rate}} of {{.Since}} requests +Download volume saved: {{.Saved}}""" + +[owner.purged] +one = "Taken down: {{.Key}}\n{{.Count}} cached file was removed. The key is blocked." +other = "Taken down: {{.Key}}\n{{.Count}} cached files were removed. The key is blocked."