Files
Media-download-telegram-bot/internal/bot/commands.go
T
MichilisandClaude Fable 5.2 7d4893bc3f Phase 4: scale out
Remote workers, Postgres and S3, all chosen by configuration.

- Pull-based worker protocol over HTTP: claim (long poll), heartbeat,
  complete, fail, upload, source, probe. Workers need no inbound ports
- cmd/worker: standalone stateless worker with health endpoint and
  scheduled yt-dlp self-update
- Per-worker bearer tokens, stored hashed, revocable; identity always
  taken from the token; actions only on jobs the worker holds a lease for
- Tags: site_tags routes a site's jobs and lookups to workers that carry
  the required tags
- Drain, /workers, /ytdlp update, and "core worker add|revoke|list"
- Link lookups can run on remote workers (PROBE_MODE), so the core needs
  no yt-dlp and no residential address
- Postgres backend with pgx, same schema and queries; per-user advisory
  lock and job row lock where SQLite's serial writes were relied on
- The whole test suite runs on SQLite and on Postgres
- S3 storage backend with presigned worker uploads, sharing a conformance
  suite with the local backend
- Dockerfile with core, worker and faketelegram targets, docker-compose
  with optional Postgres and local Bot API server, systemd units
- deploy/acceptance/kill-worker.sh: kills a worker mid-job and checks
  that the other one delivers the file
- Fixes found on the way: /cancel could let the next playlist item start;
  a refund note could be missing when the sweep refunded first

Docker was not available on the build machine: the compose files were
validated with "docker compose config" only. The acceptance scenario was
run with real processes.

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

435 lines
13 KiB
Go

