Files
Media-download-telegram-bot/internal/bot/card.go
T
MichilisandClaude Fable 5.2 0d50f453a0 Phase 2: money
Lightning payments through LNbits, wallets, passes, credits, the
entitlement resolver and priority lanes.

- internal/entitle: pure resolver (one-off, own pass, group pass, group
  credits, own credits, free) with a table-driven suite and an invariant
  check over every input combination
- internal/billing: wallets, append-only ledger with dedupe keys, stacking
  passes, purchases, gift codes, referral reward
- LNbits client verified against v0.12.12 and v1.7.1 source
- Settlement by one conditional UPDATE: idempotent under any mix of
  webhooks, polls and the check button. Webhooks are unsigned, so every
  payment is confirmed with LNbits before it is credited
- Polling fallback, reconciliation of all unsettled invoices at startup,
  late payments still honored, no expiry while LNbits is unreachable
- Charge, quota and job are written in one transaction; failed, cancelled
  and undeliverable downloads are refunded exactly once
- Paid lane first with one slot of the fleet reserved for free users
- Daily download quota and daily volume cap, per-user and per-group rate
  limits
- Bot: /buy /account /limits /credits /redeem /referral /donate, QR invoice
  message that flips to paid, over-limit offer (passes or this file only),
  deep links from groups, skip the queue
- Fake LNbits server for tests; end-to-end money flows including a payment
  made while the core was down

Cashu redemption is behind an interface and not implemented.

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

270 lines
8.8 KiB
Go

