Files
Media-download-telegram-bot/internal/bot/extras.go
T
MichilisandClaude Fable 5.2 9c9d641eda Phase 3: cache
Repeat downloads are instant, and the cache never bypasses a limit.

- internal/cache: canonical key (extractor + video id + profile, URL hash
  fallback), per-bot file_id layer, stored copy layer, metadata layer,
  TTL by source type, LRU-plus-hits eviction that keeps file_ids, orphan
  sweeper, takedown that deletes, invalidates and blocks
- One admission gate: a cache hit passes the same size, duration, quota,
  volume, active job and queue checks as a fresh download, is judged by
  the real cached file, and costs the same. It only skips the worker
- Singleflight: a second requester joins the job that is queued or running
  for the same result. Each keeps their own caps, checked at delivery
- Derive: lower profiles and audio are transcoded from a stored copy with
  ffmpeg; a higher profile that already fits is served as an alias; a
  failed derive falls back to a download
- Self-healing: a rejected file_id falls back to the stored copy, then to
  a fresh download, and the entry is updated either way
- Private or login-gated content and live streams are never cached
- Playlists as per-item jobs started in turn, /subs, /history with resend,
  /fresh, owner /purge and /cache
- Worker removes its temp files right after the upload

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 08:38:38 +00:00

454 lines
15 KiB
Go

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:<request id>:<profile>
cbResend = "rs" // rs:<delivery id>
)
// --- 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 <link> 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)
}