package bot
import (
"context"
"errors"
"html"
"strings"
"time"
"unicode/utf8"
"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/tg"
"github.com/noderunners/dlbot/internal/ytdlp"
)
// This file is about what a finished download looks like: the caption and
// the buttons under the file, the status message making way for it, and
// the buttons under an error that offer the next step.
// Callback data of the buttons under a result or an error. Each carries the
// ID of the request the result answers.
const (
cbFollowAudio = "fa" // fa:
cbFollowQuality = "fq" // fq:
cbFollowThumb = "ft" // ft:
cbFollowDelete = "fx" // fx:
cbRetry = "fr" // fr::
cbRetryLookup = "fl" // fl:
cbUpgrade = "up" // up
)
// genericTitles are titles sites give to posts that have none of their own.
var genericTitles = map[string]bool{
"video": true, "untitled": true, "instagram": true, "tiktok": true, "facebook": true,
"reel": true, "post": true, "twitter": true, "x": true, "threads": true, "media": true,
"instagram video": true, "tiktok video": true, "facebook video": true,
}
// genericTitlePrefixes start titles that only say who posted.
var genericTitlePrefixes = []string{"video by ", "post by ", "reel by ", "photo by ", "instagram post by ", "tiktok video #"}
// isGenericTitle reports whether a title says nothing about the content:
// empty, the bare video ID, the uploader's name or a site placeholder.
func isGenericTitle(info *service.CardInfo) bool {
t := strings.ToLower(strings.TrimSpace(info.Title))
if t == "" || t == strings.ToLower(info.VideoID) || genericTitles[t] {
return true
}
if u := strings.ToLower(strings.TrimSpace(info.Uploader)); u != "" && (t == u || t == "@"+u) {
return true
}
for _, p := range genericTitlePrefixes {
if strings.HasPrefix(t, p) {
return true
}
}
return false
}
// uploadDay parses yt-dlp's YYYYMMDD upload date.
func uploadDay(s string) (time.Time, bool) {
if len(s) != 8 {
return time.Time{}, false
}
t, err := time.Parse("20060102", s)
return t, err == nil
}
// displayTitle is a plain text title for people. A generic title becomes
// the uploader and the upload date, such as "nasa · 3 May 2025".
func (b *Bot) displayTitle(lang string, info *service.CardInfo) (title string, generic bool) {
if !isGenericTitle(info) {
return strings.TrimSpace(info.Title), false
}
var parts []string
if u := strings.TrimSpace(info.Uploader); u != "" {
parts = append(parts, u)
}
if day, ok := uploadDay(info.UploadDate); ok {
parts = append(parts, b.tr.Date(lang, day))
}
if len(parts) == 0 {
if info.Site != "" {
return info.Site, true
}
return strings.TrimSpace(info.Title), true
}
return strings.Join(parts, " · "), true
}
// caption is the HTML caption of a delivered file: the title, who posted
// it and how long it is, a short link to the source without tracking
// parameters, and optionally the bot's name.
func (b *Bot) caption(lang string, info *service.CardInfo, url string, profile media.Profile) string {
title, generic := b.displayTitle(lang, info)
var lines []string
if title != "" {
lines = append(lines, titleLine(title))
}
var facts []string
if u := strings.TrimSpace(info.Uploader); u != "" && !generic {
facts = append(facts, html.EscapeString(shorten(u, 40)))
}
if info.Duration > 0 && profile.Kind() != media.KindThumb && profile.Kind() != media.KindSubs {
facts = append(facts, i18n.Clock(info.Duration))
}
if len(facts) > 0 {
lines = append(lines, strings.Join(facts, " · "))
}
if url != "" {
clean := links.Clean(url)
lines = append(lines, ``+html.EscapeString(links.Short(clean, 40))+``)
}
if b.cfg.CaptionAttribution && b.username != "" {
lines = append(lines, b.tr.HTML(lang, "caption.via", i18n.Args{"Bot": b.username}))
}
return strings.Join(lines, "\n")
}
// resultKeyboard is the row of next steps under a delivered file. Only
// what makes sense for the file is offered: no MP3 of an MP3.
func (b *Bot) resultKeyboard(lang string, req *db.Request, info *service.CardInfo, profile media.Profile) *telego.InlineKeyboardMarkup {
if req == nil {
return nil
}
id := req.ID
del := button(b.tr.T(lang, "btn.delete", nil), cbData(cbFollowDelete, id))
other := button(b.tr.T(lang, "btn.other_quality", nil), cbData(cbFollowQuality, id))
switch profile.Kind() {
case media.KindVideo:
var first, second []telego.InlineKeyboardButton
if info.HasAudio {
first = append(first, button(b.tr.T(lang, "btn.result_audio", nil), cbData(cbFollowAudio, id)))
}
first = append(first, other)
if info.Thumbnail != "" {
second = append(second, button(b.profileLabel(lang, media.Thumb), cbData(cbFollowThumb, id)))
}
second = append(second, del)
return keyboard(first, second)
case media.KindAudio:
return keyboard([]telego.InlineKeyboardButton{other, del})
}
return keyboard([]telego.InlineKeyboardButton{del})
}
// retireStatus removes the status message of a delivery once its file is
// in the chat, so one message per download remains. When Telegram does not
// let it go, it is cut down to a short line instead.
func (b *Bot) retireStatus(ctx context.Context, d *db.Delivery, resultID int64) {
b.forgetStatus(d.ID)
b.liveMu.Lock()
delete(b.live, d.ID)
delete(b.liveTried, d.ID)
b.liveMu.Unlock()
// A status widget may have replaced the message since d was loaded.
if cur, err := b.store.GetDelivery(context.WithoutCancel(ctx), d.ID); err == nil {
d.StatusMessageID, d.StatusIsPhoto = cur.StatusMessageID, cur.StatusIsPhoto
}
if d.StatusMessageID == 0 || d.StatusMessageID == resultID {
return
}
err := b.api.DeleteMessage(ctx, &telego.DeleteMessageParams{ChatID: chatID(d.ChatID), MessageID: int(d.StatusMessageID)})
if err == nil || tg.IsMessageGone(err) {
return
}
b.log.Debug("status message not deleted, shortening it", "delivery_id", d.ID, "err", err)
_ = b.edit(ctx, d.ChatID, d.StatusMessageID, d.StatusIsPhoto, b.tr.HTML(d.Lang, "status.sent", nil), nil)
}
// --- buttons under a result ---------------------------------------------------
// ownRequest loads the request behind a result or error button and checks
// that the person pressing it is the one who asked. In a group everyone
// sees the buttons; only the requester may use them.
func (b *Bot) ownRequest(ctx context.Context, q *telego.CallbackQuery, act actor, requestID string) (*db.Request, bool) {
req, err := b.store.GetRequest(ctx, requestID)
if err != nil {
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
return nil, false
}
if req.UserID != act.user.ID {
b.answer(ctx, q, b.tr.T(act.lang, "notice.not_yours", nil), false)
return nil, false
}
return req, true
}
// pressedIn returns the chat a button was pressed in and the message it
// sits under.
func pressedIn(q *telego.CallbackQuery, req *db.Request) (chat int64, chatType string, messageID int64) {
if q.Message == nil {
return req.ChatID, req.ChatType, 0
}
c := q.Message.GetChat()
return c.ID, c.Type, int64(q.Message.GetMessageID())
}
// cbFollow starts another format of a past result: the MP3 or the
// thumbnail. It is a new download with the usual limits.
func (b *Bot) cbFollow(ctx context.Context, q *telego.CallbackQuery, act actor, requestID string, profile media.Profile) {
req, ok := b.ownRequest(ctx, q, act, requestID)
if !ok {
return
}
info, err := service.ParseCardInfo(req.Info)
if err != nil {
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
return
}
b.answer(ctx, q, "", false)
chat, chatType, msgID := pressedIn(q, req)
b.startAgain(ctx, act, chat, chatType, msgID, req, info, profile)
}
// cbRetryDownload is "Try again" under a failed download.
func (b *Bot) cbRetryDownload(ctx context.Context, q *telego.CallbackQuery, act actor, requestID, profileArg string) {
req, ok := b.ownRequest(ctx, q, act, requestID)
if !ok {
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
}
b.answer(ctx, q, "", false)
chat, chatType, msgID := pressedIn(q, req)
// The error message turns back into the status of the new attempt.
b.deleteMessage(ctx, chat, msgID)
b.startAgain(ctx, act, chat, chatType, req.SourceMessageID, req, info, profile)
}
// cbRetryLookup is "Try again" under a link that could not be looked up.
func (b *Bot) cbRetryLookup(ctx context.Context, q *telego.CallbackQuery, act actor, requestID string) {
req, ok := b.ownRequest(ctx, q, act, requestID)
if !ok {
return
}
chat, chatType, msgID := pressedIn(q, req)
if !b.rate.allow("u:"+itoa(act.user.ID), b.cfg.Rate.UserPerMinute, time.Minute) {
b.answer(ctx, q, b.tr.T(act.lang, "notice.rate_limited", nil), true)
return
}
b.answer(ctx, q, "", false)
lr := linkRequest{
chatID: chat, chatType: chatType, sourceID: req.SourceMessageID, act: act, url: req.URL,
preset: presetFor(act, act.group), messageID: msgID,
}
b.goBG("link", func() { b.linkFlow(ctx, lr) })
}
// cbOtherQuality shows the format card again for a past result, or for a
// download that was too big.
func (b *Bot) cbOtherQuality(ctx context.Context, q *telego.CallbackQuery, act actor, requestID string) {
orig, ok := b.ownRequest(ctx, q, act, requestID)
if !ok {
return
}
info, err := service.ParseCardInfo(orig.Info)
if err != nil {
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
return
}
b.answer(ctx, q, "", false)
chat, chatType, msgID := pressedIn(q, orig)
info.Fresh = false
req := &db.Request{
ID: ids.New(), UserID: act.user.ID, ChatID: chat, ChatType: chatType, URL: orig.URL,
SourceMessageID: msgID, Status: db.RequestReady, Info: info.JSON(), Lang: act.lang,
}
if err := b.store.InsertRequest(ctx, req); err != nil {
b.internalError(ctx, chat, act, err)
return
}
b.showCard(ctx, act.lang, req, info, 0, "")
}
// cbDeleteResult removes the message the button is under.
func (b *Bot) cbDeleteResult(ctx context.Context, q *telego.CallbackQuery, act actor, requestID string) {
req, ok := b.ownRequest(ctx, q, act, requestID)
if !ok {
return
}
chat, _, msgID := pressedIn(q, req)
if msgID == 0 {
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
return
}
if err := b.api.DeleteMessage(ctx, &telego.DeleteMessageParams{ChatID: chatID(chat), MessageID: int(msgID)}); err != nil && !tg.IsMessageGone(err) {
// Older than 48 hours: Telegram keeps it.
b.answer(ctx, q, b.tr.T(act.lang, "notice.cannot_delete", nil), true)
return
}
b.answer(ctx, q, "", false)
}
// cbShowUpgrade is "Upgrade" under an error: the buy screen.
func (b *Bot) cbShowUpgrade(ctx context.Context, q *telego.CallbackQuery, act actor) {
if q.Message != nil && !isPrivate(q.Message.GetChat().Type) {
// Invoices are personal: open the private chat.
if err := b.api.AnswerCallbackQuery(ctx, &telego.AnswerCallbackQueryParams{
CallbackQueryID: q.ID, URL: "https://t.me/" + b.username + "?start=buy",
}); err != nil {
b.answer(ctx, q, b.tr.T(act.lang, "notice.private_only", nil), true)
}
return
}
b.answer(ctx, q, "", false)
b.showBuy(ctx, act.user.ID, act)
}
// startAgain starts a known link in a chat with a new status message,
// under the usual limits. Resends and follow-ups go through here.
func (b *Bot) startAgain(ctx context.Context, act actor, chat int64, chatType string, replyTo int64, orig *db.Request, info *service.CardInfo, profile media.Profile) {
lang := act.lang
info.Fresh = false
req := &db.Request{
ID: ids.New(), UserID: act.user.ID, ChatID: chat, ChatType: chatType, URL: orig.URL,
SourceMessageID: replyTo, Status: db.RequestReady, Info: info.JSON(), Lang: lang,
}
msg, err := b.send(ctx, chat, replyTo, titleLine(info.Title)+"\n"+b.tr.HTML(lang, "status.preparing", nil), nil)
if err != nil {
return
}
req.CardMessageID = int64(msg.MessageID)
if err := b.store.InsertRequest(ctx, req); err != nil {
b.internalError(ctx, chat, act, err)
return
}
err = b.startFromRequest(ctx, req, info, profile, nil)
var le *service.LimitError
switch {
case err == nil:
case errors.As(err, &le) && le.Upgradable:
b.deleteMessage(ctx, chat, req.CardMessageID)
b.offerUpgrade(ctx, chat, replyTo, lang, req, profile, le, isPrivate(chatType))
default:
b.showStartError(ctx, req, info, profile, req.CardMessageID, false, err)
}
}
// showStartError turns a message into the reason a download could not
// start, with the buttons that may help.
func (b *Bot) showStartError(ctx context.Context, req *db.Request, info *service.CardInfo, profile media.Profile, messageID int64, isPhoto bool, err error) {
lang := req.Lang
code := "internal"
var le *service.LimitError
if errors.As(err, &le) {
code = le.Code
}
text := titleLine(info.Title) + "\n" + html.EscapeString(b.startErrorText(lang, err))
_ = b.edit(ctx, req.ChatID, messageID, isPhoto, text, b.errorKeyboard(lang, req, profile, code))
}
// --- buttons under an error -----------------------------------------------------
// transientCodes are failures that may well work a moment later.
var transientCodes = map[string]bool{
string(ytdlp.CodeRateLimited): true, string(ytdlp.CodeSiteBlocked): true, string(ytdlp.CodeNetwork): true,
string(ytdlp.CodeTimeout): true, string(ytdlp.CodeWorkerLost): true, string(ytdlp.CodeInternal): true,
string(ytdlp.CodeUnknown): true, string(ytdlp.CodeProcessing): true, "send_failed": true,
}
// contentCodes are failures that come from the content itself.
var contentCodes = map[string]bool{
string(ytdlp.CodePrivate): true, string(ytdlp.CodeLoginRequired): true, string(ytdlp.CodeGeoBlocked): true,
string(ytdlp.CodeUnsupported): true, string(ytdlp.CodeNotFound): true, string(ytdlp.CodeDRM): true,
string(ytdlp.CodeLive): true, service.LimitLive: true, service.LimitBlocked: true,
}
// errorKeyboard offers the next step after a failure: try again after a
// passing problem, a smaller quality or an upgrade after a limit, the app
// otherwise. req is the request that failed; for a failed lookup its info
// is empty and "Try again" repeats the lookup.
func (b *Bot) errorKeyboard(lang string, req *db.Request, profile media.Profile, code string) *telego.InlineKeyboardMarkup {
if req == nil {
return nil
}
private := isPrivate(req.ChatType)
var row []telego.InlineKeyboardButton
switch {
case transientCodes[code]:
data := cbData(cbRetryLookup, req.ID)
if profile != "" {
data = cbData(cbRetry, req.ID, string(profile))
}
row = append(row, button(b.tr.T(lang, "btn.try_again", nil), data))
case code == string(ytdlp.CodeTooLarge) || code == service.LimitTooLarge:
if profile.Kind() == media.KindVideo && profile != media.P480 {
row = append(row, button(b.tr.T(lang, "btn.smaller_quality", nil), cbData(cbFollowQuality, req.ID)))
}
row = append(row, b.upgradeButton(lang, private)...)
case code == string(ytdlp.CodeTooLong) || code == service.LimitTooLong ||
code == service.LimitDailyDownloads || code == service.LimitDailyVolume:
row = append(row, b.upgradeButton(lang, private)...)
case contentCodes[code]:
if btn, ok := b.appButton(lang, private, ""); ok {
row = append(row, btn)
}
}
if len(row) == 0 {
return nil
}
return keyboard(row)
}
// upgradeButton is "Upgrade", when there is something to buy.
func (b *Bot) upgradeButton(lang string, private bool) []telego.InlineKeyboardButton {
if !b.bill.Selling() {
return nil
}
if !private {
return []telego.InlineKeyboardButton{urlButton(b.tr.T(lang, "btn.upgrade", nil), "https://t.me/"+b.username+"?start=buy")}
}
return []telego.InlineKeyboardButton{button(b.tr.T(lang, "btn.upgrade", nil), cbUpgrade)}
}
// appButton opens the Mini App, at an optional page. In a private chat it
// opens in place; in a group it has to be a link, because web app buttons
// do not work there.
func (b *Bot) appButton(lang string, private bool, page string) (telego.InlineKeyboardButton, bool) {
if !b.cfg.MiniAppEnabled() {
return telego.InlineKeyboardButton{}, false
}
label := b.tr.T(lang, "btn.open_app", nil)
if !private {
return urlButton(label, "https://t.me/"+b.username+"?startapp"), true
}
url := b.cfg.PublicURL + "/app/"
if page != "" {
url += "?page=" + page
}
return telego.InlineKeyboardButton{Text: label, WebApp: &telego.WebAppInfo{URL: url}}, true
}
// alreadySent answers a link this user got in this chat a moment ago with
// a pointer and a button to send it again. Sending again is a new
// download under the usual limits.
func (b *Bot) alreadySent(ctx context.Context, lr linkRequest) bool {
since := time.Now().Add(-recentWindow).UnixMilli()
recent, err := b.store.RecentSent(ctx, lr.act.user.ID, lr.chatID, since, 20)
if err != nil {
b.log.Error("recent deliveries", "err", err)
return false
}
want := links.Clean(lr.url)
for _, r := range recent {
if links.Clean(r.URL) != want {
continue
}
title := r.Title
if utf8.RuneCountInString(title) == 0 {
title = links.Short(want, 40)
}
kb := keyboard([]telego.InlineKeyboardButton{button(b.tr.T(lr.act.lang, "btn.send_again", nil), cbData(cbResend, r.DeliveryID))})
_, _ = b.send(ctx, lr.chatID, lr.sourceID, titleLine(title)+"\n"+b.tr.HTML(lr.act.lang, "dup.already_sent", nil), kb)
return true
}
return false
}
// recentWindow is how long a sent link counts as "already sent".
const recentWindow = 10 * time.Minute