Files
Media-download-telegram-bot/internal/bot/card.go
T
MichilisandClaude Opus 5.5 6843053582 Phase 1: quick flow fixes
- One message per job: the status message is deleted once the file is
  sent, or shortened to "Sent." when Telegram keeps it.
- No reply quotes in private chats; groups keep them.
- Queue status only mentions the position when the wait is above
  QUEUE_NOTICE_THRESHOLD_SECONDS or somebody is ahead. Status edits are
  throttled to one per 2.5 s per message; a state that arrives too soon
  is shown later instead of dropped. The wait estimate is 0 with a free
  slot.
- Caption with title (uploader and date when generic), uploader,
  duration, a short source link without tracking parameters and an
  optional "via @bot" line (CAPTION_ATTRIBUTION). Uploaded videos get a
  320 px JPEG thumbnail; merged MP4s are written with faststart.
- Buttons under the result: Audio (MP3), Other quality, Thumbnail,
  Delete. Requester only in groups.
- Language resolved once per update and passed in the context. A
  fallback to English is logged as a bug; a test walks every screen in
  Spanish and Dutch. Language picker on the first /start.
- Sizes without a zero decimal ("50 MB").
- First link of a new user shows the card once and sets the default to
  "best that fits my limit".
- Errors offer the next step (Try again, Smaller quality, Upgrade, Open
  app); passing lookup failures are retried once.
- Up to MULTI_LINK_MAX links per message; a link sent a moment ago gets
  "already sent" with a Send again button.
- Mini App menu button, labelled per private chat in the user's
  language.
- Personal /settings in private chats with an "Add me to a group"
  button.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 20:08:58 +00:00

