Files
Media-download-telegram-bot/internal/service/service.go
T
MichilisandClaude Fable 5.2 3b361c17a1 Phase 1: core bot
Link in, card, download, send, in private chats and groups.

- cmd/core with an embedded download worker
- Telegram front end on telego v1.13.0 (Bot API 10.4): link card with
  thumbnail and format buttons, one live status message, /dl /audio /thumb
  /info /queue /cancel, group support with requester-only buttons
- Database backed queue: paid and free lanes, leases with heartbeats, one
  automatic retry, cancel, queue position and wait estimate
- yt-dlp and ffprobe behind a Runner interface with classified, redacted
  errors mapped to friendly messages
- SQLite via modernc with goose migrations, portable schema
- Local file storage behind a Storage interface
- go-i18n with an English catalog, no literal text in handlers
- Free tier limits enforced before queueing and again on the real file
- Bot token and webhook secret are stripped from all log output
- Tests: URL parsing, job lifecycle, worker, yt-dlp wrapper, and end to end
  flows against a fake Bot API server; opt-in test with the real yt-dlp

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

239 lines
7.0 KiB
Go

// Package service holds the download rules shared by every front end: the
// bot handlers today and the Mini App API later. Front ends render; this
// package decides.
package service
import (
"context"
"encoding/json"
"errors"
"log/slog"
"math"
"github.com/noderunners/dlbot/internal/config"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/links"
"github.com/noderunners/dlbot/internal/media"
"github.com/noderunners/dlbot/internal/sched"
"github.com/noderunners/dlbot/internal/ytdlp"
)
// CardInfo is the metadata kept with a request. It is what the card shows
// and what admission checks run against.
type CardInfo struct {
Extractor string `json:"extractor"`
VideoID string `json:"video_id"`
Title string `json:"title"`
Uploader string `json:"uploader,omitempty"`
Thumbnail string `json:"thumbnail,omitempty"`
Site string `json:"site,omitempty"`
// Duration in seconds, 0 when unknown.
Duration int64 `json:"duration,omitempty"`
MaxHeight int `json:"max_height,omitempty"`
HasAudio bool `json:"has_audio"`
Live bool `json:"live,omitempty"`
// Sizes maps a profile to its estimated size in bytes. Profiles with an
// unknown size are absent.
Sizes map[string]int64 `json:"sizes,omitempty"`
}
// JSON encodes the info for storage.
func (c *CardInfo) JSON() string {
b, _ := json.Marshal(c)
return string(b)
}
// ParseCardInfo decodes stored info.
func ParseCardInfo(s string) (*CardInfo, error) {
var c CardInfo
if err := json.Unmarshal([]byte(s), &c); err != nil {
return nil, err
}
return &c, nil
}
// sizedProfiles are the profiles a size estimate is kept for.
var sizedProfiles = []media.Profile{media.Best, media.P1080, media.P720, media.P480, media.MP3, media.M4A}
func cardInfo(url string, info *ytdlp.Info) *CardInfo {
c := &CardInfo{
Extractor: info.Extractor,
VideoID: info.ID,
Title: info.Title,
Uploader: info.Uploader,
Thumbnail: info.Thumbnail,
Site: links.Site(url),
Duration: int64(math.Round(float64(info.Duration))),
MaxHeight: info.MaxHeight(),
HasAudio: info.HasAudio(),
Live: info.Live(),
Sizes: map[string]int64{},
}
if c.Title == "" {
c.Title = info.ID
}
for _, p := range sizedProfiles {
if n := info.EstimateSize(p); n > 0 {
c.Sizes[string(p)] = n
}
}
return c
}
// Limits are the rules one download runs under.
type Limits struct {
MaxSize int64 // bytes
MaxDuration int64 // seconds
ActiveJobs int
Lane string
Priority int
}
// LimitError is a refusal caused by a limit rather than by the source.
// Code doubles as the message key suffix: "limit.<code>".
type LimitError struct {
Code string
Limits Limits
}
func (e *LimitError) Error() string { return "service: limit: " + e.Code }
// The limit refusal codes.
const (
LimitTooLarge = "too_large"
LimitTooLong = "too_long"
LimitLive = "live"
LimitActiveJobs = "active_jobs"
LimitQueueFull = "queue_full"
)
// ErrPlaylist is returned by Probe for links that resolve to a list.
var ErrPlaylist = errors.New("service: link is a playlist")
// Service implements the download rules.
type Service struct {
cfg config.Config
store *db.Store
sched *sched.Scheduler
runner ytdlp.Runner
log *slog.Logger
probes chan struct{}
}
// New creates the service.
func New(cfg config.Config, store *db.Store, sch *sched.Scheduler, runner ytdlp.Runner, log *slog.Logger) *Service {
n := cfg.Worker.ProbeConcurrency
if n < 1 {
n = 1
}
return &Service{cfg: cfg, store: store, sched: sch, runner: runner, log: log, probes: make(chan struct{}, n)}
}
// 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.
func (s *Service) Probe(ctx context.Context, url string) (*CardInfo, error) {
select {
case s.probes <- struct{}{}:
defer func() { <-s.probes }()
case <-ctx.Done():
return nil, ctx.Err()
}
info, err := s.runner.Probe(ctx, url)
if err != nil {
var ye *ytdlp.Error
if errors.As(err, &ye) {
s.log.Info("probe failed", "url", links.Redact(url), "code", string(ye.Code), "detail", ye.Raw)
}
return nil, err
}
if info.IsPlaylist() {
return nil, ErrPlaylist
}
return cardInfo(url, info), nil
}
// LimitsFor returns the limits that apply to a user. Until payments exist
// everyone is on the free tier. The Telegram upload ceiling always applies.
func (s *Service) LimitsFor(_ context.Context, _ int64) Limits {
free := s.cfg.Limits.Free
lim := Limits{
MaxSize: free.MaxSizeMB << 20,
MaxDuration: int64(free.MaxDuration.D().Seconds()),
ActiveJobs: free.ActiveJobs,
Lane: db.LaneFree,
}
if up := s.cfg.MaxUploadBytes(); up > 0 && (lim.MaxSize == 0 || lim.MaxSize > up) {
lim.MaxSize = up
}
return lim
}
// Check applies the size, duration and live rules to known metadata. The
// worker enforces the same caps again on the real file, because metadata
// is often incomplete.
func Check(info *CardInfo, profile media.Profile, lim Limits) error {
if info.Live {
return &LimitError{Code: LimitLive, Limits: lim}
}
kind := profile.Kind()
if kind == media.KindThumb || kind == media.KindSubs {
return nil
}
if lim.MaxDuration > 0 && info.Duration > lim.MaxDuration {
return &LimitError{Code: LimitTooLong, Limits: lim}
}
if size := info.Sizes[string(profile)]; lim.MaxSize > 0 && size > lim.MaxSize {
return &LimitError{Code: LimitTooLarge, Limits: lim}
}
return nil
}
// StartParams describes a download a requester asked for.
type StartParams struct {
Request *db.Request
Info *CardInfo
Profile media.Profile
StatusMessageID int64
StatusIsPhoto bool
ReplyToMessageID int64
}
// Start checks the limits and queues the download. It returns *LimitError
// when a rule refuses the request.
func (s *Service) Start(ctx context.Context, p StartParams) (*db.Job, *db.Delivery, error) {
lim := s.LimitsFor(ctx, p.Request.UserID)
if err := Check(p.Info, p.Profile, lim); err != nil {
return nil, nil, err
}
job, del, err := s.sched.Enqueue(ctx, sched.EnqueueParams{
URL: p.Request.URL,
Extractor: p.Info.Extractor,
VideoID: p.Info.VideoID,
Profile: string(p.Profile),
Title: p.Info.Title,
Uploader: p.Info.Uploader,
Lane: lim.Lane,
Priority: lim.Priority,
MaxSize: lim.MaxSize,
MaxDuration: lim.MaxDuration,
RequestID: p.Request.ID,
UserID: p.Request.UserID,
ChatID: p.Request.ChatID,
ChatType: p.Request.ChatType,
ReplyToMessageID: p.ReplyToMessageID,
StatusMessageID: p.StatusMessageID,
StatusIsPhoto: p.StatusIsPhoto,
Lang: p.Request.Lang,
ActiveLimit: lim.ActiveJobs,
})
switch {
case errors.Is(err, sched.ErrTooManyActive):
return nil, nil, &LimitError{Code: LimitActiveJobs, Limits: lim}
case errors.Is(err, sched.ErrQueueFull):
return nil, nil, &LimitError{Code: LimitQueueFull, Limits: lim}
case err != nil:
return nil, nil, err
}
return job, del, nil
}