Files
Media-download-telegram-bot/internal/bot/deliver.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

355 lines
11 KiB
Go

package bot
import (
"context"
"errors"
"io"
"time"
"github.com/mymmrac/telego"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/media"
"github.com/noderunners/dlbot/internal/sched"
"github.com/noderunners/dlbot/internal/storage"
"github.com/noderunners/dlbot/internal/tg"
)
// maxSendAttempts is how often one delivery is tried before giving up.
const maxSendAttempts = 3
// uploadTimeout bounds one upload to Telegram.
const uploadTimeout = 30 * time.Minute
// namedReader gives a storage stream the file name Telegram should show.
type namedReader struct {
io.Reader
name string
}
func (n namedReader) Name() string { return n.name }
// deliverJob sends the stored file of a job to every waiting requester.
// It is safe to call more than once: a job is delivered by one goroutine
// at a time and each delivery is taken with an atomic status change.
func (b *Bot) deliverJob(ctx context.Context, jobID string) {
b.statusMu.Lock()
if b.sending[jobID] {
b.statusMu.Unlock()
return
}
b.sending[jobID] = true
b.statusMu.Unlock()
defer func() {
b.statusMu.Lock()
delete(b.sending, jobID)
b.statusMu.Unlock()
}()
select {
case b.uploads <- struct{}{}:
defer func() { <-b.uploads }()
case <-ctx.Done():
return
}
job, err := b.store.GetJob(ctx, jobID)
if err != nil || job.Status != db.JobDelivering {
return
}
dels, err := b.store.DeliveriesForJob(ctx, jobID, db.DeliveryPending)
if err != nil {
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
for _, d := range dels {
if ctx.Err() != nil {
return
}
if id := b.deliverOne(ctx, job, d, fileID); id != "" {
fileID = id
}
}
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 {
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 ""
}
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)
stopAction()
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.
_, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryPending, "")
case tg.IsBlocked(err):
log.Info("requester unreachable", "err", err)
_, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryFailed, "blocked")
b.release(ctx, d)
case tg.IsFileTooBig(err):
log.Warn("telegram refused file size", "size", job.FileSize, "err", err)
_, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryFailed, "too_large")
b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, "too_large")+b.release(ctx, d))
case d.Attempts+1 < maxSendAttempts:
log.Warn("send failed, will retry", "attempt", d.Attempts+1, "err", err)
if wait := tg.RetryAfter(err); wait > 0 && wait <= time.Minute {
sleepCtx(ctx, wait)
}
_, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryPending, "send_failed")
default:
log.Error("send failed, giving up", "err", err)
_, _ = 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 ""
}
if err := b.store.MarkDeliverySent(context.WithoutCancel(ctx), d.ID, fileID, messageID); err != nil {
log.Error("mark delivery sent", "err", err)
}
if err := b.svc.RecordDelivered(context.WithoutCancel(ctx), d, job.FileSize); err != nil {
log.Error("record usage", "err", err)
}
log.Info("file delivered", "size", job.FileSize, "profile", job.Profile)
b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.done", nil))
return fileID
}
// streamable lists the containers Telegram plays inline as video.
func streamable(ext string) bool {
switch ext {
case "mp4", "m4v", "mov":
return true
}
return false
}
func uploadAction(job *db.Job) string {
switch jobProfile(job).Kind() {
case media.KindVideo:
if streamable(job.FileExt) {
return telego.ChatActionUploadVideo
}
case media.KindAudio:
return telego.ChatActionUploadVoice
case media.KindThumb:
return telego.ChatActionUploadPhoto
}
return telego.ChatActionUploadDocument
}
// keepChatAction shows the "sending a file" indicator until stop is
// called. Telegram clears it after five seconds, so it is repeated.
func (b *Bot) keepChatAction(ctx context.Context, chat int64, action string) (stop func()) {
done := make(chan struct{})
go func() {
t := time.NewTicker(4500 * time.Millisecond)
defer t.Stop()
for {
b.chatAction(ctx, chat, action)
select {
case <-done:
return
case <-ctx.Done():
return
case <-t.C:
}
}
}()
return func() { close(done) }
}
// 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) {
kind := jobProfile(job).Kind()
mode := "document"
switch {
case kind == media.KindVideo && streamable(job.FileExt):
mode = "video"
case kind == media.KindAudio:
mode = "audio"
case kind == media.KindThumb:
mode = "photo"
}
fileID, messageID, 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
}
func (b *Bot) sendAs(ctx context.Context, mode string, job *db.Job, d *db.Delivery, reuseFileID string) (string, int64, 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")
}
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 "", 0, err
}
defer rc.Close()
input = telego.InputFile{File: namedReader{Reader: rc, name: fileName(job.Title, job.FileExt)}}
}
caption := clip(titleLine(job.Title), 1024)
chat := chatID(d.ChatID)
reply := replyParams(d.ReplyToMessageID)
switch mode {
case "video":
msg, err := b.api.SendVideo(ctx, &telego.SendVideoParams{
ChatID: chat, Video: input, Caption: caption, ParseMode: telego.ModeHTML,
Duration: int(job.Duration), Width: job.Width, Height: job.Height,
SupportsStreaming: true, ReplyParameters: reply,
})
if err != nil {
return "", 0, err
}
if msg.Video != nil {
return msg.Video.FileID, int64(msg.MessageID), nil
}
if msg.Document != nil { // Telegram may store odd videos as documents
return msg.Document.FileID, int64(msg.MessageID), nil
}
return "", 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
}
if msg.Audio != nil {
return msg.Audio.FileID, int64(msg.MessageID), nil
}
return "", 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
}
if n := len(msg.Photo); n > 0 {
return msg.Photo[n-1].FileID, int64(msg.MessageID), nil
}
return "", 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
}
if msg.Document != nil {
return msg.Document.FileID, int64(msg.MessageID), nil
}
return "", 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.
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)
return
}
b.removeStored(ctx, job)
}
func (b *Bot) removeStored(ctx context.Context, job *db.Job) {
if job.StorageKey == "" {
return
}
if err := b.storage.Delete(ctx, job.StorageKey); err != nil {
b.log.Warn("delete stored file", "job_id", job.ID, "key", job.StorageKey, "err", err)
}
}
// failJob tells every waiting requester that the job failed.
func (b *Bot) failJob(ctx context.Context, jobID string) {
job, err := b.store.GetJob(ctx, jobID)
if err != nil || job.Status != db.JobFailed {
return
}
dels, err := b.store.DeliveriesForJob(ctx, jobID, db.DeliveryPending)
if err != nil {
b.log.Error("list deliveries", "job_id", jobID, "err", err)
return
}
for _, d := range dels {
took, err := b.store.TransitionDelivery(ctx, d.ID, db.DeliveryPending, db.DeliveryFailed, job.ErrorCode)
if err != nil || !took {
continue
}
// The automatic retry is spent: give back what the download cost.
b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, job.ErrorCode)+b.release(ctx, d))
}
b.removeStored(ctx, job)
}
// cleanupCancelled closes the deliveries of a cancelled job and removes
// any file the worker had already stored.
func (b *Bot) cleanupCancelled(ctx context.Context, jobID string) {
job, err := b.store.GetJob(ctx, jobID)
if err != nil || job.Status != db.JobCancelled {
return
}
dels, err := b.store.DeliveriesForJob(ctx, jobID, db.DeliveryPending)
if err == nil {
for _, d := range dels {
took, err := b.store.TransitionDelivery(ctx, d.ID, db.DeliveryPending, db.DeliveryCancelled, "")
if err != nil || !took {
continue
}
b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.cancelled", nil)+b.release(ctx, d))
}
}
// The worker may have uploaded before it noticed the cancel.
if err := b.storage.Delete(ctx, sched.UploadKey(job.ID)); err != nil {
b.log.Debug("delete cancelled upload", "job_id", job.ID, "err", err)
}
}
func sleepCtx(ctx context.Context, d time.Duration) {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
case <-t.C:
}
}