Files
MichilisandClaude Opus 5.5 6843053582 Phase 1: quick flow fixes
- One message per job: the status message is deleted once the file is
  sent, or shortened to "Sent." when Telegram keeps it.
- No reply quotes in private chats; groups keep them.
- Queue status only mentions the position when the wait is above
  QUEUE_NOTICE_THRESHOLD_SECONDS or somebody is ahead. Status edits are
  throttled to one per 2.5 s per message; a state that arrives too soon
  is shown later instead of dropped. The wait estimate is 0 with a free
  slot.
- Caption with title (uploader and date when generic), uploader,
  duration, a short source link without tracking parameters and an
  optional "via @bot" line (CAPTION_ATTRIBUTION). Uploaded videos get a
  320 px JPEG thumbnail; merged MP4s are written with faststart.
- Buttons under the result: Audio (MP3), Other quality, Thumbnail,
  Delete. Requester only in groups.
- Language resolved once per update and passed in the context. A
  fallback to English is logged as a bug; a test walks every screen in
  Spanish and Dutch. Language picker on the first /start.
- Sizes without a zero decimal ("50 MB").
- First link of a new user shows the card once and sets the default to
  "best that fits my limit".
- Errors offer the next step (Try again, Smaller quality, Upgrade, Open
  app); passing lookup failures are retried once.
- Up to MULTI_LINK_MAX links per message; a link sent a moment ago gets
  "already sent" with a Send again button.
- Mini App menu button, labelled per private chat in the user's
  language.
- Personal /settings in private chats with an "Add me to a group"
  button.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 20:08:58 +00:00

225 lines
6.3 KiB
Go

