- Stars as a second payment method for passes and credit packs, next to Lightning (STARS_ENABLED, prices in [stars_prices] / STARS_PRICES, set on their own). Invoices in XTR with no provider token and one price; pre-checkout checks payer, state, currency and amount; successful_payment settles through the same transaction as Lightning, so entitlement is identical. Idempotent by telegram_payment_charge_id (unique index). - Migration 00009: payment_method on purchases and ledger entries, plus stars_amount, tg_charge_id and refunded_at on purchases. Stars purchases never reach LNbits. - Chat: buy screen, /credits, /account and the over-limit offer show Lightning first and a Pay with Stars button. - Mini App: Lightning and Stars switch on Buy; Stars use createInvoiceLink and WebApp.openInvoice, confirmed by the server-side payment event. - Owner /refund <purchase or charge ID> calls refundStarPayment and takes back the credits or pass; refunded_payment messages do the same once. /stats shows revenue by payment method. - The sats referral reward counts Lightning purchases only. - The bot now asks Telegram for pre_checkout_query updates. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
871 lines
27 KiB
Go
871 lines
27 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"
|
|
"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"
|
|
"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"`
|
|
// Availability is yt-dlp's access class ("public", "private", ...).
|
|
// Anything that is not public or unlisted is never cached.
|
|
Availability string `json:"availability,omitempty"`
|
|
// UploadDate is YYYYMMDD, when the site says.
|
|
UploadDate string `json:"upload_date,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.
|
|
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{},
|
|
}
|
|
c.Availability = info.Availability
|
|
c.UploadDate = info.UploadDate
|
|
c.SubLangs, c.AutoSubLangs = info.SubtitleLangs()
|
|
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
|
|
}
|
|
|
|
// 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
|
|
// Decision is the entitlement the request was judged under.
|
|
Decision entitle.Decision
|
|
// Upgradable is true when a paid entitlement would allow the download
|
|
// and payments are available, which is when the bot offers to sell.
|
|
Upgradable bool
|
|
// Size is the estimated size of the refused download, 0 when unknown.
|
|
Size int64
|
|
}
|
|
|
|
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"
|
|
LimitDailyDownloads = "daily_downloads"
|
|
LimitDailyVolume = "daily_volume"
|
|
// LimitBlocked is a takedown by the owner: the video or its site is on
|
|
// the blocklist.
|
|
LimitBlocked = "blocked"
|
|
// Refusals from a group's own settings.
|
|
LimitGroupDisabled = "group_disabled"
|
|
LimitGroupAdminsOnly = "group_admins_only"
|
|
LimitGroupPassOnly = "group_pass_only"
|
|
LimitGroupSite = "group_site"
|
|
// LimitMaintenance is the owner's maintenance switch.
|
|
LimitMaintenance = "maintenance"
|
|
)
|
|
|
|
// AdminChecker says whether a user is an admin of a group chat.
|
|
type AdminChecker interface {
|
|
IsAdmin(ctx context.Context, chatID, userID int64) bool
|
|
}
|
|
|
|
// SetAdmins gives the service the means to check group admins. Until it
|
|
// is set nobody counts as an admin.
|
|
func (s *Service) SetAdmins(a AdminChecker) { s.admins = a }
|
|
|
|
// groupContext is what a request from a group is judged by.
|
|
type groupContext struct {
|
|
settings *db.GroupSettings
|
|
wallet entitle.Wallet
|
|
admin bool
|
|
// memberSpent and totalSpent are group credits spent today.
|
|
memberSpent, totalSpent int64
|
|
}
|
|
|
|
func isGroup(chatType string) bool { return chatType == "group" || chatType == "supergroup" }
|
|
|
|
func (s *Service) groupContext(ctx context.Context, who Who) (*groupContext, error) {
|
|
if !isGroup(who.ChatType) {
|
|
return nil, nil
|
|
}
|
|
gc := &groupContext{}
|
|
var err error
|
|
if gc.settings, err = s.store.GetGroupSettings(ctx, who.ChatID); err != nil {
|
|
return nil, err
|
|
}
|
|
if gc.wallet, err = s.billing.State(ctx, db.OwnerGroup, who.ChatID); err != nil {
|
|
return nil, err
|
|
}
|
|
if s.admins != nil {
|
|
gc.admin = s.admins.IsAdmin(ctx, who.ChatID, who.UserID)
|
|
}
|
|
if gc.memberSpent, gc.totalSpent, err = s.store.GroupSpent(ctx, who.ChatID, who.UserID, Day(s.now())); err != nil {
|
|
return nil, err
|
|
}
|
|
return gc, nil
|
|
}
|
|
|
|
// creditsAllowed applies the group's spending rule and caps to one more
|
|
// download by this member.
|
|
func (gc *groupContext) creditsAllowed(cost int64) bool {
|
|
st := gc.settings
|
|
if st.DailyCap > 0 && gc.totalSpent+cost > st.DailyCap {
|
|
return false
|
|
}
|
|
switch st.SpendRule {
|
|
case db.SpendAnyone:
|
|
return true
|
|
case db.SpendCapped:
|
|
return gc.memberSpent+cost <= st.SpendCap
|
|
default: // admins only
|
|
return gc.admin
|
|
}
|
|
}
|
|
|
|
// gate applies the group's own settings: whether the bot is on, who may
|
|
// use it, and which sites are allowed.
|
|
func (s *Service) gate(ctx context.Context, who Who, info *CardInfo, dec entitle.Decision, gc *groupContext) error {
|
|
if on, _ := s.store.GetKV(ctx, "maintenance"); on == "1" && !s.cfg.IsOwner(who.UserID) {
|
|
return &LimitError{Code: LimitMaintenance, Decision: dec}
|
|
}
|
|
if gc == nil {
|
|
return nil
|
|
}
|
|
st := gc.settings
|
|
refuse := func(code string) error { return &LimitError{Code: code, Decision: dec} }
|
|
if !st.Enabled {
|
|
return refuse(LimitGroupDisabled)
|
|
}
|
|
switch st.WhoCanUse {
|
|
case db.UseAdmins:
|
|
if !gc.admin {
|
|
return refuse(LimitGroupAdminsOnly)
|
|
}
|
|
case db.UsePassHolders:
|
|
if !gc.admin && dec.Source != entitle.OwnPass && dec.Source != entitle.GroupPass {
|
|
return refuse(LimitGroupPassOnly)
|
|
}
|
|
}
|
|
if info != nil && info.Site != "" {
|
|
if allowed := db.Sites(st.Allowed); len(allowed) > 0 && !hostInList(info.Site, allowed) {
|
|
return refuse(LimitGroupSite)
|
|
}
|
|
if hostInList(info.Site, db.Sites(st.Blocked)) {
|
|
return refuse(LimitGroupSite)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func hostInList(site string, list []string) bool {
|
|
site = strings.ToLower(site)
|
|
for _, h := range list {
|
|
if site == h || strings.HasSuffix(site, "."+h) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// 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
|
|
billing *billing.Billing
|
|
cache *cache.Cache
|
|
prober Prober
|
|
admins AdminChecker
|
|
log *slog.Logger
|
|
probes chan struct{}
|
|
now func() time.Time
|
|
// probeRetryDelay is the pause before a failed lookup is tried again.
|
|
probeRetryDelay time.Duration
|
|
}
|
|
|
|
// Prober looks up the metadata of a link. It is yt-dlp on the core, or the
|
|
// broker that hands lookups to remote workers.
|
|
type Prober interface {
|
|
Probe(ctx context.Context, url string) (*ytdlp.Info, error)
|
|
}
|
|
|
|
// New creates the service.
|
|
func New(cfg config.Config, store *db.Store, sch *sched.Scheduler, bill *billing.Billing, ch *cache.Cache, prober Prober, log *slog.Logger) *Service {
|
|
n := cfg.Worker.ProbeConcurrency
|
|
if n < 1 {
|
|
n = 1
|
|
}
|
|
return &Service{
|
|
cfg: cfg, store: store, sched: sch, billing: bill, cache: ch, prober: prober, log: log,
|
|
probes: make(chan struct{}, n), now: time.Now, probeRetryDelay: time.Second,
|
|
}
|
|
}
|
|
|
|
// 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 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 }()
|
|
case <-ctx.Done():
|
|
return nil, ctx.Err()
|
|
}
|
|
info, err := s.prober.Probe(ctx, url)
|
|
if retryable(err) && ctx.Err() == nil {
|
|
// A passing problem (network, rate limit, a lost worker) often goes
|
|
// away a moment later. One more try before the user sees an error.
|
|
s.log.Info("probe failed, trying once more", "url", links.Redact(url), "code", string(ytdlp.CodeOf(err)))
|
|
select {
|
|
case <-time.After(s.probeRetryDelay):
|
|
info, err = s.prober.Probe(ctx, url)
|
|
case <-ctx.Done():
|
|
}
|
|
}
|
|
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
|
|
}
|
|
p := &Probed{}
|
|
if info.IsPlaylist() {
|
|
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)
|
|
}
|
|
if raw, err := json.Marshal(p); err == nil {
|
|
s.cache.MetaPut(url, string(raw))
|
|
}
|
|
return p, nil
|
|
}
|
|
|
|
// retryable reports whether a lookup failure is worth one more try.
|
|
func retryable(err error) bool {
|
|
var ye *ytdlp.Error
|
|
if !errors.As(err, &ye) || !ye.Retryable {
|
|
return false
|
|
}
|
|
// A timeout already took the full probe time.
|
|
return ye.Code != ytdlp.CodeTimeout && ye.Code != ytdlp.CodeCancelled
|
|
}
|
|
|
|
// SetProbeRetryDelay changes the pause before a failed lookup is tried
|
|
// again. Tests shorten it.
|
|
func (s *Service) SetProbeRetryDelay(d time.Duration) { s.probeRetryDelay = d }
|
|
|
|
// tier converts a configured tier to resolver limits.
|
|
func tier(t config.Tier) entitle.Limits {
|
|
return entitle.Limits{
|
|
MaxSize: t.MaxSizeMB << 20,
|
|
MaxDuration: int64(t.MaxDuration.D().Seconds()),
|
|
ActiveJobs: t.ActiveJobs,
|
|
DailyDownloads: t.DailyDownloads,
|
|
DailyBytes: t.DailyMB << 20,
|
|
PlaylistItems: t.PlaylistItems,
|
|
}
|
|
}
|
|
|
|
// Day returns the usage day of a time as YYYYMMDD in UTC.
|
|
func Day(t time.Time) int {
|
|
y, m, d := t.UTC().Date()
|
|
return y*10000 + int(m)*100 + d
|
|
}
|
|
|
|
// Who identifies the requester and where the request came from.
|
|
type Who struct {
|
|
UserID int64
|
|
ChatID int64
|
|
ChatType string
|
|
}
|
|
|
|
// Entitlement resolves what pays for a download by this requester and
|
|
// which limits apply. oneOffPaid is true when an invoice for exactly this
|
|
// file was paid.
|
|
func (s *Service) Entitlement(ctx context.Context, who Who, oneOffPaid bool) (entitle.Decision, error) {
|
|
dec, _, err := s.entitle(ctx, who, oneOffPaid)
|
|
return dec, err
|
|
}
|
|
|
|
// entitle resolves the entitlement and returns the group context it was
|
|
// resolved with, which is nil in a private chat.
|
|
func (s *Service) entitle(ctx context.Context, who Who, oneOffPaid bool) (entitle.Decision, *groupContext, error) {
|
|
in := entitle.Input{
|
|
Now: s.now().UnixMilli(),
|
|
OneOffPaid: oneOffPaid,
|
|
Free: tier(s.cfg.Limits.Free),
|
|
Paid: tier(s.cfg.Limits.Paid),
|
|
CreditCost: s.cfg.Prices.CreditPerDownload,
|
|
UploadCap: s.cfg.MaxUploadBytes(),
|
|
}
|
|
user, err := s.billing.State(ctx, db.OwnerUser, who.UserID)
|
|
if err != nil {
|
|
return entitle.Decision{}, nil, err
|
|
}
|
|
in.User = user
|
|
gc, err := s.groupContext(ctx, who)
|
|
if err != nil {
|
|
return entitle.Decision{}, nil, err
|
|
}
|
|
if gc != nil {
|
|
in.Group = &entitle.Group{
|
|
Wallet: gc.wallet,
|
|
CreditsAllowed: gc.creditsAllowed(in.CreditCost),
|
|
MaxSize: gc.settings.MaxSizeMB << 20,
|
|
MaxDuration: gc.settings.MaxDuration,
|
|
}
|
|
}
|
|
return entitle.Resolve(in), gc, nil
|
|
}
|
|
|
|
// Usage returns what the user consumed today.
|
|
func (s *Service) Usage(ctx context.Context, userID int64) (db.Usage, error) {
|
|
return s.store.GetUsage(ctx, userID, Day(s.now()))
|
|
}
|
|
|
|
// 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 entitle.Limits) string {
|
|
if info.Live {
|
|
return LimitLive
|
|
}
|
|
kind := profile.Kind()
|
|
if kind == media.KindThumb || kind == media.KindSubs {
|
|
return ""
|
|
}
|
|
if lim.MaxDuration > 0 && info.Duration > lim.MaxDuration {
|
|
return LimitTooLong
|
|
}
|
|
if size := info.Sizes[string(profile)]; lim.MaxSize > 0 && size > lim.MaxSize {
|
|
return LimitTooLarge
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// admit runs every rule that can refuse a download: size, duration, live,
|
|
// the daily download quota and the daily volume cap. It is the one gate
|
|
// for fresh downloads and, later, for cache hits alike.
|
|
func (s *Service) admit(ctx context.Context, who Who, info *CardInfo, profile media.Profile, dec entitle.Decision) error {
|
|
code := Check(info, profile, dec.Limits)
|
|
if code == "" {
|
|
usage, err := s.Usage(ctx, who.UserID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
switch {
|
|
case dec.Limits.DailyDownloads > 0 && usage.Downloads >= dec.Limits.DailyDownloads:
|
|
code = LimitDailyDownloads
|
|
case dec.Limits.DailyBytes > 0 && usage.Bytes >= dec.Limits.DailyBytes:
|
|
code = LimitDailyVolume
|
|
}
|
|
}
|
|
if code == "" {
|
|
return nil
|
|
}
|
|
return s.limitError(code, info, profile, dec)
|
|
}
|
|
|
|
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 || code == LimitBlocked || strings.HasPrefix(code, "group_") ||
|
|
code == LimitMaintenance || dec.Source.Paid() || !s.billing.Selling() {
|
|
return le
|
|
}
|
|
// Would the paid tier accept it? Only then is it worth offering.
|
|
paid := tier(s.cfg.Limits.Paid)
|
|
if up := s.cfg.MaxUploadBytes(); up > 0 && (paid.MaxSize == 0 || paid.MaxSize > up) {
|
|
paid.MaxSize = up
|
|
}
|
|
le.Upgradable = Check(info, profile, paid) == ""
|
|
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, url string, info *CardInfo, profile media.Profile) error {
|
|
dec, gc, err := s.entitle(ctx, who, false)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := s.gate(ctx, who, info, dec, gc); err != nil {
|
|
return err
|
|
}
|
|
r, err := s.resolve(ctx, url, info, profile, dec)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return s.admit(ctx, who, r.view, profile, dec)
|
|
}
|
|
|
|
// Gate reports whether the requester may use the bot in this chat at all,
|
|
// before a link is even looked up. It returns *LimitError when not.
|
|
func (s *Service) Gate(ctx context.Context, who Who) error {
|
|
dec, gc, err := s.entitle(ctx, who, false)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return s.gate(ctx, who, nil, dec, gc)
|
|
}
|
|
|
|
// 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
|
|
// OneOff is the paid purchase for exactly this file, if any.
|
|
OneOff *db.Purchase
|
|
}
|
|
|
|
// Start resolves the entitlement, checks every limit, charges the wallet
|
|
// 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
|
|
// credits) makes the debit fail; resolving again then picks the next
|
|
// source in line.
|
|
for attempt := 0; ; attempt++ {
|
|
job, del, err := s.startOnce(ctx, who, p)
|
|
if errors.Is(err, db.ErrInsufficient) && attempt < 2 {
|
|
continue
|
|
}
|
|
return job, del, err
|
|
}
|
|
}
|
|
|
|
func (s *Service) startOnce(ctx context.Context, who Who, p StartParams) (*db.Job, *db.Delivery, error) {
|
|
dec, gc, err := s.entitle(ctx, who, p.OneOff != nil)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
if err := s.gate(ctx, who, p.Info, dec, gc); err != nil {
|
|
return nil, nil, err
|
|
}
|
|
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: r.extractor,
|
|
VideoID: r.videoID,
|
|
Profile: string(p.Profile),
|
|
Title: p.Info.Title,
|
|
Uploader: p.Info.Uploader,
|
|
Lane: dec.Lane,
|
|
Priority: dec.Priority,
|
|
MaxSize: dec.Limits.MaxSize,
|
|
MaxDuration: dec.Limits.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: dec.Limits.ActiveJobs,
|
|
Source: string(dec.Source),
|
|
WalletID: dec.WalletID,
|
|
ChargeSats: dec.Charge,
|
|
QuotaDay: day,
|
|
CacheKey: cache.JobKey(r.extractor, r.videoID, string(p.Profile)),
|
|
Cacheable: r.cacheable,
|
|
// Sites that refuse some networks are routed to workers that carry
|
|
// the tags the owner configured for them.
|
|
RequiredTags: s.cfg.RequiredTags(p.Info.Site),
|
|
}
|
|
if p.OneOff != nil {
|
|
// Prepaid by invoice. Remember the amount and the payer's wallet so
|
|
// a failed download can be refunded as credits.
|
|
w, err := s.billing.Wallet(ctx, db.OwnerUser, p.OneOff.UserID)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
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
|
|
attached bool
|
|
)
|
|
err = s.store.InTx(ctx, func(tx *db.Store) error {
|
|
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{
|
|
WalletID: dec.WalletID, Kind: db.LedgerDebit, Amount: dec.Charge, Reason: "download",
|
|
Ref: del.ID, DedupeKey: "download:" + del.ID, ActorID: who.UserID, CreatedAt: s.now().UnixMilli(),
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if gc != nil {
|
|
// Per-member use of the group: the base for spending caps and
|
|
// for the usage-by-member view.
|
|
var sats int64
|
|
if dec.Source == entitle.GroupCredits {
|
|
sats = dec.Charge
|
|
}
|
|
if err := tx.AddGroupUsage(ctx, who.ChatID, who.UserID, day, 1, sats, 0); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return tx.AddUsage(ctx, who.UserID, day, 1, 0)
|
|
})
|
|
switch {
|
|
case errors.Is(err, sched.ErrTooManyActive):
|
|
return nil, nil, s.limitError(LimitActiveJobs, p.Info, p.Profile, dec)
|
|
case errors.Is(err, sched.ErrQueueFull):
|
|
return nil, nil, s.limitError(LimitQueueFull, p.Info, p.Profile, dec)
|
|
case err != nil:
|
|
return nil, nil, err
|
|
}
|
|
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
|
|
}
|
|
|
|
// Release gives back what an undelivered download took: the sats that
|
|
// were charged and the slot in the daily quota. It is idempotent and
|
|
// returns the refunded sats, which is 0 on every call after the first.
|
|
func (s *Service) Release(ctx context.Context, deliveryID string) (refunded int64, err error) {
|
|
err = s.store.InTx(ctx, func(tx *db.Store) error {
|
|
d, err := tx.GetDelivery(ctx, deliveryID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if d.Status == db.DeliverySent {
|
|
return nil // the file arrived, nothing to give back
|
|
}
|
|
won, err := tx.MarkDeliveryReleased(ctx, d.ID)
|
|
if err != nil || !won {
|
|
return err
|
|
}
|
|
if d.ChargeSats > 0 && d.WalletID != "" {
|
|
applied, err := tx.AddLedger(ctx, &db.LedgerEntry{
|
|
WalletID: d.WalletID, Kind: db.LedgerRefund, Amount: d.ChargeSats, Reason: "refund",
|
|
Ref: d.ID, DedupeKey: "refund:" + d.ID, CreatedAt: s.now().UnixMilli(),
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if applied {
|
|
refunded = d.ChargeSats
|
|
}
|
|
}
|
|
if d.QuotaDay > 0 {
|
|
if isGroup(d.ChatType) {
|
|
var sats int64
|
|
if d.Source == string(entitle.GroupCredits) {
|
|
sats = d.ChargeSats
|
|
}
|
|
if err := tx.AddGroupUsage(ctx, d.ChatID, d.UserID, d.QuotaDay, -1, -sats, 0); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return tx.AddUsage(ctx, d.UserID, d.QuotaDay, -1, 0)
|
|
}
|
|
return nil
|
|
})
|
|
if errors.Is(err, db.ErrDuplicate) {
|
|
return 0, nil
|
|
}
|
|
if err == nil && refunded > 0 {
|
|
s.log.Info("download refunded", "delivery_id", deliveryID, "sats", refunded)
|
|
}
|
|
return refunded, err
|
|
}
|
|
|
|
// Refunded returns the sats that were given back for a delivery, whoever
|
|
// did it and whenever. Several paths can release a delivery (the cancel
|
|
// handler, the failure handler, the periodic sweep) and only one of them
|
|
// wins; the message to the user should mention the refund regardless.
|
|
func (s *Service) Refunded(ctx context.Context, deliveryID string) int64 {
|
|
d, err := s.store.GetDelivery(ctx, deliveryID)
|
|
if err != nil || !d.Released || d.Status == db.DeliverySent || d.WalletID == "" {
|
|
return 0
|
|
}
|
|
return d.ChargeSats
|
|
}
|
|
|
|
// RecordDelivered adds the delivered bytes to the requester's daily volume.
|
|
func (s *Service) RecordDelivered(ctx context.Context, d *db.Delivery, bytes int64) error {
|
|
day := d.QuotaDay
|
|
if day == 0 {
|
|
day = Day(s.now())
|
|
}
|
|
if isGroup(d.ChatType) {
|
|
if err := s.store.AddGroupUsage(ctx, d.ChatID, d.UserID, day, 0, 0, bytes); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return s.store.AddUsage(ctx, d.UserID, day, 0, bytes)
|
|
}
|
|
|
|
// ReleasePending refunds deliveries that ended without a file but were
|
|
// missed by the normal path, for example because the core stopped between
|
|
// the failure and the refund.
|
|
func (s *Service) ReleasePending(ctx context.Context) {
|
|
list, err := s.store.UnreleasedDeliveries(ctx, 200)
|
|
if err != nil {
|
|
s.log.Error("list unreleased deliveries", "err", err)
|
|
return
|
|
}
|
|
for _, d := range list {
|
|
if _, err := s.Release(ctx, d.ID); err != nil {
|
|
s.log.Error("release delivery", "delivery_id", d.ID, "err", err)
|
|
}
|
|
}
|
|
}
|