Files
Media-download-telegram-bot/internal/bot/card.go
T
MichilisandClaude Fable 5.2 51371da0e0 Phase 5: groups
Group wallets, group passes, spending rules and admin-only settings.

- Groups recorded from my_chat_member; admin rights verified with
  getChatMember and cached for five minutes
- Group context in entitlement resolution: group pass, group credits under
  the spending rule (anyone, admins only, capped per person per day) and
  the group's daily cap; refunds go back to the wallet that paid
- Group gate before any lookup: bot on or off, who may use it, allowed
  and blocked sites, plus the owner's maintenance mode
- /settings with inline toggles checked on every press, /grouplang,
  /autodetect, /allow, /block, /spending, /groupwallet, /grouppass,
  /groupstats
- Deep links with the target pre-selected: paying for a group happens in
  the private chat; a refused download in a group offers "Buy for me" and
  "Add group credits"
- Optional link detection, tidy mode, default quality and language per
  group; per-member usage
- /quality, /language, /app, /privacy, /terms, /support
- Remaining owner tools: /stats, /queue all, /user, /group, /ban, /unban,
  /grant (passes and gift codes), /credit, /refund, /blocklist,
  /broadcast with confirmation, /maint, /reload i18n

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

296 lines
9.5 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
}
// 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))
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.edit(ctx, lr.chatID, phID, false, b.probeErrorText(lang, err), nil)
}
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,
}
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
}
if lr.subs {
b.subsCard(ctx, lr, phID, req, info)
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(context.WithoutCancel(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)
}
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
}