// Package ytdlp wraps the yt-dlp and ffprobe executables behind an interface
// so the rest of the bot can be tested without them.
package ytdlp
import (
"context"
"errors"
"strconv"
"strings"
"time"
"github.com/noderunners/dlbot/internal/media"
)
// Runner looks up metadata and downloads media.
type Runner interface {
// Probe returns metadata for a URL without downloading it.
Probe(ctx context.Context, url string) (*Info, error)
// Download fetches one profile of a URL into req.Dir. onProgress may be
// nil. Failures are returned as *Error.
Download(ctx context.Context, req DownloadRequest, onProgress func(Progress)) (*Result, error)
}
// Info is the subset of the yt-dlp info JSON the bot uses.
type Info struct {
Type string `json:"_type"`
ID string `json:"id"`
Title string `json:"title"`
Extractor string `json:"extractor"`
ExtractorKey string `json:"extractor_key"`
WebpageURL string `json:"webpage_url"`
Thumbnail string `json:"thumbnail"`
Uploader string `json:"uploader"`
Ext string `json:"ext"`
Duration Float `json:"duration"`
Filesize Int `json:"filesize"`
FilesizeAprx Int `json:"filesize_approx"`
Width Int `json:"width"`
Height Int `json:"height"`
IsLive bool `json:"is_live"`
LiveStatus string `json:"live_status"`
Availability string `json:"availability"`
// UploadDate is YYYYMMDD, when the site says.
UploadDate string `json:"upload_date"`
Formats []Format `json:"formats"`
Subtitles map[string][]SubTrack `json:"subtitles"`
AutomaticCaptions map[string][]SubTrack `json:"automatic_captions"`
Entries []Entry `json:"entries"`
}
// Format is one downloadable format of a video.
type Format struct {
FormatID string `json:"format_id"`
FormatNote string `json:"format_note"`
Ext string `json:"ext"`
VCodec string `json:"vcodec"`
ACodec string `json:"acodec"`
Protocol string `json:"protocol"`
Width Int `json:"width"`
Height Int `json:"height"`
Filesize Int `json:"filesize"`
FilesizeAprx Int `json:"filesize_approx"`
TBR Float `json:"tbr"`
}
// SubTrack is one subtitle file variant.
type SubTrack struct {
Ext string `json:"ext"`
Name string `json:"name"`
}
// Entry is one item of a playlist in a flat listing.
type Entry struct {
ID string `json:"id"`
Title string `json:"title"`
URL string `json:"url"`
Duration Float `json:"duration"`
}
// IsPlaylist reports whether the URL resolved to a list of items.
func (i *Info) IsPlaylist() bool { return i.Type == "playlist" || i.Type == "multi_video" }
// Live reports whether the item is a running or upcoming live stream.
func (i *Info) Live() bool {
return i.IsLive || i.LiveStatus == "is_live" || i.LiveStatus == "is_upcoming"
}
// DownloadRequest describes one download.
type DownloadRequest struct {
URL string
Profile media.Profile
// Dir is an empty directory owned by this download.
Dir string
// MaxSize in bytes, 0 for no cap.
MaxSize int64
// MaxDuration, 0 for no cap.
MaxDuration time.Duration
}
// Progress is a snapshot of a running download.
type Progress struct {
Stage string // downloading or processing
Downloaded int64
Total int64 // 0 when unknown
}
// The progress stages.
const (
StageDownloading = "downloading"
StageProcessing = "processing"
StageUploading = "uploading"
)
// Result describes a finished download.
type Result struct {
Path string
Size int64
Ext string
ID string
Title string
Uploader string
Extractor string
Duration float64
Width int
Height int
}
// Code is a stable, user-presentable failure class. Each code has a
// matching "error.<code>" message in the catalogs.
type Code string
// The failure classes.
const (
CodeUnsupported Code = "unsupported_url"
CodeNotFound Code = "not_found"
CodePrivate Code = "private"
CodeLoginRequired Code = "login_required"
CodeGeoBlocked Code = "geo_blocked"
CodeSiteBlocked Code = "site_blocked"
CodeRateLimited Code = "rate_limited"
CodeLive Code = "live_stream"
CodeDRM Code = "drm"
CodeTooLarge Code = "too_large"
CodeTooLong Code = "too_long"
CodeNoMedia Code = "no_media"
CodeNoSubtitles Code = "no_subtitles"
CodeNetwork Code = "network"
CodeTimeout Code = "timeout"
CodeProcessing Code = "processing_failed"
CodeCancelled Code = "cancelled"
CodeWorkerLost Code = "worker_lost"
CodeInternal Code = "internal"
CodeUnknown Code = "unknown"
)
// KnownCodes lists every code, for catalog completeness checks.
var KnownCodes = []Code{
CodeUnsupported, CodeNotFound, CodePrivate, CodeLoginRequired, CodeGeoBlocked,
CodeSiteBlocked, CodeRateLimited, CodeLive, CodeDRM, CodeTooLarge, CodeTooLong,
CodeNoMedia, CodeNoSubtitles, CodeNetwork, CodeTimeout, CodeProcessing,
CodeCancelled, CodeWorkerLost, CodeInternal, CodeUnknown,
}
// Error is a classified yt-dlp failure. Raw is for owner logs only and must
// never be shown to users.
type Error struct {
Code Code
Retryable bool
Raw string
}
func (e *Error) Error() string { return "ytdlp: " + string(e.Code) + ": " + e.Raw }
// CodeOf extracts the failure class from any error.
func CodeOf(err error) Code {
var e *Error
switch {
case errors.As(err, &e):
return e.Code
case errors.Is(err, context.Canceled):
return CodeCancelled
case errors.Is(err, context.DeadlineExceeded):
return CodeTimeout
}
return CodeUnknown
}
// Int is an integer that tolerates the loose numbers in yt-dlp JSON: null,
// floats such as 1234.5 and quoted numbers all decode without error.
type Int int64
// UnmarshalJSON implements json.Unmarshaler.
func (i *Int) UnmarshalJSON(b []byte) error {
f, ok := looseNumber(b)
if ok {
*i = Int(f)
}
return nil
}
// Float is the floating point counterpart of Int.
type Float float64
// UnmarshalJSON implements json.Unmarshaler.
func (f *Float) UnmarshalJSON(b []byte) error {
v, ok := looseNumber(b)
if ok {
*f = Float(v)
}
return nil
}
func looseNumber(b []byte) (float64, bool) {
s := strings.Trim(strings.TrimSpace(string(b)), `"`)
if s == "" || s == "null" {
return 0, false
}
v, err := strconv.ParseFloat(s, 64)
if err != nil || v != v {
return 0, false
}
return v, true
}