393 lines
13 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
// fresh skips the cache and downloads again.
fresh bool
// subs shows the subtitle languages instead of the format buttons.
subs bool
// checkRecent answers "already sent" for a link this user got a
// moment ago, instead of downloading it again.
checkRecent bool
// messageID, when set, is an existing message to use as the status,
// such as the error message a "Try again" button sits under.
messageID int64
}
// 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
}
// Whether the requester may use the bot here at all is settled before
// anything is looked up: maintenance, and a group's own rules.
who := service.Who{UserID: lr.act.user.ID, ChatID: lr.chatID, ChatType: lr.chatType}
if err := b.svc.Gate(ctx, who); err != nil {
b.refuse(ctx, lr.chatID, lr.sourceID, lr.act.lang, err)
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))
if lr.checkRecent && !lr.fresh && b.alreadySent(ctx, lr) {
return
}
phID := lr.messageID
if phID != 0 {
_ = b.edit(ctx, lr.chatID, phID, false, b.tr.HTML(lang, "card.looking", nil), nil)
} else {
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)
}
probed, err := b.svc.ProbeAny(ctx, lr.url)
if err != nil {
if ctx.Err() == nil {
b.lookupFailed(ctx, lr, phID, err)
}
return
}
if probed.Playlist != nil {
b.playlistCard(ctx, lr, phID, probed.Playlist)
return
}
info := probed.Info
if lr.fresh {
cp := *info
cp.Fresh = true
info = &cp
}
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,
}
preset := lr.preset
if lr.subs {
preset = ""
}
if preset == presetFit {
preset = b.fitProfile(ctx, lr, info)
}
if 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 preset != "" {
job, _, err := b.svc.Start(ctx, service.StartParams{
Request: req, Info: info, Profile: preset,
StatusMessageID: phID, ReplyToMessageID: lr.sourceID,
})
if err != nil {
// Give the request back, so the offer and the buttons under the
// error can still use it.
if _, rerr := b.store.TransitionRequest(ctx, req.ID, db.RequestChosen, db.RequestReady); rerr != nil {
log.Error("release request", "err", rerr)
}
var le *service.LimitError
if errors.As(err, &le) && le.Upgradable {
b.deleteMessage(ctx, lr.chatID, phID)
b.offerUpgrade(ctx, lr.chatID, lr.sourceID, lang, req, preset, le, isPrivate(lr.chatType))
return
}
b.showStartError(ctx, req, info, preset, phID, false, err)
return
}
b.refreshStatus(ctx, job.ID)
return
}
if lr.subs {
b.subsCard(ctx, lr, phID, req, info)
return
}
// A first link from someone who never picked a default: show the card
// this once, and make "best that fits my limit" their default.
note := ""
if isPrivate(lr.chatType) && lr.act.user.Quality == qualityUnset && lr.preset == "" {
if err := b.store.SetUserQuality(context.WithoutCancel(ctx), lr.act.user.ID, qualityFit); err != nil {
log.Error("set first default quality", "err", err)
} else {
note = b.tr.HTML(lang, "card.first_run", nil)
}
}
b.showCard(ctx, lang, req, info, phID, note)
}
// showCard shows the format card of a request: a photo with the
// thumbnail when Telegram can fetch it, text otherwise. replaceID is a
// message to turn into the card (or delete, once the photo is out); 0
// sends a new one.
func (b *Bot) showCard(ctx context.Context, lang string, req *db.Request, info *service.CardInfo, replaceID int64, note string) {
text := b.cardText(lang, info, true)
if note != "" {
text += "\n\n" + note
}
kb := b.cardKeyboard(lang, req.ID, info)
if info.Thumbnail != "" {
msg, err := b.api.SendPhoto(ctx, &telego.SendPhotoParams{
ChatID: chatID(req.ChatID),
Photo: telego.InputFile{URL: info.Thumbnail},
Caption: clip(text, 1024),
ParseMode: telego.ModeHTML,
ReplyParameters: replyParams(req.ChatID, req.SourceMessageID),
ReplyMarkup: kb,
})
if err == nil {
if err := b.store.SetRequestCard(context.WithoutCancel(ctx), req.ID, int64(msg.MessageID), true); err != nil {
b.log.Error("save card", "request_id", req.ID, "err", err)
}
b.deleteMessage(ctx, req.ChatID, replaceID)
return
}
// Telegram could not fetch the thumbnail. The text card still works.
b.log.Debug("photo card failed, using text card", "err", err)
}
if replaceID != 0 {
_ = b.edit(ctx, req.ChatID, replaceID, false, text, kb)
return
}
msg, err := b.send(ctx, req.ChatID, req.SourceMessageID, text, kb)
if err == nil {
if err := b.store.SetRequestCard(context.WithoutCancel(ctx), req.ID, int64(msg.MessageID), false); err != nil {
b.log.Error("save card", "request_id", req.ID, "err", err)
}
}
}
// fitProfile picks "the best quality that fits my limit" for a looked up
// link. When nothing fits, the smallest quality is returned and the start
// is refused by the usual limit check, which leads to the over-limit offer.
func (b *Bot) fitProfile(ctx context.Context, lr linkRequest, info *service.CardInfo) media.Profile {
who := service.Who{UserID: lr.act.user.ID, ChatID: lr.chatID, ChatType: lr.chatType}
dec, err := b.svc.Entitlement(ctx, who, false)
if err != nil {
return media.Best
}
p, _ := service.BestFit(info, min64(dec.Limits.MaxSize, b.cfg.MaxUploadBytes()))
return p
}
// lookupFailed explains a link that could not be looked up. The request is
// kept, failed, so that "Try again" knows the link.
func (b *Bot) lookupFailed(ctx context.Context, lr linkRequest, messageID int64, err error) {
lang := lr.act.lang
code := string(ytdlp.CodeOf(err))
if errors.Is(err, service.ErrPlaylist) {
code = "playlist"
}
req := &db.Request{
ID: ids.New(), UserID: lr.act.user.ID, ChatID: lr.chatID, ChatType: lr.chatType,
SourceMessageID: lr.sourceID, CardMessageID: messageID, URL: lr.url,
Status: db.RequestFailed, Lang: lang,
}
var kb *telego.InlineKeyboardMarkup
if ierr := b.store.InsertRequest(ctx, req); ierr == nil {
kb = b.errorKeyboard(lang, req, "", code)
} else {
b.log.Error("insert failed request", "err", ierr)
}
_ = b.edit(ctx, lr.chatID, messageID, false, b.probeErrorText(lang, err), 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
}