package bot
import (
"context"
"errors"
"html"
"strconv"
"strings"
"time"
"github.com/mymmrac/telego"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/i18n"
"github.com/noderunners/dlbot/internal/ids"
"github.com/noderunners/dlbot/internal/links"
"github.com/noderunners/dlbot/internal/media"
"github.com/noderunners/dlbot/internal/service"
"github.com/noderunners/dlbot/internal/ytdlp"
)
func secondsDuration(s int64) time.Duration { return time.Duration(s) * time.Second }
// linkRequest is one link a user asked about.
type linkRequest struct {
chatID int64
chatType string
// sourceID is the message that holds the link. The card and the file
// are sent as replies to it.
sourceID int64
act actor
url string
// preset skips the card and starts this profile right away.
preset media.Profile
}
// startLink runs the link flow in the background so a slow metadata lookup
// never blocks other updates of the chat.
func (b *Bot) startLink(ctx context.Context, lr linkRequest) {
userOK := b.rate.allow("u:"+strconv.FormatInt(lr.act.user.ID, 10), b.cfg.Rate.UserPerMinute, time.Minute)
groupOK := isPrivate(lr.chatType) ||
b.rate.allow("g:"+strconv.FormatInt(lr.chatID, 10), b.cfg.Rate.GroupPerMinute, time.Minute)
if !userOK || !groupOK {
// One notice per minute is enough; more would be its own flood.
if b.rate.allow("n:"+strconv.FormatInt(lr.chatID, 10)+":"+strconv.FormatInt(lr.act.user.ID, 10), 1, time.Minute) {
_, _ = b.send(ctx, lr.chatID, lr.sourceID, b.tr.HTML(lr.act.lang, "notice.rate_limited", nil), nil)
}
return
}
b.goBG("link", func() { b.linkFlow(ctx, lr) })
}
func (b *Bot) linkFlow(ctx context.Context, lr linkRequest) {
lang := lr.act.lang
log := b.log.With("user_id", lr.act.user.ID, "chat_id", lr.chatID, "url", links.Redact(lr.url))
placeholder, err := b.send(ctx, lr.chatID, lr.sourceID, b.tr.HTML(lang, "card.looking", nil), nil)
if err != nil {
return
}
phID := int64(placeholder.MessageID)
info, err := b.svc.Probe(ctx, lr.url)
if err != nil {
if ctx.Err() == nil {
_ = b.edit(ctx, lr.chatID, phID, false, b.probeErrorText(lang, err), nil)
}
return
}
req := &db.Request{
ID: ids.New(),
UserID: lr.act.user.ID,
ChatID: lr.chatID,
ChatType: lr.chatType,
SourceMessageID: lr.sourceID,
CardMessageID: phID,
URL: lr.url,
Status: db.RequestReady,
Info: info.JSON(),
Lang: lang,
}
if lr.preset != "" {
req.Status = db.RequestChosen
}
if err := b.store.InsertRequest(ctx, req); err != nil {
log.Error("insert request", "err", err)
_ = b.edit(ctx, lr.chatID, phID, false, b.tr.HTML(lang, "error.internal", nil), nil)
return
}
log = log.With("request_id", req.ID)
if lr.preset != "" {
job, _, err := b.svc.Start(ctx, service.StartParams{
Request: req, Info: info, Profile: lr.preset,
StatusMessageID: phID, ReplyToMessageID: lr.sourceID,
})
if err != nil {
_ = b.edit(ctx, lr.chatID, phID, false, titleLine(info.Title)+"\n"+html.EscapeString(b.startErrorText(lang, err)), nil)
return
}
b.refreshStatus(ctx, job.ID)
return
}
text := b.cardText(lang, info, true)
kb := b.cardKeyboard(lang, req.ID, info)
if info.Thumbnail != "" {
msg, err := b.api.SendPhoto(ctx, &telego.SendPhotoParams{
ChatID: chatID(lr.chatID),
Photo: telego.InputFile{URL: info.Thumbnail},
Caption: clip(text, 1024),
ParseMode: telego.ModeHTML,
ReplyParameters: replyParams(lr.sourceID),
ReplyMarkup: kb,
})
if err == nil {
if err := b.store.SetRequestCard(context.WithoutCancel(ctx), req.ID, int64(msg.MessageID), true); err != nil {
log.Error("save card", "err", err)
}
b.deleteMessage(ctx, lr.chatID, phID)
return
}
// Telegram could not fetch the thumbnail. The text card still works.
log.Debug("photo card failed, using text card", "err", err)
}
_ = b.edit(ctx, lr.chatID, phID, false, text, kb)
}
// cardText renders the card: title, a line of facts and, for cards with
// buttons, the prompt to pick a format.
func (b *Bot) cardText(lang string, info *service.CardInfo, withPrompt bool) string {
var facts []string
if info.Uploader != "" {
facts = append(facts, html.EscapeString(shorten(info.Uploader, 40)))
}
if info.Duration > 0 {
facts = append(facts, i18n.Clock(info.Duration))
}
if info.Site != "" {
facts = append(facts, html.EscapeString(info.Site))
}
var sb strings.Builder
sb.WriteString(titleLine(info.Title))
if len(facts) > 0 {
sb.WriteString("\n")
sb.WriteString(strings.Join(facts, " · "))
}
if withPrompt {
sb.WriteString("\n\n")
sb.WriteString(b.tr.HTML(lang, "card.pick", nil))
}
return sb.String()
}
// probeErrorText maps a lookup failure to a friendly message. Raw yt-dlp
// output never reaches the user.
func (b *Bot) probeErrorText(lang string, err error) string {
if errors.Is(err, service.ErrPlaylist) {
return b.tr.HTML(lang, "error.playlist", nil)
}
return b.tr.HTML(lang, "error."+string(ytdlp.CodeOf(err)), nil)
}
// startErrorText maps a refused or failed start to plain text.
func (b *Bot) startErrorText(lang string, err error) string {
var le *service.LimitError
if errors.As(err, &le) {
return b.limitText(lang, le)
}
b.log.Error("start download", "err", err)
return b.tr.T(lang, "error.internal", nil)
}
// cbDownload handles a format button on a card.
func (b *Bot) cbDownload(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)
info, ierr := service.ParseCardInfo(req.Info)
if perr != nil || ierr != nil {
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
return
}
// Taking the request first makes a double tap start only one job.
took, err := b.store.TransitionRequest(ctx, req.ID, db.RequestReady, db.RequestChosen)
if err != nil {
b.log.Error("take request", "request_id", req.ID, "err", err)
b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true)
return
}
if !took {
b.answer(ctx, q, b.tr.T(act.lang, "notice.already_chosen", nil), false)
return
}
cardID, cardIsPhoto := cardMessage(q, req)
job, _, err := b.svc.Start(ctx, service.StartParams{
Request: req, Info: info, Profile: profile,
StatusMessageID: cardID, StatusIsPhoto: cardIsPhoto,
ReplyToMessageID: req.SourceMessageID,
})
if err != nil {
// Give the card back so another format can be picked.
if _, rerr := b.store.TransitionRequest(ctx, req.ID, db.RequestChosen, db.RequestReady); rerr != nil {
b.log.Error("release request", "request_id", req.ID, "err", rerr)
}
var le *service.LimitError
if errors.As(err, &le) && le.Upgradable {
// Over the limit, but a pass or a one-off payment would cover
// it: offer those instead of a dead end.
b.answer(ctx, q, "", false)
b.offerUpgrade(ctx, req.ChatID, cardID, act.lang, req, profile, le, isPrivate(req.ChatType))
return
}
b.answer(ctx, q, b.startErrorText(act.lang, err), true)
return
}
b.answer(ctx, q, "", false)
b.refreshStatus(ctx, job.ID)
}
// cbCancelCard handles the Cancel button on a card that has no job yet.
func (b *Bot) cbCancelCard(ctx context.Context, q *telego.CallbackQuery, act actor, requestID 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
}
took, err := b.store.TransitionRequest(ctx, req.ID, db.RequestReady, db.RequestCancelled)
if err != nil || !took {
b.answer(ctx, q, b.tr.T(act.lang, "notice.too_late", nil), false)
return
}
b.answer(ctx, q, b.tr.T(act.lang, "notice.cancelled", nil), false)
cardID, cardIsPhoto := cardMessage(q, req)
if err := b.api.DeleteMessage(ctx, &telego.DeleteMessageParams{
ChatID: chatID(req.ChatID), MessageID: int(cardID),
}); err != nil {
_ = b.edit(ctx, req.ChatID, cardID, cardIsPhoto, b.tr.HTML(req.Lang, "card.cancelled", nil), nil)
}
}
// cardMessage identifies the message a card button was pressed on. The
// callback itself is the source of truth: a press can arrive before the
// card's message ID has been saved with the request.
func cardMessage(q *telego.CallbackQuery, req *db.Request) (id int64, isPhoto bool) {
if q.Message == nil || q.Message.GetMessageID() == 0 {
return req.CardMessageID, req.CardIsPhoto
}
id = int64(q.Message.GetMessageID())
if m := q.Message.Message(); m != nil && q.Message.IsAccessible() {
return id, len(m.Photo) > 0
}
if id == req.CardMessageID {
return id, req.CardIsPhoto
}
return id, false
}