package bot
import (
"context"
"errors"
"strconv"
"strings"
"time"
"github.com/mymmrac/telego"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/i18n"
"github.com/noderunners/dlbot/internal/links"
"github.com/noderunners/dlbot/internal/media"
"github.com/noderunners/dlbot/internal/sched"
"github.com/noderunners/dlbot/internal/service"
)
// maxLinksPerMessage caps how many links of one message get a card.
const maxLinksPerMessage = 3
func (b *Bot) handleMessage(ctx context.Context, m *telego.Message) {
if m.From == nil || m.From.IsBot {
return
}
act, err := b.actorFor(ctx, m.From)
if err != nil {
b.log.Error("load user", "user_id", m.From.ID, "err", err)
return
}
if act.user.Banned {
return
}
private := isPrivate(m.Chat.Type)
cmd, forUs, isCmd := b.parseCommand(m)
if isCmd {
if !forUs {
return // addressed to another bot in the group
}
switch cmd {
case "start":
b.cmdStart(ctx, m, act)
case "help":
b.cmdHelp(ctx, m, act)
case "dl":
b.cmdDownload(ctx, m, act, "")
case "audio":
b.cmdDownload(ctx, m, act, media.MP3)
case "thumb":
b.cmdDownload(ctx, m, act, media.Thumb)
case "fresh":
b.cmdLink(ctx, m, act, linkRequest{fresh: true})
case "subs":
b.cmdLink(ctx, m, act, linkRequest{subs: true})
case "history":
b.cmdHistory(ctx, m, act)
case "purge":
if b.isOwner(m) {
b.cmdPurge(ctx, m, act)
}
case "cache":
if b.isOwner(m) {
b.cmdCache(ctx, m, act)
}
case "workers":
if b.isOwner(m) {
b.cmdWorkers(ctx, m, act)
}
case "drain":
if b.isOwner(m) {
b.cmdDrain(ctx, m, act)
}
case "ytdlp":
if b.isOwner(m) {
b.cmdYtDlp(ctx, m, act)
}
case "info":
b.cmdInfo(ctx, m, act)
case "queue":
b.cmdQueue(ctx, m, act)
case "cancel":
b.cmdCancel(ctx, m, act)
case "buy":
b.cmdBuy(ctx, m, act)
case "account":
b.cmdAccount(ctx, m, act)
case "limits":
b.cmdLimits(ctx, m, act)
case "credits":
b.cmdCredits(ctx, m, act)
case "donate":
b.cmdDonate(ctx, m, act)
case "redeem":
b.cmdRedeem(ctx, m, act, commandArgs(m))
case "referral":
b.cmdReferral(ctx, m, act)
default:
if private {
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "cmd.unknown", nil), nil)
}
}
return
}
if !private {
return // groups are driven by commands; auto-detect is an admin opt-in
}
urls := messageLinks(m)
if len(urls) == 0 {
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "hint.send_link", nil), nil)
return
}
if len(urls) > maxLinksPerMessage {
urls = urls[:maxLinksPerMessage]
}
for _, u := range urls {
b.startLink(ctx, linkRequest{
chatID: m.Chat.ID, chatType: m.Chat.Type, sourceID: int64(m.MessageID), act: act, url: u,
})
}
}
// commandArgs returns the text after the command of a message.
func commandArgs(m *telego.Message) string {
for _, e := range m.Entities {
if e.Type == telego.EntityTypeBotCommand && e.Offset == 0 && e.Length <= len(m.Text) {
return strings.TrimSpace(m.Text[e.Length:])
}
}
return ""
}
// parseCommand finds a bot command at the start of the message. forUs is
// false when the command names a different bot (/dl@otherbot).
func (b *Bot) parseCommand(m *telego.Message) (cmd string, forUs, isCmd bool) {
for _, e := range m.Entities {
if e.Type != telego.EntityTypeBotCommand || e.Offset != 0 {
continue
}
// Commands are ASCII, so the UTF-16 length is also the byte length.
if e.Length > len(m.Text) || e.Length < 2 {
return "", false, false
}
full := m.Text[1:e.Length]
name, target, hasTarget := strings.Cut(full, "@")
if hasTarget && !strings.EqualFold(target, b.username) {
return "", false, true
}
return strings.ToLower(name), true, true
}
return "", false, false
}
func toLinkEntities(ents []telego.MessageEntity) []links.Entity {
out := make([]links.Entity, 0, len(ents))
for _, e := range ents {
out = append(out, links.Entity{Type: e.Type, Offset: e.Offset, Length: e.Length, URL: e.URL})
}
return out
}
// messageLinks extracts links from the text or the caption of a message.
func messageLinks(m *telego.Message) []string {
if m == nil {
return nil
}
if urls := links.Extract(m.Text, toLinkEntities(m.Entities)); len(urls) > 0 {
return urls
}
return links.Extract(m.Caption, toLinkEntities(m.CaptionEntities))
}
func (b *Bot) cmdStart(ctx context.Context, m *telego.Message, act actor) {
if !isPrivate(m.Chat.Type) {
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "start.group", nil), nil)
return
}
// Deep links arrive as "/start <payload>".
payload := commandArgs(m)
switch {
case strings.HasPrefix(payload, "buy_"):
b.startBuyLink(ctx, m, act, strings.TrimPrefix(payload, "buy_"))
return
case strings.HasPrefix(payload, "skip_"):
b.startSkipLink(ctx, m, act, strings.TrimPrefix(payload, "skip_"))
return
case payload == "buy":
b.showBuy(ctx, m.Chat.ID, act)
return
case strings.HasPrefix(payload, "ref_"):
// Only somebody who is new to the bot can be referred.
if referrer, err := strconv.ParseInt(strings.TrimPrefix(payload, "ref_"), 10, 64); err == nil && act.user.IsNew {
if _, err := b.store.SetReferrer(ctx, act.user.ID, referrer); err != nil {
b.log.Error("set referrer", "user_id", act.user.ID, "err", err)
}
}
}
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "start.private", i18n.Args{"Name": act.user.FirstName}), nil)
}
func (b *Bot) cmdHelp(ctx context.Context, m *telego.Message, act actor) {
dec, err := b.svc.Entitlement(ctx, service.Who{UserID: act.user.ID, ChatID: m.Chat.ID, ChatType: m.Chat.Type}, false)
if err != nil {
b.internalError(ctx, m.Chat.ID, act, err)
return
}
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "help.text", i18n.Args{
"MaxSize": b.tr.Size(act.lang, dec.Limits.MaxSize),
"MaxDuration": b.tr.Span(act.lang, secondsDuration(dec.Limits.MaxDuration)),
}), nil)
}
// cmdDownload handles /dl, /audio and /thumb. The link comes from the
// command itself or from the message the command replies to. The bot
// answers under the message that holds the link.
func (b *Bot) cmdDownload(ctx context.Context, m *telego.Message, act actor, preset media.Profile) {
urls := messageLinks(m)
source := int64(m.MessageID)
if len(urls) == 0 && m.ReplyToMessage != nil {
urls = messageLinks(m.ReplyToMessage)
source = int64(m.ReplyToMessage.MessageID)
}
if len(urls) == 0 {
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "dl.usage", nil), nil)
return
}
b.startLink(ctx, linkRequest{
chatID: m.Chat.ID, chatType: m.Chat.Type, sourceID: source, act: act, url: urls[0], preset: preset,
})
}
// cmdLink handles the commands that take a link and differ only in how
// the link flow runs: /fresh and /subs.
func (b *Bot) cmdLink(ctx context.Context, m *telego.Message, act actor, lr linkRequest) {
urls := messageLinks(m)
source := int64(m.MessageID)
if len(urls) == 0 && m.ReplyToMessage != nil {
urls = messageLinks(m.ReplyToMessage)
source = int64(m.ReplyToMessage.MessageID)
}
if len(urls) == 0 {
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "dl.usage", nil), nil)
return
}
lr.chatID, lr.chatType, lr.sourceID, lr.act, lr.url = m.Chat.ID, m.Chat.Type, source, act, urls[0]
b.startLink(ctx, lr)
}
func (b *Bot) cmdInfo(ctx context.Context, m *telego.Message, act actor) {
urls := messageLinks(m)
if len(urls) == 0 && m.ReplyToMessage != nil {
urls = messageLinks(m.ReplyToMessage)
}
if len(urls) == 0 {
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "info.usage", nil), nil)
return
}
url := urls[0]
b.goBG("info", func() {
b.chatAction(ctx, m.Chat.ID, telego.ChatActionTyping)
info, err := b.svc.Probe(ctx, url)
if err != nil {
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.probeErrorText(act.lang, err), nil)
return
}
var sb strings.Builder
sb.WriteString(b.cardText(act.lang, info, false))
sb.WriteString("\n")
profiles := append([]media.Profile{}, media.VideoProfiles...)
if info.HasAudio {
profiles = append(profiles, media.MP3, media.M4A)
}
for _, p := range profiles {
if h := p.Height(); h > 0 && info.MaxHeight > 0 && info.MaxHeight < h {
continue
}
size := b.tr.T(act.lang, "info.size_unknown", nil)
if n := info.Sizes[string(p)]; n > 0 {
size = b.tr.Size(act.lang, n)
}
sb.WriteString("\n")
sb.WriteString(b.tr.HTML(act.lang, "info.line", i18n.Args{"Label": b.profileLabel(act.lang, p), "Size": size}))
}
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), sb.String(), nil)
})
}
func (b *Bot) cmdQueue(ctx context.Context, m *telego.Message, act actor) {
dels, err := b.store.ActiveDeliveriesForUser(ctx, act.user.ID)
if err != nil {
b.log.Error("list deliveries", "err", err)
return
}
if len(dels) == 0 {
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "queue.empty", nil), nil)
return
}
var sb strings.Builder
sb.WriteString(b.tr.HTML(act.lang, "queue.header", i18n.Args{"Count": len(dels)}))
for _, d := range dels {
job, err := b.store.GetJob(ctx, d.JobID)
if err != nil {
continue
}
text, _, _ := b.renderStatus(ctx, d, job)
sb.WriteString("\n\n")
sb.WriteString(text)
}
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), sb.String(), nil)
}
func (b *Bot) cmdCancel(ctx context.Context, m *telego.Message, act actor) {
n := 0
// Playlist items that have not started go first. Cancelling a running
// download frees a slot, and the next waiting item would take it.
b.statusMu.Lock()
b.cancelledAt[act.user.ID] = time.Now()
b.statusMu.Unlock()
if waiting, err := b.store.CancelWaitingRequests(ctx, act.user.ID); err == nil {
n += int(waiting)
}
dels, err := b.store.ActiveDeliveriesForUser(ctx, act.user.ID)
if err != nil {
b.log.Error("list deliveries", "err", err)
return
}
for _, d := range dels {
if b.cancelDelivery(ctx, d.ID, act.user.ID) == nil {
n++
}
}
key := "cancel.done"
if n == 0 {
key = "cancel.nothing"
}
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, key, i18n.Args{"Count": n}), nil)
}
// cancelDelivery withdraws one delivery and updates its status message.
func (b *Bot) cancelDelivery(ctx context.Context, deliveryID string, userID int64) error {
d, err := b.sched.CancelDelivery(ctx, deliveryID, userID)
if err != nil {
return err
}
note := b.release(ctx, d)
job, err := b.store.GetJob(ctx, d.JobID)
if err != nil {
return nil
}
b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.cancelled", nil)+note)
return nil
}
// release gives back what an undelivered download took and returns a line
// to append to the status when sats were refunded.
func (b *Bot) release(ctx context.Context, d *db.Delivery) string {
bg := context.WithoutCancel(ctx)
refunded, err := b.svc.Release(bg, d.ID)
if err != nil {
b.log.Error("release delivery", "delivery_id", d.ID, "err", err)
return ""
}
if refunded <= 0 {
// Another path may have released it a moment ago.
refunded = b.svc.Refunded(bg, d.ID)
}
if refunded <= 0 {
return ""
}
return "\n" + b.tr.HTML(d.Lang, "status.refunded", i18n.Args{"Amount": b.tr.Sats(d.Lang, refunded)})
}
func (b *Bot) handleCallback(ctx context.Context, q *telego.CallbackQuery) {
act, err := b.actorFor(ctx, &q.From)
if err != nil {
b.log.Error("load user", "user_id", q.From.ID, "err", err)
return
}
if act.user.Banned {
b.answer(ctx, q, "", false)
return
}
action, id, arg := parseCallback(q.Data)
switch action {
case cbDownload:
b.cbDownload(ctx, q, act, id, arg)
case cbCancelCard:
b.cbCancelCard(ctx, q, act, id)
case cbPlaylist:
b.cbPlaylistStart(ctx, q, act, id, arg)
case cbResend:
b.cbResendFile(ctx, q, act, id)
case cbSkipQueue:
b.cbSkip(ctx, q, act, id)
case cbBuy:
b.cbBuyProduct(ctx, q, act, id, arg)
case cbOfferBuy:
b.cbOffer(ctx, q, act, id, arg)
case cbPayCheck:
b.cbPayCheck(ctx, q, act, id)
case cbPayCancel:
b.cbPayCancel(ctx, q, act, id)
case cbCancelJob:
err := b.cancelDelivery(ctx, id, act.user.ID)
switch {
case err == nil:
b.answer(ctx, q, b.tr.T(act.lang, "notice.cancelled", nil), false)
case errors.Is(err, sched.ErrNotOwner):
b.answer(ctx, q, b.tr.T(act.lang, "notice.not_yours", nil), false)
case errors.Is(err, sched.ErrTooLate), errors.Is(err, db.ErrNotFound):
b.answer(ctx, q, b.tr.T(act.lang, "notice.too_late", nil), false)
default:
b.log.Error("cancel delivery", "delivery_id", id, "err", err)
b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true)
}
default:
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
}
}
// limitText renders a limit refusal for the user as plain text.
func (b *Bot) limitText(lang string, le *service.LimitError) string {
l := le.Decision.Limits
count := l.ActiveJobs
if le.Code == service.LimitDailyDownloads {
count = l.DailyDownloads
}
return b.tr.T(lang, "limit."+le.Code, i18n.Args{
"MaxSize": b.tr.Size(lang, l.MaxSize),
"MaxDuration": b.tr.Span(lang, secondsDuration(l.MaxDuration)),
"MaxVolume": b.tr.Size(lang, l.DailyBytes),
"Count": count,
})
}