Phase 3: cache

Repeat downloads are instant, and the cache never bypasses a limit.

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

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-18 08:38:38 +00:00
co-authored by Claude Fable 5.2
parent 0d50f453a0
commit 9c9d641eda
39 changed files with 4121 additions and 121 deletions
+8
View File
@@ -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,
+20 -1
View File
@@ -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 != "" {
+39
View File
@@ -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:
+169 -42
View File
@@ -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) {
+453
View File
@@ -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:<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)
}
+1 -1
View File
@@ -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.<name>".
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.
+1 -1
View File
@@ -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:
+5
View File
@@ -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)