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:
Michilis
2026-11-18 07:33:32 +00:00
co-authored by Claude Fable 5.2
commit 3b361c17a1
63 changed files with 10715 additions and 0 deletions
+317
View File
@@ -0,0 +1,317 @@
// Package bot is the Telegram front end: it turns updates into requests
// and jobs, keeps the status message of every delivery current and sends
// finished files.
package bot
import (
"context"
"fmt"
"log/slog"
"runtime/debug"
"sync"
"time"
"github.com/mymmrac/telego"
"github.com/noderunners/dlbot/internal/config"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/i18n"
"github.com/noderunners/dlbot/internal/sched"
"github.com/noderunners/dlbot/internal/service"
"github.com/noderunners/dlbot/internal/storage"
"github.com/noderunners/dlbot/internal/tg"
)
// Deps are the collaborators of the bot.
type Deps struct {
API tg.API
Config config.Config
Store *db.Store
Sched *sched.Scheduler
Service *service.Service
Storage storage.Storage
I18n *i18n.Bundle
Log *slog.Logger
// WorkerSlots is the number of download slots serving the queue. It
// only feeds the wait estimate.
WorkerSlots func() int
}
// Bot handles Telegram updates and job events.
type Bot struct {
api tg.API
cfg config.Config
store *db.Store
sched *sched.Scheduler
svc *service.Service
storage storage.Storage
tr *i18n.Bundle
log *slog.Logger
slots func() int
id int64
username string
events chan sched.Event
uploads chan struct{} // limits concurrent uploads to Telegram
bg sync.WaitGroup
baseCtx context.Context
statusMu sync.Mutex
statuses map[string]*statusState // by delivery ID
sending map[string]bool // jobs being delivered right now
// Tunables, shortened in tests.
reconcileEvery time.Duration
statusMinGap time.Duration
}
// New creates the bot and learns its own username, which is needed to
// recognize commands addressed as /cmd@botname.
func New(ctx context.Context, d Deps) (*Bot, error) {
me, err := d.API.GetMe(ctx)
if err != nil {
return nil, fmt.Errorf("bot: getMe: %w", err)
}
if d.Log == nil {
d.Log = slog.Default()
}
if d.WorkerSlots == nil {
d.WorkerSlots = func() int { return 1 }
}
b := &Bot{
api: d.API,
cfg: d.Config,
store: d.Store,
sched: d.Sched,
svc: d.Service,
storage: d.Storage,
tr: d.I18n,
log: d.Log,
slots: d.WorkerSlots,
id: me.ID,
username: me.Username,
events: make(chan sched.Event, 1024),
uploads: make(chan struct{}, 4),
baseCtx: ctx,
statuses: map[string]*statusState{},
sending: map[string]bool{},
reconcileEvery: 5 * time.Second,
statusMinGap: 3 * time.Second,
}
d.Sched.Subscribe(func(ev sched.Event) {
select {
case b.events <- ev:
default:
// The reconcile loop picks up anything dropped here.
}
})
return b, nil
}
// Username returns the bot's @username without the at sign.
func (b *Bot) Username() string { return b.username }
// SetTimings overrides the reconcile interval and the minimum gap between
// status edits. Tests use it to run fast.
func (b *Bot) SetTimings(reconcile, statusGap time.Duration) {
b.reconcileEvery = reconcile
b.statusMinGap = statusGap
}
// Run processes updates and job events until ctx ends, then waits for
// in-flight work to finish.
func (b *Bot) Run(ctx context.Context, updates <-chan telego.Update) {
b.baseCtx = ctx
n := b.cfg.Telegram.UpdateWorkers
if n < 1 {
n = 1
}
// Updates of one chat always go to the same worker, so they are
// handled in order.
lanes := make([]chan telego.Update, n)
var wg sync.WaitGroup
for i := range lanes {
lanes[i] = make(chan telego.Update, 64)
wg.Add(1)
go func(ch <-chan telego.Update) {
defer wg.Done()
for u := range ch {
b.safely("update", func() { b.HandleUpdate(ctx, u) })
}
}(lanes[i])
}
wg.Add(1)
go func() {
defer wg.Done()
b.eventLoop(ctx)
}()
loop:
for {
select {
case <-ctx.Done():
break loop
case u, ok := <-updates:
if !ok {
break loop
}
key := updateChatID(u)
if key < 0 {
key = -key
}
select {
case lanes[int(key%int64(n))] <- u:
case <-ctx.Done():
break loop
}
}
}
for _, ch := range lanes {
close(ch)
}
wg.Wait()
b.bg.Wait()
}
// goBG runs fn in the background and tracks it for shutdown.
func (b *Bot) goBG(name string, fn func()) {
b.bg.Add(1)
go func() {
defer b.bg.Done()
b.safely(name, fn)
}()
}
func (b *Bot) safely(name string, fn func()) {
defer func() {
if r := recover(); r != nil {
b.log.Error("panic recovered", "where", name, "panic", fmt.Sprint(r), "stack", string(debug.Stack()))
}
}()
fn()
}
func updateChatID(u telego.Update) int64 {
switch {
case u.Message != nil:
return u.Message.Chat.ID
case u.CallbackQuery != nil:
if u.CallbackQuery.Message != nil {
return u.CallbackQuery.Message.GetChat().ID
}
return u.CallbackQuery.From.ID
}
return int64(u.UpdateID)
}
// HandleUpdate routes one update.
func (b *Bot) HandleUpdate(ctx context.Context, u telego.Update) {
switch {
case u.Message != nil:
b.handleMessage(ctx, u.Message)
case u.CallbackQuery != nil:
b.handleCallback(ctx, u.CallbackQuery)
}
}
// actor is the user behind an update, with the language to answer in.
type actor struct {
user *db.User
lang string
}
func (b *Bot) actorFor(ctx context.Context, from *telego.User) (actor, error) {
u, err := b.store.UpsertUser(ctx, from.ID, from.Username, from.FirstName, from.LanguageCode)
if err != nil {
return actor{}, err
}
lang := u.LangOverride
if lang == "" {
lang = b.tr.Resolve(u.Lang)
}
return actor{user: u, lang: lang}, nil
}
func isPrivate(chatType string) bool { return chatType == telego.ChatTypePrivate }
// --- sending helpers -------------------------------------------------------
func chatID(id int64) telego.ChatID { return telego.ChatID{ID: id} }
func replyParams(messageID int64) *telego.ReplyParameters {
if messageID == 0 {
return nil
}
return &telego.ReplyParameters{MessageID: int(messageID), AllowSendingWithoutReply: true}
}
var noPreview = &telego.LinkPreviewOptions{IsDisabled: true}
// send posts an HTML message, optionally as a reply and with buttons.
func (b *Bot) send(ctx context.Context, chat, replyTo int64, text string, kb *telego.InlineKeyboardMarkup) (*telego.Message, error) {
p := &telego.SendMessageParams{
ChatID: chatID(chat),
Text: text,
ParseMode: telego.ModeHTML,
LinkPreviewOptions: noPreview,
ReplyParameters: replyParams(replyTo),
}
if kb != nil {
p.ReplyMarkup = kb
}
msg, err := b.api.SendMessage(ctx, p)
if err != nil {
b.log.Warn("sendMessage failed", "chat_id", chat, "err", err)
}
return msg, err
}
// edit changes the text (or the caption, for photo cards) and the buttons
// of a message. A nil keyboard removes the buttons.
func (b *Bot) edit(ctx context.Context, chat, messageID int64, isPhoto bool, text string, kb *telego.InlineKeyboardMarkup) error {
if messageID == 0 {
return nil
}
var err error
if isPhoto {
_, err = b.api.EditMessageCaption(ctx, &telego.EditMessageCaptionParams{
ChatID: chatID(chat), MessageID: int(messageID), Caption: clip(text, 1024),
ParseMode: telego.ModeHTML, ReplyMarkup: kb,
})
} else {
_, err = b.api.EditMessageText(ctx, &telego.EditMessageTextParams{
ChatID: chatID(chat), MessageID: int(messageID), Text: clip(text, 4096),
ParseMode: telego.ModeHTML, LinkPreviewOptions: noPreview, ReplyMarkup: kb,
})
}
if err != nil && !tg.IsNotModified(err) {
if !tg.IsMessageGone(err) {
b.log.Warn("edit failed", "chat_id", chat, "message_id", messageID, "err", err)
}
return err
}
return nil
}
// answer acknowledges a button press, optionally with a short notice.
func (b *Bot) answer(ctx context.Context, q *telego.CallbackQuery, text string, alert bool) {
err := b.api.AnswerCallbackQuery(ctx, &telego.AnswerCallbackQueryParams{
CallbackQueryID: q.ID, Text: clip(text, 200), ShowAlert: alert,
})
if err != nil {
b.log.Debug("answerCallbackQuery failed", "err", err)
}
}
func (b *Bot) deleteMessage(ctx context.Context, chat, messageID int64) {
if messageID == 0 {
return
}
if err := b.api.DeleteMessage(ctx, &telego.DeleteMessageParams{ChatID: chatID(chat), MessageID: int(messageID)}); err != nil {
b.log.Debug("deleteMessage failed", "chat_id", chat, "err", err)
}
}
func (b *Bot) chatAction(ctx context.Context, chat int64, action string) {
_ = b.api.SendChatAction(ctx, &telego.SendChatActionParams{ChatID: chatID(chat), Action: action})
}
+250
View File
@@ -0,0 +1,250 @@
package bot
import (
"context"
"errors"
"html"
"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) {
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(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)
}
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
}
+293
View File
@@ -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,
})
}
+349
View File
@@ -0,0 +1,349 @@
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")
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"))
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"))
}
return ""
}
if err := b.store.MarkDeliverySent(context.WithoutCancel(ctx), d.ID, fileID, messageID); err != nil {
log.Error("mark delivery sent", "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
}
b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, job.ErrorCode))
}
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))
}
}
// 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:
}
}
+90
View File
@@ -0,0 +1,90 @@
package bot
import (
"strings"
"github.com/mymmrac/telego"
"github.com/noderunners/dlbot/internal/i18n"
"github.com/noderunners/dlbot/internal/media"
"github.com/noderunners/dlbot/internal/service"
)
// Callback data is "<action>:<id>[:<arg>]". It carries identifiers only,
// never translated text, so buttons keep working when the language changes.
const (
cbDownload = "dl" // dl:<request id>:<profile>
cbCancelCard = "cx" // cx:<request id>
cbCancelJob = "jc" // jc:<delivery id>
)
func cbData(parts ...string) string { return strings.Join(parts, ":") }
// parseCallback splits callback data into the action, the ID and the rest.
func parseCallback(data string) (action, id, arg string) {
parts := strings.SplitN(data, ":", 3)
action = parts[0]
if len(parts) > 1 {
id = parts[1]
}
if len(parts) > 2 {
arg = parts[2]
}
return
}
func button(text, data string) telego.InlineKeyboardButton {
return telego.InlineKeyboardButton{Text: text, CallbackData: data}
}
func keyboard(rows ...[]telego.InlineKeyboardButton) *telego.InlineKeyboardMarkup {
var kept [][]telego.InlineKeyboardButton
for _, r := range rows {
if len(r) > 0 {
kept = append(kept, r)
}
}
return &telego.InlineKeyboardMarkup{InlineKeyboard: kept}
}
// cardProfiles picks the video buttons worth showing: Best always, then the
// lower resolutions the source can actually be scaled down to.
func cardProfiles(info *service.CardInfo) []media.Profile {
out := []media.Profile{media.Best}
for _, p := range []media.Profile{media.P720, media.P480} {
if info.MaxHeight == 0 || info.MaxHeight > p.Height() {
out = append(out, p)
}
}
return out
}
// cardKeyboard builds the format buttons of a link card.
func (b *Bot) cardKeyboard(lang, requestID string, info *service.CardInfo) *telego.InlineKeyboardMarkup {
label := func(p media.Profile) string {
name := b.profileLabel(lang, p)
if size := info.Sizes[string(p)]; size > 0 {
return b.tr.T(lang, "btn.with_size", i18n.Args{"Label": name, "Size": b.tr.Size(lang, size)})
}
return name
}
var video, extra []telego.InlineKeyboardButton
for _, p := range cardProfiles(info) {
video = append(video, button(label(p), cbData(cbDownload, requestID, string(p))))
}
if info.HasAudio {
extra = append(extra, button(label(media.MP3), cbData(cbDownload, requestID, string(media.MP3))))
}
if info.Thumbnail != "" {
extra = append(extra, button(b.profileLabel(lang, media.Thumb), cbData(cbDownload, requestID, string(media.Thumb))))
}
cancel := []telego.InlineKeyboardButton{button(b.tr.T(lang, "btn.cancel", nil), cbData(cbCancelCard, requestID))}
return keyboard(video, extra, cancel)
}
// cancelJobKeyboard is the single Cancel button under a live status.
func (b *Bot) cancelJobKeyboard(lang, deliveryID string) *telego.InlineKeyboardMarkup {
return keyboard([]telego.InlineKeyboardButton{
button(b.tr.T(lang, "btn.cancel", nil), cbData(cbCancelJob, deliveryID)),
})
}
+32
View File
@@ -0,0 +1,32 @@
package bot
import (
"context"
"github.com/mymmrac/telego"
)
// menuCommands are the commands shown in Telegram's command menu, in
// order. Names are lowercase ASCII in every language; only descriptions
// are translated, under "menu.<name>".
var menuCommands = []string{"dl", "audio", "thumb", "info", "queue", "cancel", "help"}
// RegisterCommands publishes the command menu. A failure is logged and
// otherwise ignored: the bot works without a menu.
func (b *Bot) RegisterCommands(ctx context.Context) {
for _, lang := range b.tr.Langs() {
cmds := make([]telego.BotCommand, 0, len(menuCommands))
for _, name := range menuCommands {
cmds = append(cmds, telego.BotCommand{Command: name, Description: b.tr.T(lang, "menu."+name, nil)})
}
params := &telego.SetMyCommandsParams{Commands: cmds}
if lang != b.tr.Langs()[0] {
// The source language is the default menu; the others are
// registered for their own language code.
params.LanguageCode = lang
}
if err := b.api.SetMyCommands(ctx, params); err != nil {
b.log.Warn("setMyCommands failed", "lang", lang, "err", err)
}
}
}
+226
View File
@@ -0,0 +1,226 @@
package bot
import (
"context"
"time"
"github.com/mymmrac/telego"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/i18n"
"github.com/noderunners/dlbot/internal/sched"
"github.com/noderunners/dlbot/internal/tg"
"github.com/noderunners/dlbot/internal/ytdlp"
)
// statusState remembers what a status message shows, so edits that would
// change nothing or come too fast are skipped.
type statusState struct {
text string
phase string
at time.Time
}
// eventLoop reacts to job events and periodically reconciles, which covers
// dropped events and work left over from before a restart.
func (b *Bot) eventLoop(ctx context.Context) {
b.safely("reconcile", func() { b.reconcile(ctx) })
t := time.NewTicker(b.reconcileEvery)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case ev := <-b.events:
b.safely("event", func() { b.handleEvent(ctx, ev) })
case <-t.C:
b.safely("reconcile", func() { b.reconcile(ctx) })
}
}
}
func (b *Bot) handleEvent(ctx context.Context, ev sched.Event) {
switch ev.Type {
case sched.EventStarted, sched.EventProgress, sched.EventRequeued:
b.refreshStatus(ctx, ev.JobID)
case sched.EventStored:
b.goBG("deliver", func() { b.deliverJob(ctx, ev.JobID) })
case sched.EventFailed:
b.failJob(ctx, ev.JobID)
case sched.EventCancelled:
b.cleanupCancelled(ctx, ev.JobID)
}
}
// reconcile brings Telegram in line with the database: it resumes
// deliveries, reports failures, frees stuck uploads and refreshes the
// position shown on queued jobs.
func (b *Bot) reconcile(ctx context.Context) {
if ctx.Err() != nil {
return
}
stale, err := b.store.StaleSendingDeliveries(ctx, db.NowMilli()-staleSending.Milliseconds())
if err != nil {
b.log.Error("reconcile: stale deliveries", "err", err)
}
for _, d := range stale {
if _, err := b.store.TransitionDelivery(ctx, d.ID, db.DeliverySending, db.DeliveryPending, ""); err != nil {
b.log.Error("reconcile: reset delivery", "delivery_id", d.ID, "err", err)
}
}
each := func(status string, fn func(jobID string)) {
jobIDs, err := b.store.PendingDeliveryJobIDs(ctx, status, 200)
if err != nil {
b.log.Error("reconcile: list jobs", "status", status, "err", err)
return
}
for _, id := range jobIDs {
fn(id)
}
}
each(db.JobDelivering, func(id string) { b.goBG("deliver", func() { b.deliverJob(ctx, id) }) })
each(db.JobFailed, func(id string) { b.failJob(ctx, id) })
each(db.JobCancelled, func(id string) { b.cleanupCancelled(ctx, id) })
each(db.JobQueued, func(id string) { b.refreshStatus(ctx, id) })
each(db.JobRunning, func(id string) { b.refreshStatus(ctx, id) })
// Jobs whose requesters were all served but that were never closed.
delivering, err := b.store.JobsByStatus(ctx, db.JobDelivering, 200)
if err != nil {
b.log.Error("reconcile: delivering jobs", "err", err)
return
}
for _, j := range delivering {
b.finishIfServed(ctx, j)
}
}
// staleSending is how long a delivery may sit in "sending" before it is
// assumed to be left over from a crash.
const staleSending = 20 * time.Minute
// refreshStatus updates the status message of every waiting requester of
// a job.
func (b *Bot) refreshStatus(ctx context.Context, jobID string) {
job, err := b.store.GetJob(ctx, jobID)
if err != nil {
return
}
if job.Status != db.JobQueued && job.Status != db.JobRunning {
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 {
text, kb, phase := b.renderStatus(ctx, d, job)
b.setStatus(ctx, d, text, kb, phase, false)
}
}
// renderStatus builds the live status text of a delivery. phase groups
// states that only differ in numbers, which is what throttling keys on.
func (b *Bot) renderStatus(ctx context.Context, d *db.Delivery, job *db.Job) (text string, kb *telego.InlineKeyboardMarkup, phase string) {
lang := d.Lang
head := titleLine(job.Title) + "\n"
cancel := b.cancelJobKeyboard(lang, d.ID)
switch job.Status {
case db.JobQueued:
pos, err := b.sched.Position(ctx, job, b.slots())
if err != nil {
b.log.Error("queue position", "job_id", job.ID, "err", err)
}
return head + b.tr.HTML(lang, "status.queued", i18n.Args{
"Position": pos.Ahead + 1,
"Wait": b.tr.Span(lang, pos.Wait),
}), cancel, "queued"
case db.JobRunning:
switch job.Stage {
case ytdlp.StageProcessing:
return head + b.tr.HTML(lang, "status.processing", nil), cancel, "processing"
case ytdlp.StageUploading:
return head + b.tr.HTML(lang, "status.uploading", nil), cancel, "uploading"
}
switch {
case job.TotalBytes > 0:
ratio := float64(job.ProgressBytes) / float64(job.TotalBytes)
return head + b.tr.HTML(lang, "status.downloading_progress", i18n.Args{
"Bar": bar(ratio),
"Percent": b.tr.Percent(lang, ratio),
"Done": b.tr.Size(lang, job.ProgressBytes),
"Total": b.tr.Size(lang, job.TotalBytes),
}), cancel, "downloading"
case job.ProgressBytes > 0:
return head + b.tr.HTML(lang, "status.downloading_bytes", i18n.Args{
"Done": b.tr.Size(lang, job.ProgressBytes),
}), cancel, "downloading"
}
return head + b.tr.HTML(lang, "status.downloading", nil), cancel, "downloading"
case db.JobDelivering:
return head + b.tr.HTML(lang, "status.uploading", nil), nil, "uploading"
case db.JobDone:
return head + b.tr.HTML(lang, "status.done", nil), nil, "done"
case db.JobCancelled:
return head + b.tr.HTML(lang, "status.cancelled", nil), nil, "cancelled"
default:
return head + b.failureText(lang, job.ErrorCode), nil, "failed"
}
}
// failureText is the user-facing explanation of a failed job.
func (b *Bot) failureText(lang, code string) string {
if code == "" {
code = string(ytdlp.CodeUnknown)
}
return b.tr.HTML(lang, "status.failed", i18n.Args{"Reason": b.tr.T(lang, "error."+code, nil)})
}
// setStatus edits the status message unless nothing changed or the last
// edit of the same phase was too recent. Telegram limits how often a
// message may be edited, and progress numbers are not worth a flood wait.
func (b *Bot) setStatus(ctx context.Context, d *db.Delivery, text string, kb *telego.InlineKeyboardMarkup, phase string, force bool) {
if d.StatusMessageID == 0 {
return
}
now := time.Now()
b.statusMu.Lock()
st := b.statuses[d.ID]
if st != nil {
if st.text == text || (!force && st.phase == phase && now.Sub(st.at) < b.statusMinGap) {
b.statusMu.Unlock()
return
}
}
b.statuses[d.ID] = &statusState{text: text, phase: phase, at: now}
b.statusMu.Unlock()
if err := b.edit(ctx, d.ChatID, d.StatusMessageID, d.StatusIsPhoto, text, kb); err != nil {
if wait := tg.RetryAfter(err); wait > 0 {
// Back off this message for as long as Telegram asked.
b.statusMu.Lock()
if cur := b.statuses[d.ID]; cur != nil {
cur.text = ""
cur.at = now.Add(wait)
}
b.statusMu.Unlock()
}
}
}
// finalStatus writes the last state of a delivery and forgets its
// throttling state. When the status message is gone a new one is sent, so
// the requester always learns the outcome.
func (b *Bot) finalStatus(ctx context.Context, d *db.Delivery, text string) {
b.statusMu.Lock()
delete(b.statuses, d.ID)
b.statusMu.Unlock()
if d.StatusMessageID != 0 {
err := b.edit(ctx, d.ChatID, d.StatusMessageID, d.StatusIsPhoto, text, nil)
if err == nil || !tg.IsMessageGone(err) {
return
}
}
_, _ = b.send(ctx, d.ChatID, d.ReplyToMessageID, text, nil)
}
+107
View File
@@ -0,0 +1,107 @@
package bot
import (
"html"
"strings"
"unicode"
"unicode/utf8"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/i18n"
"github.com/noderunners/dlbot/internal/media"
)
// clip shortens s to at most max bytes without cutting a rune, and without
// leaving an HTML entity or tag half open at the end.
func clip(s string, max int) string {
if len(s) <= max {
return s
}
cut := max - 1
for cut > 0 && !utf8.RuneStart(s[cut]) {
cut--
}
out := s[:cut]
if i := strings.LastIndexAny(out, "<&"); i >= 0 && !strings.ContainsAny(out[i:], ">;") {
out = out[:i]
}
return out + "…"
}
// shorten cuts plain text to a number of runes, adding an ellipsis.
func shorten(s string, runes int) string {
s = strings.TrimSpace(s)
if utf8.RuneCountInString(s) <= runes {
return s
}
r := []rune(s)
return strings.TrimSpace(string(r[:runes-1])) + "…"
}
// titleLine is the bold, escaped title used at the top of cards and
// status messages.
func titleLine(title string) string {
return "<b>" + html.EscapeString(shorten(title, 120)) + "</b>"
}
// fileName builds the name a delivered file gets in Telegram.
func fileName(title, ext string) string {
var sb strings.Builder
for _, r := range title {
switch {
case r == '/' || r == '\\' || r == ':' || r == '*' || r == '?' || r == '"' || r == '<' || r == '>' || r == '|':
sb.WriteRune(' ')
case unicode.IsControl(r):
default:
sb.WriteRune(r)
}
}
name := strings.Join(strings.Fields(sb.String()), " ")
name = strings.Trim(shorten(name, 80), ". ")
if name == "" {
name = "media"
}
if ext == "" {
return name
}
return name + "." + ext
}
// bar renders a ten segment progress bar. It has no words, so it needs no
// translation.
func bar(ratio float64) string {
if ratio < 0 {
ratio = 0
}
if ratio > 1 {
ratio = 1
}
filled := int(ratio*10 + 0.5)
return strings.Repeat("▰", filled) + strings.Repeat("▱", 10-filled)
}
// profileLabel is the human name of a profile, as used on buttons.
func (b *Bot) profileLabel(lang string, p media.Profile) string {
switch {
case p == media.Best:
return b.tr.T(lang, "btn.best", nil)
case p == media.MP3:
return b.tr.T(lang, "btn.mp3", nil)
case p == media.M4A:
return b.tr.T(lang, "btn.m4a", nil)
case p == media.Thumb:
return b.tr.T(lang, "btn.thumb", nil)
case p.Kind() == media.KindSubs:
return b.tr.T(lang, "btn.subs", i18n.Args{"Lang": p.SubLang()})
default:
return b.tr.T(lang, "btn.res", i18n.Args{"Height": p.Height()})
}
}
func jobProfile(j *db.Job) media.Profile {
p, err := media.Parse(j.Profile)
if err != nil {
return media.Best
}
return p
}