Phase 1: core bot
Link in, card, download, send, in private chats and groups. - cmd/core with an embedded download worker - Telegram front end on telego v1.13.0 (Bot API 10.4): link card with thumbnail and format buttons, one live status message, /dl /audio /thumb /info /queue /cancel, group support with requester-only buttons - Database backed queue: paid and free lanes, leases with heartbeats, one automatic retry, cancel, queue position and wait estimate - yt-dlp and ffprobe behind a Runner interface with classified, redacted errors mapped to friendly messages - SQLite via modernc with goose migrations, portable schema - Local file storage behind a Storage interface - go-i18n with an English catalog, no literal text in handlers - Free tier limits enforced before queueing and again on the real file - Bot token and webhook secret are stripped from all log output - Tests: URL parsing, job lifecycle, worker, yt-dlp wrapper, and end to end flows against a fake Bot API server; opt-in test with the real yt-dlp Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,293 @@
|
||||
package bot
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"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 "info":
|
||||
b.cmdInfo(ctx, m, act)
|
||||
case "queue":
|
||||
b.cmdQueue(ctx, m, act)
|
||||
case "cancel":
|
||||
b.cmdCancel(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,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 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) {
|
||||
key := "start.private"
|
||||
if !isPrivate(m.Chat.Type) {
|
||||
key = "start.group"
|
||||
}
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, key, i18n.Args{"Name": act.user.FirstName}), nil)
|
||||
}
|
||||
|
||||
func (b *Bot) cmdHelp(ctx context.Context, m *telego.Message, act actor) {
|
||||
lim := b.svc.LimitsFor(ctx, act.user.ID)
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "help.text", i18n.Args{
|
||||
"MaxSize": b.tr.Size(act.lang, lim.MaxSize),
|
||||
"MaxDuration": b.tr.Span(act.lang, secondsDuration(lim.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,
|
||||
})
|
||||
}
|
||||
|
||||
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) {
|
||||
dels, err := b.store.ActiveDeliveriesForUser(ctx, act.user.ID)
|
||||
if err != nil {
|
||||
b.log.Error("list deliveries", "err", err)
|
||||
return
|
||||
}
|
||||
n := 0
|
||||
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
|
||||
}
|
||||
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))
|
||||
return nil
|
||||
}
|
||||
|
||||
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 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.
|
||||
func (b *Bot) limitText(lang string, le *service.LimitError) string {
|
||||
return b.tr.T(lang, "limit."+le.Code, i18n.Args{
|
||||
"MaxSize": b.tr.Size(lang, le.Limits.MaxSize),
|
||||
"MaxDuration": b.tr.Span(lang, secondsDuration(le.Limits.MaxDuration)),
|
||||
"Count": le.Limits.ActiveJobs,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user